From ada014929b01af5ce8ca5e6fdd13401bc3c392f5 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 14 Oct 2010 13:24:26 -0300 Subject: Use ActiveSupport::WeakHash for MRI, JRuby prefers Weakling. --- activesupport/lib/active_support/weak_hash.rb | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 activesupport/lib/active_support/weak_hash.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/weak_hash.rb b/activesupport/lib/active_support/weak_hash.rb new file mode 100644 index 0000000000..c6bf098074 --- /dev/null +++ b/activesupport/lib/active_support/weak_hash.rb @@ -0,0 +1,46 @@ +module ActiveSupport + class WeakHash + def initialize(cache = Hash.new) + @cache = cache + @key_map = {} + @rev_cache = Hash.new{|h,k| h[k] = {}} + @reclaim_value = lambda do |value_id| + if value = @rev_cache.delete(value_id) + value.each_key{|key| @cache.delete key} + end + end + end + + def [](key) + value_id = @cache[key] + value_id && ObjectSpace._id2ref(value_id) + rescue RangeError + nil + end + + def []=(key, value) + key2 = case key + when Fixnum, Symbol, true, false, nil + key + else + key.dup + end + + @rev_cache[value.object_id][key2] = true + @cache[key2] = value.object_id + @key_map[key.object_id] = key2 + + ObjectSpace.define_finalizer(value, @reclaim_value) + end + + def clear + @cache.clear + end + + def delete(key) + @cache.delete(key) + end + end +end + +ActiveSupport::WeakHash = ::Weakling::WeakHash if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' -- cgit v1.2.3 From 0873d1e944147b0f4b15e742fa9df0776a024d51 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 14 Oct 2010 13:35:05 -0300 Subject: Use conditional to avoid warnings. --- activesupport/lib/active_support/weak_hash.rb | 70 ++++++++++++++------------- 1 file changed, 36 insertions(+), 34 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/weak_hash.rb b/activesupport/lib/active_support/weak_hash.rb index c6bf098074..171e38f9d8 100644 --- a/activesupport/lib/active_support/weak_hash.rb +++ b/activesupport/lib/active_support/weak_hash.rb @@ -1,46 +1,48 @@ module ActiveSupport - class WeakHash - def initialize(cache = Hash.new) - @cache = cache - @key_map = {} - @rev_cache = Hash.new{|h,k| h[k] = {}} - @reclaim_value = lambda do |value_id| - if value = @rev_cache.delete(value_id) - value.each_key{|key| @cache.delete key} + if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' + WeakHash = ::Weakling::WeakHash + else + class WeakHash + def initialize(cache = Hash.new) + @cache = cache + @key_map = {} + @rev_cache = Hash.new{|h,k| h[k] = {}} + @reclaim_value = lambda do |value_id| + if value = @rev_cache.delete(value_id) + value.each_key{|key| @cache.delete key} + end end end - end - def [](key) - value_id = @cache[key] - value_id && ObjectSpace._id2ref(value_id) - rescue RangeError - nil - end + def [](key) + value_id = @cache[key] + value_id && ObjectSpace._id2ref(value_id) + rescue RangeError + nil + end - def []=(key, value) - key2 = case key - when Fixnum, Symbol, true, false, nil - key - else - key.dup - end + def []=(key, value) + key2 = case key + when Fixnum, Symbol, true, false, nil + key + else + key.dup + end - @rev_cache[value.object_id][key2] = true - @cache[key2] = value.object_id - @key_map[key.object_id] = key2 + @rev_cache[value.object_id][key2] = true + @cache[key2] = value.object_id + @key_map[key.object_id] = key2 - ObjectSpace.define_finalizer(value, @reclaim_value) - end + ObjectSpace.define_finalizer(value, @reclaim_value) + end - def clear - @cache.clear - end + def clear + @cache.clear + end - def delete(key) - @cache.delete(key) + def delete(key) + @cache.delete(key) + end end end end - -ActiveSupport::WeakHash = ::Weakling::WeakHash if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' -- cgit v1.2.3 From 4da31d21bc0fe10fc329eb6d89ba52b27f8ed25e Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 14 Oct 2010 15:11:06 -0300 Subject: Add initial tests for WeakHash. --- activesupport/test/weak_hash_test.rb | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 activesupport/test/weak_hash_test.rb (limited to 'activesupport') diff --git a/activesupport/test/weak_hash_test.rb b/activesupport/test/weak_hash_test.rb new file mode 100644 index 0000000000..7d1620dc34 --- /dev/null +++ b/activesupport/test/weak_hash_test.rb @@ -0,0 +1,33 @@ +require 'abstract_unit' +require 'active_support/weak_hash' + +class WeakHashTest < ActiveSupport::TestCase + + def setup + @weak_hash = ActiveSupport::WeakHash.new + @str = "A"; + @obj = Object.new + end + + test "allows us to assign value, and return assigned value" do + a = @str; b = @obj + assert_equal @weak_hash[a] = b, b + end + + test "should allow us to assign and read value" do + a = @str; b = @obj + assert_equal @weak_hash[a] = b, b + assert_equal @weak_hash[a], b + end + + test "should use object_id to identify objects" do + a = Object.new + @weak_hash[a] = "b" + assert_nil @weak_hash[a.dup] + end + + test "should find objects that have same hash" do + @weak_hash["a"] = "b" + assert_equal "b", @weak_hash["a"] + end +end -- cgit v1.2.3 From a84add0c2c4afa86feec94e63f2d17e49269ce31 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Sat, 30 Oct 2010 10:48:36 -0300 Subject: We don't need to dup key, since only value is weak. --- activesupport/lib/active_support/weak_hash.rb | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/weak_hash.rb b/activesupport/lib/active_support/weak_hash.rb index 171e38f9d8..d6096e606e 100644 --- a/activesupport/lib/active_support/weak_hash.rb +++ b/activesupport/lib/active_support/weak_hash.rb @@ -22,16 +22,9 @@ module ActiveSupport end def []=(key, value) - key2 = case key - when Fixnum, Symbol, true, false, nil - key - else - key.dup - end - - @rev_cache[value.object_id][key2] = true - @cache[key2] = value.object_id - @key_map[key.object_id] = key2 + @rev_cache[value.object_id][key] = true + @cache[key] = value.object_id + @key_map[key.object_id] = key ObjectSpace.define_finalizer(value, @reclaim_value) end -- cgit v1.2.3 From ad14926b44596f090c0ef060c1b2c2dde4c71016 Mon Sep 17 00:00:00 2001 From: zhengjia Date: Fri, 17 Dec 2010 18:54:57 -0600 Subject: Fix the example in ActiveSupport::Concern --- activesupport/lib/active_support/concern.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb index ac94d12e5e..81fb859334 100644 --- a/activesupport/lib/active_support/concern.rb +++ b/activesupport/lib/active_support/concern.rb @@ -3,7 +3,7 @@ module ActiveSupport # # module M # def self.included(base) - # base.extend, ClassMethods + # base.extend ClassMethods # base.send(:include, InstanceMethods) # scope :disabled, where(:disabled => true) # end -- cgit v1.2.3 From 435bccda930e4dde3d0fafca958e1c8330b4c3ca Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 19 Dec 2010 15:58:58 -0800 Subject: Replace AD::Callbacks.to_prepare with AD::Reloader.to_prepare MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activesupport/lib/active_support/file_update_checker.rb | 2 +- activesupport/lib/active_support/i18n_railtie.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb index cd658fe173..a97e9d7daf 100644 --- a/activesupport/lib/active_support/file_update_checker.rb +++ b/activesupport/lib/active_support/file_update_checker.rb @@ -8,7 +8,7 @@ module ActiveSupport # I18n.reload! # end # - # ActionDispatch::Callbacks.to_prepare do + # ActionDispatch::Reloader.to_prepare do # i18n_reloader.execute_if_updated # end # diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb index f8a5616a76..282337d373 100644 --- a/activesupport/lib/active_support/i18n_railtie.rb +++ b/activesupport/lib/active_support/i18n_railtie.rb @@ -19,7 +19,7 @@ module I18n # on to_prepare callbacks. This will only happen on the config.after_initialize # callback below. initializer "i18n.callbacks" do - ActionDispatch::Callbacks.to_prepare do + ActionDispatch::Reloader.to_prepare do I18n::Railtie.reloader.execute_if_updated end end -- cgit v1.2.3 From 1cacb08b213e9d0f92cf1fad89ff10141211bce8 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 20 Dec 2010 11:50:47 +1000 Subject: Improve documentation on ActiveSupport::Deprecation. --- activesupport/lib/active_support/deprecation.rb | 2 +- activesupport/lib/active_support/deprecation/behaviors.rb | 7 +++++++ activesupport/lib/active_support/deprecation/reporting.rb | 8 +++++++- 3 files changed, 15 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb index e1b8211d68..e3e63ce316 100644 --- a/activesupport/lib/active_support/deprecation.rb +++ b/activesupport/lib/active_support/deprecation.rb @@ -4,7 +4,7 @@ require 'active_support/deprecation/method_wrappers' require 'active_support/deprecation/proxy_wrappers' module ActiveSupport - module Deprecation #:nodoc: + module Deprecation class << self # The version the deprecated behavior will be removed, by default. attr_accessor :deprecation_horizon diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb index f54f65dcf0..da4af339fc 100644 --- a/activesupport/lib/active_support/deprecation/behaviors.rb +++ b/activesupport/lib/active_support/deprecation/behaviors.rb @@ -7,10 +7,17 @@ module ActiveSupport # Whether to print a backtrace along with the warning. attr_accessor :debug + # Returns the set behaviour or if one isn't set, defaults to +:stderr+ def behavior @behavior ||= [DEFAULT_BEHAVIORS[:stderr]] end + # Sets the behaviour to the specified value. Can be a single value or an array. + # + # Examples + # + # ActiveSupport::Deprecation.behavior = :stderr + # ActiveSupport::Deprecation.behavior = [:stderr, :log] def behavior=(behavior) @behavior = Array.wrap(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b } end diff --git a/activesupport/lib/active_support/deprecation/reporting.rb b/activesupport/lib/active_support/deprecation/reporting.rb index 6a7b11c7e0..c7723d139b 100644 --- a/activesupport/lib/active_support/deprecation/reporting.rb +++ b/activesupport/lib/active_support/deprecation/reporting.rb @@ -2,7 +2,13 @@ module ActiveSupport module Deprecation class << self attr_accessor :silenced - + + # Outputs a deprecation warning to the output configured by ActiveSupport::Deprecation.behavior + # + # Example: + # + # ActiveSupport::Deprecation.warn("something broke!") + # #=> "DEPRECATION WARNING: something broke! (called from your_code.rb:1)" def warn(message = nil, callstack = caller) return if silenced deprecation_message(callstack, message).tap do |m| -- cgit v1.2.3 From 3c1a0a8b62cafe50a9098fa1f925db25c6c63767 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 13 Dec 2010 22:13:33 -0500 Subject: expand on set_callback method to explain that in some cases an implicit :before is assumed --- activesupport/lib/active_support/callbacks.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 844237fe6a..32ebea8571 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -447,6 +447,10 @@ module ActiveSupport # set_callback :save, :after, :after_meth, :if => :condition # set_callback :save, :around, lambda { |r| stuff; yield; stuff } # + # If the second argument is not :before, :after or :around then an implicit :before is assumed. + # It means the first example mentioned above can also be written as: + # set_callback :save, :before_meth + # # Use skip_callback to skip any defined one. # # When creating or skipping callbacks, you can specify conditions that -- cgit v1.2.3 From 9b4622a483319f3d1e7f4489442f0d86afb6da36 Mon Sep 17 00:00:00 2001 From: John Paul Ashenfelter Date: Tue, 30 Nov 2010 13:48:25 -0500 Subject: Added a word boundary to uncountable inflection regex for #singularize so short inflections like ors do not affect larger words like sponsors [#6093 state:resolved] --- .../lib/active_support/inflector/inflections.rb | 2 +- activesupport/test/inflector_test.rb | 27 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb index 3caf78bc7d..e136e4c5b3 100644 --- a/activesupport/lib/active_support/inflector/inflections.rb +++ b/activesupport/lib/active_support/inflector/inflections.rb @@ -148,7 +148,7 @@ module ActiveSupport def singularize(word) result = word.to_s.dup - if inflections.uncountables.any? { |inflection| result =~ /#{inflection}\Z/i } + if inflections.uncountables.any? { |inflection| result =~ /\b(#{inflection})\Z/i } result else inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index 2990177bed..e8fe635c03 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -21,6 +21,33 @@ class InflectorTest < Test::Unit::TestCase def test_pluralize_empty_string assert_equal "", ActiveSupport::Inflector.pluralize("") end + + ActiveSupport::Inflector.inflections.uncountable.each do |word| + define_method "test_uncountability_of_#{word}" do + assert_equal word, ActiveSupport::Inflector.singularize(word) + assert_equal word, ActiveSupport::Inflector.pluralize(word) + assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word) + end + end + + def test_uncountable_word_is_not_greedy + uncountable_word = "ors" + countable_word = "sponsor" + + cached_uncountables = ActiveSupport::Inflector.inflections.uncountables + + ActiveSupport::Inflector.inflections.uncountable << uncountable_word + + assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word) + assert_equal uncountable_word, ActiveSupport::Inflector.pluralize(uncountable_word) + assert_equal ActiveSupport::Inflector.pluralize(uncountable_word), ActiveSupport::Inflector.singularize(uncountable_word) + + assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word) + assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word) + assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word)) + + ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_uncountables + end SingularToPlural.each do |singular, plural| define_method "test_pluralize_#{singular}" do -- cgit v1.2.3 From 1a2c4279913a2af895b03465d4486c51dc61d138 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 22 Dec 2010 09:08:20 +0100 Subject: Ensure that uncountable are removed after test --- activesupport/test/inflector_test.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index e8fe635c03..60714a152d 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -21,7 +21,7 @@ class InflectorTest < Test::Unit::TestCase def test_pluralize_empty_string assert_equal "", ActiveSupport::Inflector.pluralize("") end - + ActiveSupport::Inflector.inflections.uncountable.each do |word| define_method "test_uncountability_of_#{word}" do assert_equal word, ActiveSupport::Inflector.singularize(word) @@ -29,13 +29,13 @@ class InflectorTest < Test::Unit::TestCase assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word) end end - + def test_uncountable_word_is_not_greedy uncountable_word = "ors" countable_word = "sponsor" - + cached_uncountables = ActiveSupport::Inflector.inflections.uncountables - + ActiveSupport::Inflector.inflections.uncountable << uncountable_word assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word) @@ -45,7 +45,8 @@ class InflectorTest < Test::Unit::TestCase assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word) assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word) assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word)) - + + ensure ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_uncountables end -- cgit v1.2.3 From b613145284624b7344675072d2502f9212097965 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 22 Dec 2010 09:15:40 +0100 Subject: Fix activesupport tests. These classes are not used anywhere --- activesupport/test/core_ext/object_and_class_ext_test.rb | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index 398e6ca9b2..5d68b198f2 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -28,18 +28,6 @@ module Nested end end -module Bar - def bar; end -end - -module Baz - def baz; end -end - -class Foo - include Bar -end - class ObjectTests < ActiveSupport::TestCase class DuckTime def acts_like_time? -- cgit v1.2.3 From 27d0d4fffdb62d221e124b67b7ee3de6bfa1893b Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Fri, 17 Dec 2010 11:04:20 +0800 Subject: while defining callbacks option :rescuable => true can be passed. There were no tests for this case. This patch adds a test for :rescuable => true option. --- activesupport/test/callbacks_test.rb | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 51b28b6a43..c89b03e243 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -3,6 +3,27 @@ require 'test/unit' require 'active_support' module CallbacksTest + class Phone + include ActiveSupport::Callbacks + define_callbacks :save, :rescuable => true + + set_callback :save, :before, :before_save1 + set_callback :save, :after, :after_save1 + + def before_save1; self.history << :before; end + def after_save1; self.history << :after; end + + def save + self.send(:_run_save_callbacks) do + raise 'boom' + end + end + + def history + @history ||= [] + end + end + class Record include ActiveSupport::Callbacks @@ -338,6 +359,14 @@ module CallbacksTest end class CallbacksTest < Test::Unit::TestCase + def test_save_phone + phone = Phone.new + assert_raise RuntimeError do + phone.save + end + assert_equal [:before, :after], phone.history + end + def test_save_person person = Person.new assert_equal [], person.history @@ -573,5 +602,5 @@ module CallbacksTest ], writer.history end end - + end -- cgit v1.2.3 From 0ac66caac5581c4793d120c8ad4a2cf4137f6ce2 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Wed, 29 Dec 2010 22:20:14 +0000 Subject: Fix Duration#to_json --- activesupport/lib/active_support/duration.rb | 4 ++++ activesupport/test/core_ext/duration_test.rb | 5 +++++ 2 files changed, 9 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index de3ded1e1f..00c67a470d 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -80,6 +80,10 @@ module ActiveSupport parts.to_sentence(:locale => :en) end + def as_json(options = nil) #:nodoc: + to_i + end + protected def sum(sign, time = ::Time.current) #:nodoc: diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index bb453b8d7f..6a01eeed6b 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'active_support/time' +require 'active_support/json' class DurationTest < ActiveSupport::TestCase def test_is_a @@ -138,6 +139,10 @@ class DurationTest < ActiveSupport::TestCase assert_equal counter, 60 end + def test_to_json + assert_equal '172800', 2.days.to_json + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz -- cgit v1.2.3 From 1f8ecb85d7c1b3efdf45c3cf3461502b608c1a7c Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Sun, 2 Jan 2011 03:35:38 +0700 Subject: Update CHANGELOGs to include 3.0.3 changes --- activesupport/CHANGELOG | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 6e8cce0d27..58cfc86c41 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -4,14 +4,22 @@ * Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White] -*Rails 3.0.2 (unreleased)* + +*Rails 3.0.3 (November 16, 2010)* + +* No changes. + + +*Rails 3.0.2 (November 15, 2010)* * Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White] + *Rails 3.0.1 (October 15, 2010)* * No Changes, just a version bump. + *Rails 3.0.0 (August 29, 2010)* * Implemented String#strip_heredoc. [fxn] -- cgit v1.2.3 From 99424eb0996d41eaccb1b140cc30820fb5779fef Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 2 Jan 2011 00:20:59 +0100 Subject: Revert "Update CHANGELOGs to include 3.0.3 changes" Reason: Sorry, CHANGELOGs can only be edited in master. If you provide a patch I'll apply it myself. Thanks! This reverts commit 1f8ecb85d7c1b3efdf45c3cf3461502b608c1a7c. --- activesupport/CHANGELOG | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 58cfc86c41..6e8cce0d27 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -4,22 +4,14 @@ * Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White] - -*Rails 3.0.3 (November 16, 2010)* - -* No changes. - - -*Rails 3.0.2 (November 15, 2010)* +*Rails 3.0.2 (unreleased)* * Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White] - *Rails 3.0.1 (October 15, 2010)* * No Changes, just a version bump. - *Rails 3.0.0 (August 29, 2010)* * Implemented String#strip_heredoc. [fxn] -- cgit v1.2.3 From 0619dc2319cf839977ea9670a52d9280a1af3595 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 3 Jan 2011 19:54:38 +0000 Subject: Implement deprecated version of AssociationReflection#primary_key_name, which has been renamed to #foreign_key. Also bumping the deprecation_horizon in Active Support to 3.1. --- activesupport/lib/active_support/deprecation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb index e3e63ce316..ce0775a690 100644 --- a/activesupport/lib/active_support/deprecation.rb +++ b/activesupport/lib/active_support/deprecation.rb @@ -9,7 +9,7 @@ module ActiveSupport # The version the deprecated behavior will be removed, by default. attr_accessor :deprecation_horizon end - self.deprecation_horizon = '3.0' + self.deprecation_horizon = '3.1' # By default, warnings are not silenced and debugging is off. self.silenced = false -- cgit v1.2.3 From b1dc9c004e0e81fe69416c117bcc04d2cbd2c83c Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Jan 2011 14:09:16 -0800 Subject: use dots for method calls --- activesupport/test/ordered_hash_test.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 72088854fc..69f24dd6f8 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -239,14 +239,14 @@ class OrderedHashTest < Test::Unit::TestCase def test_each_after_yaml_serialization values = [] - @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash)) + @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash)) @deserialized_ordered_hash.each {|key, value| values << value} assert_equal @values, values end def test_order_after_yaml_serialization - @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash)) + @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash)) assert_equal @keys, @deserialized_ordered_hash.keys assert_equal @values, @deserialized_ordered_hash.values @@ -255,12 +255,17 @@ class OrderedHashTest < Test::Unit::TestCase def test_order_after_yaml_serialization_with_nested_arrays @ordered_hash[:array] = %w(a b c) - @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash)) + @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash)) assert_equal @ordered_hash.keys, @deserialized_ordered_hash.keys assert_equal @ordered_hash.values, @deserialized_ordered_hash.values end + def test_has_yaml_tag + @ordered_hash[:array] = %w(a b c) + assert_match '!omap', YAML.dump(@ordered_hash) + end + def test_update_sets_keys @updated_ordered_hash = ActiveSupport::OrderedHash.new @updated_ordered_hash.update(:name => "Bob") -- cgit v1.2.3 From a84b84efaca02a0164c32a10df59f581eef16ac8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Jan 2011 14:09:35 -0800 Subject: require Psych if possible, use Psych output when enabled --- activesupport/lib/active_support/ordered_hash.rb | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 8e157d3af4..ac20988230 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -1,3 +1,8 @@ +begin + require 'psych' +rescue LoadError +end + require 'yaml' YAML.add_builtin_type("omap") do |type, val| @@ -20,9 +25,17 @@ module ActiveSupport "!tag:yaml.org,2002:omap" end + def encode_with(coder) + coder.represent_seq '!omap', map { |k,v| { k => v } } + end + def to_yaml(opts = {}) + if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? + return super + end + YAML.quick_emit(self, opts) do |out| - out.seq(taguri, to_yaml_style) do |seq| + out.seq(taguri) do |seq| each do |k, v| seq.add(k => v) end -- cgit v1.2.3 From 4fabad7cf125178c95468a573951e587928c333b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Jan 2011 15:01:51 -0800 Subject: test that the custom ordered hash can be round-tripped --- activesupport/lib/active_support/ordered_hash.rb | 5 ----- activesupport/test/ordered_hash_test.rb | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index ac20988230..5b8c342f4f 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -1,8 +1,3 @@ -begin - require 'psych' -rescue LoadError -end - require 'yaml' YAML.add_builtin_type("omap") do |type, val| diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 69f24dd6f8..09203465c3 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -261,6 +261,23 @@ class OrderedHashTest < Test::Unit::TestCase assert_equal @ordered_hash.values, @deserialized_ordered_hash.values end + begin + require 'psych' + + def test_psych_serialize + @deserialized_ordered_hash = Psych.load(Psych.dump(@ordered_hash)) + + values = @deserialized_ordered_hash.map { |_, value| value } + assert_equal @values, values + end + + def test_psych_serialize_tag + yaml = Psych.dump(@ordered_hash) + assert_match '!omap', yaml + end + rescue LoadError + end + def test_has_yaml_tag @ordered_hash[:array] = %w(a b c) assert_match '!omap', YAML.dump(@ordered_hash) -- cgit v1.2.3 From 7bd32e4d1d7b5ffe300ce667dd8daa17a2a9ad26 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Jan 2011 16:52:47 -0800 Subject: add Psych::SyntaxError to the list of rescued YAML exceptions --- activesupport/lib/active_support/json/backends/yaml.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index 4cb9d01077..2e389b5c12 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -7,13 +7,20 @@ module ActiveSupport ParseError = ::StandardError extend self + EXCEPTIONS = [::ArgumentError] # :nodoc: + begin + require 'psych' + EXCEPTIONS << Psych::SyntaxError + rescue LoadError + end + # Parses a JSON string or IO and converts it into an object def decode(json) if json.respond_to?(:read) json = json.read end YAML.load(convert_json_to_yaml(json)) - rescue ArgumentError + rescue *EXCEPTIONS raise ParseError, "Invalid JSON string" end -- cgit v1.2.3 From 5c666779872e6702f4d826686eab09db37cba062 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Jan 2011 17:29:40 -0800 Subject: make our yaml output consistent --- activesupport/lib/active_support/time_with_zone.rb | 6 +----- activesupport/test/core_ext/time_with_zone_test.rb | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 6a7da8266c..8137f8e17e 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -138,11 +138,7 @@ module ActiveSupport end def to_yaml(options = {}) - if options.kind_of?(YAML::Emitter) - utc.to_yaml(options) - else - time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z')) - end + utc.to_yaml(options) end def httpdate diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 5579c27215..2b86da67fa 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -106,7 +106,7 @@ class TimeWithZoneTest < Test::Unit::TestCase end def test_to_yaml - assert_equal "--- 1999-12-31 19:00:00 -05:00\n", @twz.to_yaml + assert_equal "--- 2000-01-01 00:00:00 Z\n", @twz.to_yaml end def test_ruby_to_yaml -- cgit v1.2.3 From 54f3aa86334917bdc947b242c277060a2cfe7b72 Mon Sep 17 00:00:00 2001 From: Nick Sutterer Date: Wed, 5 Jan 2011 21:34:37 +0100 Subject: added tests for XmlMini#to_tag. --- activesupport/test/test_xml_mini.rb | 123 ++++++++++++++++++++++++------------ 1 file changed, 81 insertions(+), 42 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/test_xml_mini.rb b/activesupport/test/test_xml_mini.rb index 309fa234bf..6dbcd1f40b 100644 --- a/activesupport/test/test_xml_mini.rb +++ b/activesupport/test/test_xml_mini.rb @@ -1,61 +1,100 @@ require 'abstract_unit' require 'active_support/xml_mini' +require 'active_support/builder' -class XmlMiniTest < Test::Unit::TestCase - def test_rename_key_dasherizes_by_default - assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key") - end +module XmlMiniTest + class RenameKeyTest < Test::Unit::TestCase + def test_rename_key_dasherizes_by_default + assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key") + end - def test_rename_key_does_nothing_with_dasherize_true - assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true) - end + def test_rename_key_does_nothing_with_dasherize_true + assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true) + end - def test_rename_key_does_nothing_with_dasherize_false - assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false) - end + def test_rename_key_does_nothing_with_dasherize_false + assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false) + end - def test_rename_key_camelizes_with_camelize_false - assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => false) - end + def test_rename_key_camelizes_with_camelize_false + assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => false) + end - def test_rename_key_camelizes_with_camelize_nil - assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => nil) - end + def test_rename_key_camelizes_with_camelize_nil + assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => nil) + end - def test_rename_key_camelizes_with_camelize_true - assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true) - end + def test_rename_key_camelizes_with_camelize_true + assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true) + end - def test_rename_key_lower_camelizes_with_camelize_lower - assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :lower) - end + def test_rename_key_lower_camelizes_with_camelize_lower + assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :lower) + end - def test_rename_key_lower_camelizes_with_camelize_upper - assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :upper) - end + def test_rename_key_lower_camelizes_with_camelize_upper + assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :upper) + end - def test_rename_key_does_not_dasherize_leading_underscores - assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id") - end + def test_rename_key_does_not_dasherize_leading_underscores + assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id") + end - def test_rename_key_with_leading_underscore_dasherizes_interior_underscores - assert_equal "_my-key", ActiveSupport::XmlMini.rename_key("_my_key") - end + def test_rename_key_with_leading_underscore_dasherizes_interior_underscores + assert_equal "_my-key", ActiveSupport::XmlMini.rename_key("_my_key") + end - def test_rename_key_does_not_dasherize_trailing_underscores - assert_equal "id_", ActiveSupport::XmlMini.rename_key("id_") - end + def test_rename_key_does_not_dasherize_trailing_underscores + assert_equal "id_", ActiveSupport::XmlMini.rename_key("id_") + end - def test_rename_key_with_trailing_underscore_dasherizes_interior_underscores - assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_") - end + def test_rename_key_with_trailing_underscore_dasherizes_interior_underscores + assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_") + end - def test_rename_key_does_not_dasherize_multiple_leading_underscores - assert_equal "__id", ActiveSupport::XmlMini.rename_key("__id") - end + def test_rename_key_does_not_dasherize_multiple_leading_underscores + assert_equal "__id", ActiveSupport::XmlMini.rename_key("__id") + end - def test_rename_key_does_not_dasherize_multiple_leading_underscores - assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__") + def test_rename_key_does_not_dasherize_multiple_leading_underscores + assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__") + end end + class ToTagTest < ActiveSupport::TestCase + def assert_xml(xml) + assert_equal xml, @options[:builder].target! + end + + setup do + @xml = ActiveSupport::XmlMini + @options = {:skip_instruct => true, :builder => Builder::XmlMarkup.new} + end + + test "#to_tag accepts a callable object and passes options with the builder" do + @xml.to_tag(:some_tag, lambda {|o| o[:builder].br }, @options) + assert_xml "
" + end + + test "#to_tag accepts a callable object and passes options and tag name" do + @xml.to_tag(:tag, lambda {|o, t| o[:builder].b(t) }, @options) + assert_xml "tag" + end + + test "#to_tag accepts an object responding to #to_xml and passes the options, where :root is key" do + obj = Object.new + obj.instance_eval do + def to_xml(options) options[:builder].yo(options[:root].to_s) end + end + + @xml.to_tag(:tag, obj, @options) + assert_xml "tag" + end + + test "#to_tag accepts arbitrary objects responding to #to_str" do + @xml.to_tag(:b, "Howdy", @options) + assert_xml "Howdy" + end + # TODO: test the remaining functions hidden in #to_tag. + end end -- cgit v1.2.3 From 7773c3240048d66d09afa1658c6f49b5de54bbe8 Mon Sep 17 00:00:00 2001 From: Nick Sutterer Date: Thu, 6 Jan 2011 14:33:20 +0100 Subject: corrected docs for Hash#to_xml and added examples. --- .../lib/active_support/core_ext/hash/conversions.rb | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index 4e8ec5a3a8..3005fef44c 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -26,10 +26,22 @@ class Hash # # * If +value+ is a callable object it must expect one or two arguments. Depending # on the arity, the callable is invoked with the +options+ hash as first argument - # with +key+ as :root, and +key+ singularized as second argument. Its - # return value becomes a new node. + # with +key+ as :root, and +key+ singularized as second argument. The + # callable can add nodes by using options[:builder]. + # + # "foo".to_xml(lambda { |options, key| options[:builder].b(key) }) + # # => "foo" # # * If +value+ responds to +to_xml+ the method is invoked with +key+ as :root. + # + # class Foo + # def to_xml(options) + # options[:builder].bar "fooing!" + # end + # end + # + # {:foo => Foo.new}.to_xml(:skip_instruct => true) + # # => "fooing!" # # * Otherwise, a node with +key+ as tag is created with a string representation of # +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. -- cgit v1.2.3 From 726a66a7a46c1274a3a1ff45b589952252749ebe Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 9 Jan 2011 10:00:15 -0800 Subject: Expand and clarify AS::Callbacks docs. --- activesupport/lib/active_support/callbacks.rb | 228 +++++++++++++------------- 1 file changed, 115 insertions(+), 113 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 32ebea8571..f79363d953 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -5,27 +5,28 @@ require 'active_support/core_ext/kernel/reporting' require 'active_support/core_ext/kernel/singleton_class' module ActiveSupport - # Callbacks are hooks into the life cycle of an object that allow you to trigger logic - # before or after an alteration of the object state. + # \Callbacks are code hooks that are run at key points in an object's lifecycle. + # The typical use case is to have a base class define a set of callbacks relevant + # to the other functionality it supplies, so that subclasses can install callbacks + # that enhance or modify the base functionality without needing to override + # or redefine methods of the base class. # - # Mixing in this module allows you to define callbacks in your class. + # Mixing in this module allows you to define the events in the object's lifecycle + # that will support callbacks (via +ClassMethods.define_callbacks+), set the instance + # methods, procs, or callback objects to be called (via +ClassMethods.set_callback+), + # and run the installed callbacks at the appropriate times (via +run_callbacks+). # - # Example: - # class Storage - # include ActiveSupport::Callbacks + # Three kinds of callbacks are supported: before callbacks, run before a certain event; + # after callbacks, run after the event; and around callbacks, blocks that surround the + # event, triggering it when they yield. Callback code can be contained in instance + # methods, procs or lambdas, or callback objects that respond to certain predetermined + # methods. See +ClassMethods.set_callback+ for details. # - # define_callbacks :save - # end + # ==== Example # - # class ConfigStorage < Storage - # set_callback :save, :before, :saving_message - # def saving_message - # puts "saving..." - # end - # - # set_callback :save, :after do |object| - # puts "saved" - # end + # class Record + # include ActiveSupport::Callbacks + # define_callbacks :save # # def save # run_callbacks :save do @@ -34,29 +35,7 @@ module ActiveSupport # end # end # - # config = ConfigStorage.new - # config.save - # - # Output: - # saving... - # - save - # saved - # - # Callbacks from parent classes are inherited. - # - # Example: - # class Storage - # include ActiveSupport::Callbacks - # - # define_callbacks :save - # - # set_callback :save, :before, :prepare - # def prepare - # puts "preparing save" - # end - # end - # - # class ConfigStorage < Storage + # class PersonRecord < Record # set_callback :save, :before, :saving_message # def saving_message # puts "saving..." @@ -65,19 +44,12 @@ module ActiveSupport # set_callback :save, :after do |object| # puts "saved" # end - # - # def save - # run_callbacks :save do - # puts "- save" - # end - # end # end # - # config = ConfigStorage.new - # config.save + # person = PersonRecord.new + # person.save # # Output: - # preparing save # saving... # - save # saved @@ -89,11 +61,25 @@ module ActiveSupport extend ActiveSupport::DescendantsTracker end + # Runs the callbacks for the given event. + # + # Calls the before and around callbacks in the order they were set, yields + # the block (if given one), and then runs the after callbacks in reverse order. + # Optionally accepts a key, which will be used to compile an optimized callback + # method for each key. See +ClassMethods.define_callbacks+ for more information. + # + # If the callback chain was halted, returns +false+. Otherwise returns the result + # of the block, or +true+ if no block is given. + # + # run_callbacks :save do + # save + # end + # def run_callbacks(kind, *args, &block) send("_run_#{kind}_callbacks", *args, &block) end - class Callback + class Callback #:nodoc:# @@_callback_sequence = 0 attr_accessor :chain, :filter, :kind, :options, :per_key, :klass, :raw_filter @@ -328,7 +314,7 @@ module ActiveSupport end # An Array with a compile method - class CallbackChain < Array + class CallbackChain < Array #:nodoc:# attr_reader :name, :config def initialize(name, config) @@ -373,18 +359,7 @@ module ActiveSupport end module ClassMethods - # Make the run_callbacks :save method. The generated method takes - # a block that it'll yield to. It'll call the before and around filters - # in order, yield the block, and then run the after filters. - # - # run_callbacks :save do - # save - # end - # - # The run_callbacks :save method can optionally take a key, which - # will be used to compile an optimized callback method for each - # key. See #define_callbacks for more information. - # + # Generate the internal runner method called by +run_callbacks+. def __define_runner(symbol) #:nodoc: body = send("_#{symbol}_callbacks").compile @@ -440,18 +415,42 @@ module ActiveSupport end end - # Set callbacks for a previously defined callback. + # Install a callback for the given event. # - # Syntax: # set_callback :save, :before, :before_meth # set_callback :save, :after, :after_meth, :if => :condition # set_callback :save, :around, lambda { |r| stuff; yield; stuff } # - # If the second argument is not :before, :after or :around then an implicit :before is assumed. - # It means the first example mentioned above can also be written as: + # The second arguments indicates whether the callback is to be run +:before+, + # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This + # means the first example above can also be written as: + # # set_callback :save, :before_meth # - # Use skip_callback to skip any defined one. + # The callback can 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 :scope argument to + # +define_callback+. + # + # If a proc, lambda, or block is given, its body is evaluated in the context + # of the current object. It can also optionally accept the current object as + # an argument. + # + # Before and around callbacks are called in the order that they are set; after + # callbacks are called in the reverse order. + # + # ===== Options + # + # * :if - A symbol naming an instance method or a proc; the callback + # will be called only when it returns a true value. + # * :unless - A symbol naming an instance method or a proc; the callback + # will be called only when it returns a false value. + # * :prepend - If true, the callback will be prepended to the existing + # chain rather than appended. + # * :per_key - A hash with :if and :unless options; + # see "Per-key conditions" below. + # + # ===== Per-key conditions # # When creating or skipping callbacks, you can specify conditions that # are always the same for a given key. For instance, in Action Pack, @@ -463,7 +462,7 @@ module ActiveSupport # # set_callback :process_action, :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}} # - # Per-Key conditions are evaluated only once per use of a given key. + # Per-key conditions are evaluated only once per use of a given key. # In the case of the above example, you would do: # # run_callbacks(:process_action, action_name) { ... dispatch stuff ... } @@ -490,7 +489,8 @@ module ActiveSupport end end - # Skip a previously defined callback. + # Skip a previously set callback. Like +set_callback+, :if or :unless + # options may be passed in order to control when the callback is skipped. # # class Writer < Person # skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 } @@ -513,7 +513,7 @@ module ActiveSupport end end - # Reset callbacks for a given type. + # Remove all set callbacks for the given event. # def reset_callbacks(symbol) callbacks = send("_#{symbol}_callbacks") @@ -530,68 +530,70 @@ module ActiveSupport __define_runner(symbol) end - # Defines callbacks types: + # Define sets of events in the object lifecycle that support callbacks. # # define_callbacks :validate + # define_callbacks :initialize, :save, :destroy # - # This macro accepts the following options: + # ===== Options # - # * :terminator - Indicates when a before filter is considered - # to halted. This is a string to be eval'ed and has the result of the - # very filter available in the result variable: + # * :terminator - 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. # - # define_callbacks :validate, :terminator => "result == false" + # define_callbacks :validate, :terminator => "result == false" # - # In the example above, if any before validate callbacks returns +false+, - # other callbacks are not executed. Defaults to "false", meaning no value - # halts the chain. + # In this example, if any before validate callbacks returns +false+, + # other callbacks are not executed. Defaults to "false", meaning no value + # halts the chain. # # * :rescuable - By default, after filters are not executed if - # the given block or a before filter raises an error. Set this option to - # true to change this behavior. + # the given block or a before filter raises an error. Set this option to + # true to change this behavior. # - # * :scope - Indicates which methods should be executed when a class - # is given as callback. Defaults to [:kind]. + # * :scope - Indicates which methods should be executed when an object + # is used as a callback. # - # class Audit - # def before(caller) - # puts 'Audit: before is called' - # end + # class Audit + # def before(caller) + # puts 'Audit: before is called' + # end # - # def before_save(caller) - # puts 'Audit: before_save is called' - # end - # end + # def before_save(caller) + # puts 'Audit: before_save is called' + # end + # end # - # class Account - # include ActiveSupport::Callbacks + # class Account + # include ActiveSupport::Callbacks # - # define_callbacks :save - # set_callback :save, :before, Audit.new + # define_callbacks :save + # set_callback :save, :before, Audit.new # - # def save - # run_callbacks :save do - # puts 'save in main' - # end - # end - # end + # def save + # run_callbacks :save do + # puts 'save in main' + # end + # end + # end # - # In the above case whenever you save an account the method Audit#before will - # be called. On the other hand + # In the above case whenever you save an account the method Audit#before will + # be called. On the other hand # - # define_callbacks :save, :scope => [:kind, :name] + # define_callbacks :save, :scope => [:kind, :name] # - # would trigger Audit#before_save instead. That's constructed by calling - # "#{kind}_#{name}" on the given instance. In this case "kind" is "before" and - # "name" is "save". In this context ":kind" and ":name" have special meanings: ":kind" - # refers to the kind of callback (before/after/around) and ":name" refers to the - # method on which callbacks are being defined. + # would trigger Audit#before_save instead. That's constructed by calling + # #{kind}_#{name} on the given instance. In this case "kind" is "before" and + # "name" is "save". In this context +:kind+ and +:name+ have special meanings: +:kind+ + # refers to the kind of callback (before/after/around) and +:name+ refers to the + # method on which callbacks are being defined. # - # A declaration like + # A declaration like # - # define_callbacks :save, :scope => [:name] + # define_callbacks :save, :scope => [:name] # - # would call Audit#save. + # would call Audit#save. # def define_callbacks(*callbacks) config = callbacks.last.is_a?(Hash) ? callbacks.pop : {} -- cgit v1.2.3 From 1cc556dc5263bbbe5845b9a7abde9c84dffa7fb0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 10 Jan 2011 15:43:21 -0800 Subject: adding to_d to BigDecimal --- .../active_support/core_ext/big_decimal/conversions.rb | 4 ++++ activesupport/test/core_ext/bigdecimal.rb | 10 ---------- activesupport/test/core_ext/bigdecimal_test.rb | 15 +++++++++++++++ 3 files changed, 19 insertions(+), 10 deletions(-) delete mode 100644 activesupport/test/core_ext/bigdecimal.rb create mode 100644 activesupport/test/core_ext/bigdecimal_test.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb index f7f03f4d95..3720dbb8b8 100644 --- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb @@ -18,6 +18,10 @@ class BigDecimal end end + def to_d + self + end + DEFAULT_STRING_FORMAT = 'F' def to_formatted_s(format = DEFAULT_STRING_FORMAT) _original_to_s(format) diff --git a/activesupport/test/core_ext/bigdecimal.rb b/activesupport/test/core_ext/bigdecimal.rb deleted file mode 100644 index 9faad9146f..0000000000 --- a/activesupport/test/core_ext/bigdecimal.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'abstract_unit' - -class BigDecimalTest < Test::Unit::TestCase - def test_to_yaml - assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml) - assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) - assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml) - assert_equal("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml) - end -end \ No newline at end of file diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb new file mode 100644 index 0000000000..0272f564de --- /dev/null +++ b/activesupport/test/core_ext/bigdecimal_test.rb @@ -0,0 +1,15 @@ +require 'abstract_unit' + +class BigDecimalTest < Test::Unit::TestCase + def test_to_yaml + assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml) + assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) + assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml) + assert_equal("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml) + end + + def test_to_d + bd = BigDecimal.new '10' + assert_equal bd, bd.to_d + end +end -- cgit v1.2.3 From de18b85969b7a5457536df905c76078f032a9cda Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Wed, 12 Jan 2011 15:16:55 +0100 Subject: In AS, only inflector/methods is need in proxy_wrappers.rb, as well as date, date_time, and time conversions.rb. This fixes an issue when requiring json and AS saying that i18n is also required. Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/core_ext/date/conversions.rb | 2 +- activesupport/lib/active_support/core_ext/date_time/conversions.rb | 2 +- activesupport/lib/active_support/core_ext/time/conversions.rb | 2 +- activesupport/lib/active_support/deprecation/proxy_wrappers.rb | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb index 092f936961..06d868a3b0 100644 --- a/activesupport/lib/active_support/core_ext/date/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date/conversions.rb @@ -1,5 +1,5 @@ require 'date' -require 'active_support/inflector' +require 'active_support/inflector/methods' require 'active_support/core_ext/date/zones' class Date 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 8e267c76c4..029b8c41b4 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -1,4 +1,4 @@ -require 'active_support/inflector' +require 'active_support/inflector/methods' require 'active_support/core_ext/time/conversions' require 'active_support/core_ext/date_time/calculations' require 'active_support/values/time_zone' diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb index d4ae3131ec..49ac18d245 100644 --- a/activesupport/lib/active_support/core_ext/time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/time/conversions.rb @@ -1,4 +1,4 @@ -require 'active_support/inflector' +require 'active_support/inflector/methods' require 'active_support/core_ext/time/publicize_conversion_methods' require 'active_support/values/time_zone' diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb index 970536a594..a65fcafb44 100644 --- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb +++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb @@ -1,4 +1,4 @@ -require 'active_support/inflector' +require 'active_support/inflector/methods' module ActiveSupport module Deprecation -- cgit v1.2.3 From 199e220e885277dad5e222bf98f00a67b2e6674e Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Wed, 12 Jan 2011 15:18:21 +0100 Subject: Fixed various isolated test missing requires within AS. Signed-off-by: Santiago Pastorino --- activesupport/test/core_ext/bigdecimal_test.rb | 6 ++++-- activesupport/test/core_ext/hash_ext_test.rb | 1 + activesupport/test/json/encoding_test.rb | 1 + 3 files changed, 6 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb index 0272f564de..d592973d7a 100644 --- a/activesupport/test/core_ext/bigdecimal_test.rb +++ b/activesupport/test/core_ext/bigdecimal_test.rb @@ -1,10 +1,12 @@ require 'abstract_unit' +require 'bigdecimal' +require 'active_support/core_ext/big_decimal' class BigDecimalTest < Test::Unit::TestCase def test_to_yaml assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml) - assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) - assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml) + assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) + assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml) assert_equal("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml) end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 74223dd7f2..a0479d45ac 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -4,6 +4,7 @@ require 'bigdecimal' require 'active_support/core_ext/string/access' require 'active_support/ordered_hash' require 'active_support/core_ext/object/conversions' +require 'active_support/inflections' class HashExtTest < Test::Unit::TestCase class IndifferentHash < HashWithIndifferentAccess diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index e0494de6e4..7469ae70fd 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -1,5 +1,6 @@ # encoding: utf-8 require 'abstract_unit' +require 'active_support/core_ext/string/inflections' require 'active_support/json' class TestJSONEncoding < Test::Unit::TestCase -- cgit v1.2.3 From f2beb56c8b14326f35af887ef0d2ee6356946065 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Jan 2011 15:53:25 -0800 Subject: fixing whitespace errors --- activesupport/lib/active_support/deprecation/reporting.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/deprecation/reporting.rb b/activesupport/lib/active_support/deprecation/reporting.rb index c7723d139b..ced08b8783 100644 --- a/activesupport/lib/active_support/deprecation/reporting.rb +++ b/activesupport/lib/active_support/deprecation/reporting.rb @@ -2,7 +2,7 @@ module ActiveSupport module Deprecation class << self attr_accessor :silenced - + # Outputs a deprecation warning to the output configured by ActiveSupport::Deprecation.behavior # # Example: -- cgit v1.2.3 From b461fe76f47dc34a6a958d1761ac0332421627fd Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Wed, 12 Jan 2011 22:37:34 -0500 Subject: editing comments regarding rescuable optoin in AS callbacks --- activesupport/lib/active_support/callbacks.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index f79363d953..6e284182b2 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -549,8 +549,9 @@ module ActiveSupport # halts the chain. # # * :rescuable - By default, after filters are not executed if - # the given block or a before filter raises an error. Set this option to - # true to change this behavior. + # the given block or a before filter raises an error. By setting this option + # to true exception raised by given block is stored and after + # executing all the after callbacks the stored exception is raised. # # * :scope - Indicates which methods should be executed when an object # is used as a callback. -- cgit v1.2.3 From d2c17dbd11417012c47b9ac48c62651a1415de5d Mon Sep 17 00:00:00 2001 From: Alexey Nayden Date: Thu, 13 Jan 2011 03:16:16 +0300 Subject: Complex struct encoding test Signed-off-by: Santiago Pastorino --- activesupport/test/json/encoding_test.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'activesupport') diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 7469ae70fd..f7ca39f0f6 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -215,6 +215,29 @@ class TestJSONEncoding < Test::Unit::TestCase assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json) end + def test_struct_encoding + Struct.new('UserNameAndEmail', :name, :email) + Struct.new('UserNameAndDate', :name, :date) + Struct.new('Custom', :name, :sub) + user_email = Struct::UserNameAndEmail.new 'David', 'sample@example.com' + user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01) + custom = Struct::Custom.new 'David', user_birthday + + + json_strings = "" + json_string_and_date = "" + json_custom = "" + + assert_nothing_raised do + json_strings = user_email.to_json + json_string_and_date = user_birthday.to_json + json_custom = custom.to_json + end + + assert_equal %({"name":"David","email":"sample@example.com"}), json_strings + assert_equal %({"name":"David","date":"2010/01/01"}), json_string_and_date + assert_equal %({"sub":{"name":"David","date":"2010/01/01"},"name":"David"}), json_custom + end protected -- cgit v1.2.3 From a9163b547c7cfd4861c814371fa9d1a6bdb31231 Mon Sep 17 00:00:00 2001 From: Alexey Nayden Date: Thu, 13 Jan 2011 03:17:47 +0300 Subject: Complex struct encoding fix [#6077 state:committed] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/json/encoding.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index c8cac52027..b2ea196003 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -153,6 +153,12 @@ class Object end end +class Struct + def as_json(options = nil) #:nodoc: + Hash[members.zip(values)] + end +end + class TrueClass AS_JSON = ActiveSupport::JSON::Variable.new('true').freeze def as_json(options = nil) AS_JSON end #:nodoc: -- cgit v1.2.3 From d780d1f508c880c59d6d932bd052cb0b1c1c76b0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 16:06:55 -0800 Subject: ordering can change depending on ruby version, so parse the JSON and verify data structure equality --- activesupport/test/json/encoding_test.rb | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index f7ca39f0f6..d5fcbf15b7 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -234,9 +234,16 @@ class TestJSONEncoding < Test::Unit::TestCase json_custom = custom.to_json end - assert_equal %({"name":"David","email":"sample@example.com"}), json_strings - assert_equal %({"name":"David","date":"2010/01/01"}), json_string_and_date - assert_equal %({"sub":{"name":"David","date":"2010/01/01"},"name":"David"}), json_custom + assert_equal({"name" => "David", + "sub" => { + "name" => "David", + "date" => "2010/01/01" }}, JSON.parse(json_custom)) + + assert_equal({"name" => "David", "email" => "sample@example.com"}, + JSON.parse(json_strings)) + + assert_equal({"name" => "David", "date" => "2010/01/01"}, + JSON.parse(json_string_and_date)) end protected -- cgit v1.2.3 From cc446eee99b9e480637ea8792349068d2c98fc85 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Tue, 18 Jan 2011 13:34:12 +0800 Subject: Class.__subclasses__ was removed from Rubinius. https://github.com/evanphx/rubinius/issues/issue/11 https://github.com/evanphx/rubinius/commit/2fccbb5dad5cb3f5414d635547290538cfc0a2d4 --- .../active_support/core_ext/class/subclasses.rb | 54 ++++++++-------------- 1 file changed, 20 insertions(+), 34 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb index 3e5d1a2a42..46e9daaa8f 100644 --- a/activesupport/lib/active_support/core_ext/class/subclasses.rb +++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb @@ -2,49 +2,35 @@ require 'active_support/core_ext/module/anonymous' require 'active_support/core_ext/module/reachable' class Class #:nodoc: - # Rubinius - if defined?(Class.__subclasses__) - alias :subclasses :__subclasses__ + begin + ObjectSpace.each_object(Class.new) {} def descendants descendants = [] - __subclasses__.each do |k| - descendants << k - descendants.concat k.descendants + ObjectSpace.each_object(class << self; self; end) do |k| + descendants.unshift k unless k == self end descendants end - else # MRI - begin - ObjectSpace.each_object(Class.new) {} - - def descendants - descendants = [] - ObjectSpace.each_object(class << self; self; end) do |k| - descendants.unshift k unless k == self - end - descendants - end - rescue StandardError # JRuby - def descendants - descendants = [] - ObjectSpace.each_object(Class) do |k| - descendants.unshift k if k < self - end - descendants.uniq! - descendants + rescue StandardError # JRuby + def descendants + descendants = [] + ObjectSpace.each_object(Class) do |k| + descendants.unshift k if k < self end + descendants.uniq! + descendants end + end - # Returns an array with the direct children of +self+. - # - # Integer.subclasses # => [Bignum, Fixnum] - def subclasses - subclasses, chain = [], descendants - chain.each do |k| - subclasses << k unless chain.any? { |c| c > k } - end - subclasses + # Returns an array with the direct children of +self+. + # + # Integer.subclasses # => [Bignum, Fixnum] + def subclasses + subclasses, chain = [], descendants + chain.each do |k| + subclasses << k unless chain.any? { |c| c > k } end + subclasses end end -- cgit v1.2.3 From 7091d800b80dd5cd06c3a232c5386efc16fda6fb Mon Sep 17 00:00:00 2001 From: Nick Sutterer Date: Tue, 18 Jan 2011 20:45:52 +0100 Subject: fixed a missing require that causes trouble when using AS in a non-rails env. --- activesupport/lib/active_support/xml_mini/libxml.rb | 1 + activesupport/lib/active_support/xml_mini/libxmlsax.rb | 3 ++- activesupport/lib/active_support/xml_mini/nokogiri.rb | 1 + activesupport/lib/active_support/xml_mini/nokogirisax.rb | 1 + activesupport/lib/active_support/xml_mini/rexml.rb | 1 + 5 files changed, 6 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb index 7fdcb11465..16570c6aea 100644 --- a/activesupport/lib/active_support/xml_mini/libxml.rb +++ b/activesupport/lib/active_support/xml_mini/libxml.rb @@ -1,5 +1,6 @@ require 'libxml' require 'active_support/core_ext/object/blank' +require 'stringio' # = XmlMini LibXML implementation module ActiveSupport diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb index fe2c1b9349..2536b1f33e 100644 --- a/activesupport/lib/active_support/xml_mini/libxmlsax.rb +++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb @@ -1,5 +1,6 @@ require 'libxml' require 'active_support/core_ext/object/blank' +require 'stringio' # = XmlMini LibXML implementation using a SAX-based parser module ActiveSupport @@ -82,4 +83,4 @@ module ActiveSupport end end end -end \ No newline at end of file +end diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb index e03a744257..04ec9e8ab8 100644 --- a/activesupport/lib/active_support/xml_mini/nokogiri.rb +++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb @@ -5,6 +5,7 @@ rescue LoadError => e raise e end require 'active_support/core_ext/object/blank' +require 'stringio' # = XmlMini Nokogiri implementation module ActiveSupport diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb index 25afbfcd1c..93fd3dfe57 100644 --- a/activesupport/lib/active_support/xml_mini/nokogirisax.rb +++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb @@ -5,6 +5,7 @@ rescue LoadError => e raise e end require 'active_support/core_ext/object/blank' +require 'stringio' # = XmlMini Nokogiri implementation using a SAX-based parser module ActiveSupport diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb index 36692af1d3..a13ad10118 100644 --- a/activesupport/lib/active_support/xml_mini/rexml.rb +++ b/activesupport/lib/active_support/xml_mini/rexml.rb @@ -1,5 +1,6 @@ require 'active_support/core_ext/kernel/reporting' require 'active_support/core_ext/object/blank' +require 'stringio' # = XmlMini ReXML implementation module ActiveSupport -- cgit v1.2.3 From 36d66786905b3cc2dda6c48345a89bbd760fcb82 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 18 Jan 2011 14:55:20 -0800 Subject: removing usesless variable assignments --- activesupport/lib/active_support/callbacks.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 32ebea8571..843c688ca9 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -185,7 +185,11 @@ module ActiveSupport # end filter = <<-RUBY_EVAL unless halted - result = #{@filter} + # This double assignment is to prevent warnings in 1.9.3. I would + # remove the `result` variable, but apparently some other + # generated code is depending on this variable being set sometimes + # and sometimes not. + result = result = #{@filter} halted = (#{chain.config[:terminator]}) end RUBY_EVAL -- cgit v1.2.3 From 2570c85cb7de03a2c9cc183c73707a267f2efb91 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 19 Jan 2011 14:31:22 -0800 Subject: fixing psych support in big decimal, fixing tests to support YAML 1.1 --- .../lib/active_support/core_ext/big_decimal/conversions.rb | 7 +++++++ activesupport/test/core_ext/bigdecimal_test.rb | 8 ++++---- 2 files changed, 11 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb index 3720dbb8b8..a279849829 100644 --- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb @@ -12,12 +12,19 @@ class BigDecimal # # Note that reconstituting YAML floats to native floats may lose precision. def to_yaml(opts = {}) + return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? + YAML.quick_emit(nil, opts) do |out| string = to_s out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain) end end + def encode_with(coder) + string = to_s + coder.represent_scalar(nil, YAML_MAPPING[string] || string) + end + def to_d self end diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb index d592973d7a..b38e08a9f4 100644 --- a/activesupport/test/core_ext/bigdecimal_test.rb +++ b/activesupport/test/core_ext/bigdecimal_test.rb @@ -4,10 +4,10 @@ require 'active_support/core_ext/big_decimal' class BigDecimalTest < Test::Unit::TestCase def test_to_yaml - assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml) - assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) - assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml) - assert_equal("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml) + assert_match("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml) + assert_match("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) + assert_match("--- .NaN\n", BigDecimal.new('NaN').to_yaml) + assert_match("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml) end def test_to_d -- cgit v1.2.3 From 7642b7531d222c9d7a94add50fffca69458e0eef Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 19 Jan 2011 15:19:57 -0800 Subject: prefering psych as the yaml parser if possible, fixing assertions for YAML 1.1 compatibility --- .../lib/active_support/core_ext/big_decimal/conversions.rb | 6 ++++++ activesupport/lib/active_support/time_with_zone.rb | 10 ++++++++++ activesupport/test/core_ext/time_with_zone_test.rb | 4 ++-- 3 files changed, 18 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb index a279849829..11c318c244 100644 --- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb @@ -1,4 +1,10 @@ require 'bigdecimal' + +begin + require 'psych' +rescue LoadError +end + require 'yaml' class BigDecimal diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 8137f8e17e..3da216ac78 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -137,7 +137,17 @@ module ActiveSupport end end + def encode_with(coder) + if coder.respond_to?(:represent_object) + coder.represent_object(nil, utc) + else + coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ")) + end + end + def to_yaml(options = {}) + return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? + utc.to_yaml(options) end diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 2b86da67fa..5c226c2d09 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -106,11 +106,11 @@ class TimeWithZoneTest < Test::Unit::TestCase end def test_to_yaml - assert_equal "--- 2000-01-01 00:00:00 Z\n", @twz.to_yaml + assert_match(/^--- 2000-01-01 00:00:00(\.0+)?\s*Z\n/, @twz.to_yaml) end def test_ruby_to_yaml - assert_equal "--- \n:twz: 2000-01-01 00:00:00 Z\n", {:twz => @twz}.to_yaml + assert_match(/---\s*\n:twz: 2000-01-01 00:00:00(\.0+)?\s*Z\n/, {:twz => @twz}.to_yaml) end def test_httpdate -- cgit v1.2.3 From 370bcd1a017816422db2fdb410366752d60d72c8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 21 Jan 2011 14:09:59 -0800 Subject: use ! " " YAML string literal syntax rather than removing both quotes --- activesupport/lib/active_support/json/backends/yaml.rb | 8 ++++---- activesupport/test/json/decoding_test.rb | 4 +--- 2 files changed, 5 insertions(+), 7 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index 2e389b5c12..c7ed931c1b 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -20,8 +20,8 @@ module ActiveSupport json = json.read end YAML.load(convert_json_to_yaml(json)) - rescue *EXCEPTIONS - raise ParseError, "Invalid JSON string" + rescue *EXCEPTIONS => e + raise ParseError, "Invalid JSON string: '%s'" % json end protected @@ -39,7 +39,7 @@ module ActiveSupport if json[pos..scanner.pos-2] =~ DATE_REGEX # found a date, track the exact positions of the quotes so we can # overwrite them with spaces later. - times << pos << scanner.pos + times << pos end quoting = false end @@ -70,7 +70,7 @@ module ActiveSupport chunk = scanner.peek(right_pos[i] - scanner.pos + 1) # overwrite the quotes found around the dates with spaces while times.size > 0 && times[0] <= right_pos[i] - chunk[times.shift - scanner.pos - 1] = ' ' + chunk.insert(times.shift - scanner.pos - 1, '! ') end chunk.gsub!(/\\([\\\/]|u[[:xdigit:]]{4})/) do ustr = $1 diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index d2e3efaa6b..a0beb97537 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -57,9 +57,7 @@ class TestJSONDecoding < ActiveSupport::TestCase ActiveSupport.parse_json_times = true silence_warnings do ActiveSupport::JSON.with_backend backend do - assert_nothing_raised do - assert_equal expected, ActiveSupport::JSON.decode(json) - end + assert_equal expected, ActiveSupport::JSON.decode(json) end end end -- cgit v1.2.3 From c29eef7da735bf19e7c9cd205c753e8de24516cd Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 28 Jan 2011 14:24:11 -0800 Subject: load psych by default if possible --- activesupport/lib/active_support/ordered_hash.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 5b8c342f4f..ac20988230 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -1,3 +1,8 @@ +begin + require 'psych' +rescue LoadError +end + require 'yaml' YAML.add_builtin_type("omap") do |type, val| -- cgit v1.2.3 From 452dba72f5bac3118a3405408665ae372ebbe6a1 Mon Sep 17 00:00:00 2001 From: brainopia Date: Wed, 19 Jan 2011 16:34:27 +0300 Subject: Remove unneeded yaml_as declaration --- activesupport/lib/active_support/core_ext/big_decimal/conversions.rb | 2 -- 1 file changed, 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb index 11c318c244..080604147d 100644 --- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb @@ -11,8 +11,6 @@ class BigDecimal YAML_TAG = 'tag:yaml.org,2002:float' YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' } - yaml_as YAML_TAG - # This emits the number without any scientific notation. # This is better than self.to_f.to_s since it doesn't lose precision. # -- cgit v1.2.3 From eb33bd944d03d174ac7eac5d59fc280b35b1a3bd Mon Sep 17 00:00:00 2001 From: brainopia Date: Wed, 19 Jan 2011 17:10:01 +0300 Subject: Psych correctly gets visitor for SafeBuffer from superclass --- activesupport/lib/active_support/core_ext/string/output_safety.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index bb0f747960..29d6613611 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -1,5 +1,6 @@ require 'erb' require 'active_support/core_ext/kernel/singleton_class' +require 'active_support/core_ext/yaml' class ERB module Util @@ -101,8 +102,10 @@ module ActiveSupport #:nodoc: self end - def to_yaml(*args) - to_str.to_yaml(*args) + unless defined?(Psych) + def to_yaml(*args) + to_str.to_yaml(*args) + end end end end -- cgit v1.2.3 From c87fb22a061292e66d790e23eee6982c8053d270 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 28 Jan 2011 15:00:52 -0800 Subject: make sure we play nicely when syck is activated --- .../core_ext/string/output_safety.rb | 13 ++++++++----- activesupport/test/safe_buffer_test.rb | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 29d6613611..c930abc003 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -1,6 +1,5 @@ require 'erb' require 'active_support/core_ext/kernel/singleton_class' -require 'active_support/core_ext/yaml' class ERB module Util @@ -102,10 +101,14 @@ module ActiveSupport #:nodoc: self end - unless defined?(Psych) - def to_yaml(*args) - to_str.to_yaml(*args) - end + def encode_with(coder) + coder.represent_scalar nil, to_str + end + + def to_yaml(*args) + return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? + + to_str.to_yaml(*args) end end end diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb index bf61f9e58c..a4e2acbb32 100644 --- a/activesupport/test/safe_buffer_test.rb +++ b/activesupport/test/safe_buffer_test.rb @@ -1,4 +1,10 @@ require 'abstract_unit' +begin + require 'psych' +rescue LoadError +end + +require 'yaml' class SafeBufferTest < ActiveSupport::TestCase def setup @@ -38,4 +44,20 @@ class SafeBufferTest < ActiveSupport::TestCase new_buffer = @buffer.to_s assert_equal ActiveSupport::SafeBuffer, new_buffer.class end + + def test_to_yaml + str = 'hello!' + buf = ActiveSupport::SafeBuffer.new str + yaml = buf.to_yaml + + assert_match(/^--- #{str}/, yaml) + assert_equal 'hello!', YAML.load(yaml) + end + + def test_nested + str = 'hello!' + data = { 'str' => ActiveSupport::SafeBuffer.new(str) } + yaml = YAML.dump data + assert_equal({'str' => str}, YAML.load(yaml)) + end end -- cgit v1.2.3 From 57bc25c5f8129f57b08a2dc7c319b86778dd8a40 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 9 Jan 2011 10:15:05 -0800 Subject: Use run_callbacks; the generated _run__callbacks method is not a public interface. Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/testing/setup_and_teardown.rb | 8 ++++---- activesupport/test/callback_inheritance_test.rb | 2 +- activesupport/test/callbacks_test.rb | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb index b2d9ddfeb7..22e41fa905 100644 --- a/activesupport/lib/active_support/testing/setup_and_teardown.rb +++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb @@ -31,14 +31,14 @@ module ActiveSupport def run(runner) result = '.' begin - _run_setup_callbacks do + run_callbacks :setup do result = super end rescue Exception => e result = runner.puke(self.class, method_name, e) ensure begin - _run_teardown_callbacks + run_callbacks :teardown rescue Exception => e result = runner.puke(self.class, method_name, e) end @@ -62,7 +62,7 @@ module ActiveSupport begin begin - _run_setup_callbacks do + run_callbacks :setup do setup __send__(@method_name) mocha_verify(mocha_counter) if mocha_counter @@ -77,7 +77,7 @@ module ActiveSupport ensure begin teardown - _run_teardown_callbacks + run_callbacks :teardown rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) rescue Exception => e diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb index 8caf000c5d..71249050fc 100644 --- a/activesupport/test/callback_inheritance_test.rb +++ b/activesupport/test/callback_inheritance_test.rb @@ -70,7 +70,7 @@ class EmptyParent end def dispatch - _run_dispatch_callbacks + run_callbacks :dispatch self end end diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index c89b03e243..cff914f4ae 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -14,7 +14,7 @@ module CallbacksTest def after_save1; self.history << :after; end def save - self.send(:_run_save_callbacks) do + run_callbacks :save do raise 'boom' end end -- cgit v1.2.3 From b1ca339b53559a71958c02644e329c714037f616 Mon Sep 17 00:00:00 2001 From: Saimon Moore Date: Fri, 28 Jan 2011 13:53:07 +0100 Subject: Additionally trigger i18n configuration setup before any eager loading [#6353 state:resolved] This handles the case where config.cache_classes is true and classes are loaded before the I18n load path has had a chance to be populated. Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/i18n_railtie.rb | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb index 282337d373..7fdc908bbd 100644 --- a/activesupport/lib/active_support/i18n_railtie.rb +++ b/activesupport/lib/active_support/i18n_railtie.rb @@ -24,9 +24,8 @@ module I18n end end - # Set the i18n configuration only after initialization since a lot of - # configuration is still usually done in application initializers. - config.after_initialize do |app| + # Proc to set up i18n configuration + init_load_path = Proc.new do |app| fallbacks = app.config.i18n.delete(:fallbacks) app.config.i18n.each do |setting, value| @@ -46,6 +45,14 @@ module I18n reloader.execute_if_updated end + # Set the i18n configuration only after initialization since a lot of + # configuration is still usually done in application initializers. + config.after_initialize(&init_load_path) + + # Trigger i18n config before any eager loading has happened + # so it's ready if any classes require it when eager loaded + config.before_eager_load(&init_load_path) + protected def self.include_fallbacks_module @@ -78,4 +85,4 @@ module I18n end end end -end \ No newline at end of file +end -- cgit v1.2.3 From c2aca3ddd78b514d099ddef5afc4cee0dd7d75f2 Mon Sep 17 00:00:00 2001 From: Saimon Moore Date: Tue, 1 Feb 2011 17:12:51 +0100 Subject: Ensure I18n setup is only executed once if triggered on eager loading [#6353 state:resolved] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/i18n_railtie.rb | 32 +++++++++++++++--------- 1 file changed, 20 insertions(+), 12 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb index 7fdc908bbd..4a9ee5a769 100644 --- a/activesupport/lib/active_support/i18n_railtie.rb +++ b/activesupport/lib/active_support/i18n_railtie.rb @@ -24,8 +24,24 @@ module I18n end end - # Proc to set up i18n configuration - init_load_path = Proc.new do |app| + # Set the i18n configuration after initialization since a lot of + # configuration is still usually done in application initializers. + config.after_initialize do |app| + I18n::Railtie.initialize_i18n(app) + end + + # Trigger i18n config before any eager loading has happened + # so it's ready if any classes require it when eager loaded + config.before_eager_load do |app| + I18n::Railtie.initialize_i18n(app) + end + + protected + + # Setup i18n configuration + def self.initialize_i18n(app) + return if @i18n_inited + fallbacks = app.config.i18n.delete(:fallbacks) app.config.i18n.each do |setting, value| @@ -43,17 +59,9 @@ module I18n reloader.paths.concat I18n.load_path reloader.execute_if_updated - end - # Set the i18n configuration only after initialization since a lot of - # configuration is still usually done in application initializers. - config.after_initialize(&init_load_path) - - # Trigger i18n config before any eager loading has happened - # so it's ready if any classes require it when eager loaded - config.before_eager_load(&init_load_path) - - protected + @i18n_inited = true + end def self.include_fallbacks_module I18n.backend.class.send(:include, I18n::Backend::Fallbacks) -- cgit v1.2.3 From 9a0f43d3c1dd35fde074af6cc2825ae1872aabef Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Wed, 2 Feb 2011 09:58:40 -0500 Subject: OrderedHash#each* methods return self like Hash does [#6364 state:resolved] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/ordered_hash.rb | 3 +++ activesupport/test/ordered_hash_test.rb | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index ac20988230..b2f04b427b 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -138,14 +138,17 @@ module ActiveSupport def each_key @keys.each { |key| yield key } + self end def each_value @keys.each { |key| yield self[key]} + self end def each @keys.each {|key| yield [key, self[key]]} + self end alias_method :each_pair, :each diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 09203465c3..d2cfd3698f 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -78,19 +78,19 @@ class OrderedHashTest < Test::Unit::TestCase def test_each_key keys = [] - @ordered_hash.each_key { |k| keys << k } + assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k } assert_equal @keys, keys end def test_each_value values = [] - @ordered_hash.each_value { |v| values << v } + assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v } assert_equal @values, values end def test_each values = [] - @ordered_hash.each {|key, value| values << value} + assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value} assert_equal @values, values end -- cgit v1.2.3 From 68e3fb81090ba67575e513407fc2463dba3b002b Mon Sep 17 00:00:00 2001 From: Maxime RETY Date: Mon, 14 Jun 2010 16:05:49 +0200 Subject: Fix JSON decoding of newline character with Yaml backend [#3479 state:resolved] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/json/backends/yaml.rb | 8 ++++++-- activesupport/test/json/decoding_test.rb | 6 +++++- 2 files changed, 11 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index c7ed931c1b..b1dd2a8107 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -54,7 +54,9 @@ module ActiveSupport json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do ustr = $1 if ustr.start_with?('u') - [ustr[1..-1].to_i(16)].pack("U") + char = [ustr[1..-1].to_i(16)].pack("U") + # "\n" needs extra escaping due to yaml formatting + char == "\n" ? "\\n" : char elsif ustr == '\\' '\\\\' else @@ -75,7 +77,9 @@ module ActiveSupport chunk.gsub!(/\\([\\\/]|u[[:xdigit:]]{4})/) do ustr = $1 if ustr.start_with?('u') - [ustr[1..-1].to_i(16)].pack("U") + char = [ustr[1..-1].to_i(16)].pack("U") + # "\n" needs extra escaping due to yaml formatting + char == "\n" ? "\\n" : char elsif ustr == '\\' '\\\\' else diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index a0beb97537..613c7531d9 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -41,7 +41,11 @@ class TestJSONDecoding < ActiveSupport::TestCase [{'d' => Date.new(1970, 1, 1), 's' => ' escape'},{'d' => Date.new(1970, 1, 1), 's' => ' escape'}], %q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) => [{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}, - {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}] + {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}], + # tests escaping of "\n" char with Yaml backend + %q("\n") => "\n", + %q("\u000a") => "\n", + %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"} } # load the default JSON backend -- cgit v1.2.3 From 434aa095607669f3b95343e874064d7c74bf921c Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 2 Feb 2011 20:52:38 -0200 Subject: Fix tests providing valid JSON --- activesupport/test/json/decoding_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 613c7531d9..436861baad 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -43,8 +43,8 @@ class TestJSONDecoding < ActiveSupport::TestCase [{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}, {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}], # tests escaping of "\n" char with Yaml backend - %q("\n") => "\n", - %q("\u000a") => "\n", + %q({"a":"\n"}) => {"a"=>"\n"}, + %q({"a":"\u000a"}) => {"a"=>"\n"}, %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"} } -- cgit v1.2.3 From bf0395837fc735bf98daed23f475b267e48c1118 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Thu, 6 Jan 2011 13:26:31 -0800 Subject: Preserve fractional seconds in DateTime#to_time Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/core_ext/date_time/conversions.rb | 2 +- activesupport/test/core_ext/date_time_ext_test.rb | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'activesupport') 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 029b8c41b4..21b84b994b 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -66,7 +66,7 @@ class DateTime # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time def to_time - self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self + self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self end # To be able to keep Times, Dates and DateTimes interchangeable on conversions diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb index 7d993d84e2..8edb95b63a 100644 --- a/activesupport/test/core_ext/date_time_ext_test.rb +++ b/activesupport/test/core_ext/date_time_ext_test.rb @@ -38,6 +38,8 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0, 0).to_time # DateTimes with offsets other than 0 are returned unaltered assert_equal DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)), DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).to_time + # Fractional seconds are preserved + assert_equal Time.utc(2005, 2, 21, 10, 11, 12, 256), DateTime.new(2005, 2, 21, 10, 11, 12 + Rational(256, 1000000), 0).to_time end def test_civil_from_format -- cgit v1.2.3 From 080345baca1076a9788dff4803153600aec31f86 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Thu, 6 Jan 2011 13:33:36 -0800 Subject: Ruby 1.8.7+ provides to_date/to_datetime, AS just makes them public. Signed-off-by: Santiago Pastorino --- .../active_support/core_ext/time/conversions.rb | 22 ---------------------- activesupport/test/core_ext/time_ext_test.rb | 16 +++------------- 2 files changed, 3 insertions(+), 35 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb index 49ac18d245..d9d5e02778 100644 --- a/activesupport/lib/active_support/core_ext/time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/time/conversions.rb @@ -55,31 +55,9 @@ class Time utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) end - # Converts a Time object to a Date, dropping hour, minute, and second precision. - # - # my_time = Time.now # => Mon Nov 12 22:59:51 -0500 2007 - # my_time.to_date # => Mon, 12 Nov 2007 - # - # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009 - # your_time.to_date # => Tue, 13 Jan 2009 - def to_date - ::Date.new(year, month, day) - end unless method_defined?(:to_date) - # A method to keep Time, Date and DateTime instances interchangeable on conversions. # In this case, it simply returns +self+. def to_time self end unless method_defined?(:to_time) - - # Converts a Time instance to a Ruby DateTime instance, preserving UTC offset. - # - # my_time = Time.now # => Mon Nov 12 23:04:21 -0500 2007 - # my_time.to_datetime # => Mon, 12 Nov 2007 23:04:21 -0500 - # - # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009 - # your_time.to_datetime # => Tue, 13 Jan 2009 13:13:03 -0500 - def to_datetime - ::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400)) - end unless method_defined?(:to_datetime) end diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 53d497013a..891a6badac 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -533,19 +533,9 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase Time::DATE_FORMATS.delete(:custom) end - def test_to_date - assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date - end - - def test_to_datetime - assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0, 0) - with_env_tz 'US/Eastern' do - assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0) - end - with_env_tz 'NZ' do - assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0) - end - assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value + def test_conversion_methods_are_publicized + assert Time.public_instance_methods.include?(:to_date) || Time.public_instance_methods.include?('to_date') + assert Time.public_instance_methods.include?(:to_datetime) || Time.public_instance_methods.include?('to_datetime') end def test_to_time -- cgit v1.2.3 From c0b4db0c28465866b656c894c16ce35f4d313a12 Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Wed, 2 Feb 2011 23:35:54 -0500 Subject: fix OrderedHash#each* methods to return Enumerators when called without a block [#6366 state:resolved] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/ordered_hash.rb | 3 +++ activesupport/test/ordered_hash_test.rb | 6 ++++++ 2 files changed, 9 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index b2f04b427b..fbc40d1b69 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -137,16 +137,19 @@ module ActiveSupport end def each_key + return to_enum(:each_key) unless block_given? @keys.each { |key| yield key } self end def each_value + return to_enum(:each_value) unless block_given? @keys.each { |key| yield self[key]} self end def each + return to_enum(:each) unless block_given? @keys.each {|key| yield [key, self[key]]} self end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index d2cfd3698f..0a7dadf7a8 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -80,18 +80,24 @@ class OrderedHashTest < Test::Unit::TestCase keys = [] assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k } assert_equal @keys, keys + expected_class = RUBY_VERSION < '1.9.1' ? Enumerable::Enumerator : Enumerator + assert_kind_of expected_class, @ordered_hash.each_key end def test_each_value values = [] assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v } assert_equal @values, values + expected_class = RUBY_VERSION < '1.9.1' ? Enumerable::Enumerator : Enumerator + assert_kind_of expected_class, @ordered_hash.each_value end def test_each values = [] assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value} assert_equal @values, values + expected_class = RUBY_VERSION < '1.9.1' ? Enumerable::Enumerator : Enumerator + assert_kind_of expected_class, @ordered_hash.each end def test_each_with_index -- cgit v1.2.3 From 092a4e296de5b69f06edac2fe0993e2a30e33555 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 3 Feb 2011 19:27:33 -0200 Subject: just < 1.9 is fine and 1.9.1 is not supported --- activesupport/test/ordered_hash_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 0a7dadf7a8..50168fa78f 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -80,7 +80,7 @@ class OrderedHashTest < Test::Unit::TestCase keys = [] assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k } assert_equal @keys, keys - expected_class = RUBY_VERSION < '1.9.1' ? Enumerable::Enumerator : Enumerator + expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator assert_kind_of expected_class, @ordered_hash.each_key end @@ -88,7 +88,7 @@ class OrderedHashTest < Test::Unit::TestCase values = [] assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v } assert_equal @values, values - expected_class = RUBY_VERSION < '1.9.1' ? Enumerable::Enumerator : Enumerator + expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator assert_kind_of expected_class, @ordered_hash.each_value end @@ -96,7 +96,7 @@ class OrderedHashTest < Test::Unit::TestCase values = [] assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value} assert_equal @values, values - expected_class = RUBY_VERSION < '1.9.1' ? Enumerable::Enumerator : Enumerator + expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator assert_kind_of expected_class, @ordered_hash.each end -- cgit v1.2.3 From 3a29bfae2cbb956e469942ed1d4ea8c702085a1a Mon Sep 17 00:00:00 2001 From: Brian Morearty Date: Fri, 4 Feb 2011 09:10:07 -0800 Subject: Change Time.zone= docs. Update the example to show how to reset the current thread's Time.zone upon exiting a request. --- activesupport/lib/active_support/core_ext/time/zones.rb | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb index ef401a6d18..ff90d7ca58 100644 --- a/activesupport/lib/active_support/core_ext/time/zones.rb +++ b/activesupport/lib/active_support/core_ext/time/zones.rb @@ -19,14 +19,18 @@ class Time # * A TZInfo::Timezone object. # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). # - # Here's an example of how you might set Time.zone on a per request basis -- current_user.time_zone - # just needs to return a string identifying the user's preferred TimeZone: + # Here's an example of how you might set Time.zone on a per request basis and reset it when the request is done. + # current_user.time_zone just needs to return a string identifying the user's preferred time zone: # # class ApplicationController < ActionController::Base - # before_filter :set_time_zone + # around_filter :set_time_zone # # def set_time_zone - # Time.zone = current_user.time_zone + # old_time_zone = Time.zone + # Time.zone = current_user.time_zone if logged_in? + # yield + # ensure + # Time.zone = old_time_zone # end # end def zone=(time_zone) -- cgit v1.2.3 From da2d24f7cf4dfb826843cda96b413ca2ba326158 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 4 Feb 2011 21:36:10 -0200 Subject: git am is better here --- activesupport/README.rdoc | 1 + 1 file changed, 1 insertion(+) (limited to 'activesupport') diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc index 77b8a64304..7237f7386a 100644 --- a/activesupport/README.rdoc +++ b/activesupport/README.rdoc @@ -1,4 +1,5 @@ = Active Support -- Utility classes and Ruby extensions from Rails +fasdf Active Support is a collection of utility classes and standard library extensions that were found useful for the Rails framework. These additions -- cgit v1.2.3 From 78d23edf9a5ba6d4c50cb603c9828fcf5c7fe357 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 4 Feb 2011 21:49:56 -0200 Subject: Remove stupid mistake --- activesupport/README.rdoc | 1 - 1 file changed, 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc index 7237f7386a..77b8a64304 100644 --- a/activesupport/README.rdoc +++ b/activesupport/README.rdoc @@ -1,5 +1,4 @@ = Active Support -- Utility classes and Ruby extensions from Rails -fasdf Active Support is a collection of utility classes and standard library extensions that were found useful for the Rails framework. These additions -- cgit v1.2.3 From 1fd9d978a737d36cf7cca698f0fcbfc6fcdbed98 Mon Sep 17 00:00:00 2001 From: wycats Date: Sun, 6 Feb 2011 13:41:56 -0800 Subject: Add initial FileWatcher implementation. The Backend is just an abstract implementation, which will be inherited by backends that do the heavy lifting. --- activesupport/lib/active_support.rb | 1 + activesupport/lib/active_support/file_watcher.rb | 41 +++++++++++++++ activesupport/test/file_watcher_test.rb | 65 ++++++++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 activesupport/lib/active_support/file_watcher.rb create mode 100644 activesupport/test/file_watcher_test.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 6b87774978..6b662ac660 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -42,6 +42,7 @@ module ActiveSupport autoload :DescendantsTracker autoload :FileUpdateChecker + autoload :FileWatcher autoload :LogSubscriber autoload :Notifications diff --git a/activesupport/lib/active_support/file_watcher.rb b/activesupport/lib/active_support/file_watcher.rb new file mode 100644 index 0000000000..046a5a0309 --- /dev/null +++ b/activesupport/lib/active_support/file_watcher.rb @@ -0,0 +1,41 @@ +module ActiveSupport + class FileWatcher + class Backend + def initialize(path, watcher) + @watcher = watcher + @path = path + end + + def trigger(files) + @watcher.trigger(files) + end + end + + def initialize + @regex_matchers = {} + end + + def watch(path, &block) + return watch_regex(path, &block) if path.is_a?(Regexp) + raise "Paths must be regular expressions. #{path.inspect} is a #{path.class}" + end + + def watch_regex(regex, &block) + @regex_matchers[regex] = block + end + + def trigger(files) + trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } } + + files.each do |file, state| + @regex_matchers.each do |regex, block| + trigger_files[block][state] << file if file =~ regex + end + end + + trigger_files.each do |block, payload| + block.call payload + end + end + end +end diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb new file mode 100644 index 0000000000..54aa9f92f1 --- /dev/null +++ b/activesupport/test/file_watcher_test.rb @@ -0,0 +1,65 @@ +require 'abstract_unit' + +class FileWatcherTest < ActiveSupport::TestCase + class DumbBackend < ActiveSupport::FileWatcher::Backend + end + + def setup + @watcher = ActiveSupport::FileWatcher.new + + # In real life, the backend would take the path and use it to observe the file + # system. In our case, we will manually trigger the events for unit testing, + # so we can pass any path. + @backend = DumbBackend.new("RAILS_WOOT", @watcher) + + @payload = [] + @watcher.watch %r{^app/assets/.*\.scss$} do |pay| + pay.each do |status, files| + files.sort! + end + @payload << pay + end + end + + def test_one_change + @backend.trigger("app/assets/main.scss" => :changed) + assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first) + end + + def test_multiple_changes + @backend.trigger("app/assets/main.scss" => :changed, "app/assets/javascripts/foo.coffee" => :changed) + assert_equal([{:changed => ["app/assets/main.scss"]}], @payload) + end + + def test_multiple_changes_match + @backend.trigger("app/assets/main.scss" => :changed, "app/assets/print.scss" => :changed, "app/assets/javascripts/foo.coffee" => :changed) + assert_equal([{:changed => ["app/assets/main.scss", "app/assets/print.scss"]}], @payload) + end + + def test_multiple_state_changes + @backend.trigger("app/assets/main.scss" => :created, "app/assets/print.scss" => :changed) + assert_equal([{:changed => ["app/assets/print.scss"], :created => ["app/assets/main.scss"]}], @payload) + end + + def test_more_blocks + payload = [] + @watcher.watch %r{^config/routes\.rb$} do |pay| + payload << pay + end + + @backend.trigger "config/routes.rb" => :changed + assert_equal [:changed => ["config/routes.rb"]], payload + assert_equal [], @payload + end + + def test_overlapping_watchers + payload = [] + @watcher.watch %r{^app/assets/main\.scss$} do |pay| + payload << pay + end + + @backend.trigger "app/assets/print.scss" => :changed, "app/assets/main.scss" => :changed + assert_equal [:changed => ["app/assets/main.scss"]], payload + assert_equal [:changed => ["app/assets/main.scss", "app/assets/print.scss"]], @payload + end +end -- cgit v1.2.3 From 60da34b4be009da5da460c59d10c500a76170ed5 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 13:45:43 -0800 Subject: notifier should be saved and re-set, not deleted --- activesupport/lib/active_support/log_subscriber/test_helper.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb index 5c24b9c759..52a64383a2 100644 --- a/activesupport/lib/active_support/log_subscriber/test_helper.rb +++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb @@ -38,13 +38,14 @@ module ActiveSupport ActiveSupport::LogSubscriber.colorize_logging = false + @old_notifier = ActiveSupport::Notifications.notifier set_logger(@logger) ActiveSupport::Notifications.notifier = @notifier end def teardown set_logger(nil) - ActiveSupport::Notifications.notifier = nil + ActiveSupport::Notifications.notifier = @old_notifier end class MockLogger -- cgit v1.2.3 From 1df3b65acccaee908b6a579640f5060094fad8c0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 10:42:03 -0800 Subject: use === so that regular expressions are not required --- activesupport/lib/active_support/file_watcher.rb | 8 ++------ activesupport/test/file_watcher_test.rb | 10 ++++++++++ 2 files changed, 12 insertions(+), 6 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/file_watcher.rb b/activesupport/lib/active_support/file_watcher.rb index 046a5a0309..81b4b117c1 100644 --- a/activesupport/lib/active_support/file_watcher.rb +++ b/activesupport/lib/active_support/file_watcher.rb @@ -15,21 +15,17 @@ module ActiveSupport @regex_matchers = {} end - def watch(path, &block) - return watch_regex(path, &block) if path.is_a?(Regexp) - raise "Paths must be regular expressions. #{path.inspect} is a #{path.class}" - end - def watch_regex(regex, &block) @regex_matchers[regex] = block end + alias :watch :watch_regex def trigger(files) trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } } files.each do |file, state| @regex_matchers.each do |regex, block| - trigger_files[block][state] << file if file =~ regex + trigger_files[block][state] << file if regex === file end end diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb index 54aa9f92f1..3e577df5af 100644 --- a/activesupport/test/file_watcher_test.rb +++ b/activesupport/test/file_watcher_test.rb @@ -21,6 +21,16 @@ class FileWatcherTest < ActiveSupport::TestCase end end + def test_use_triple_equals + fw = ActiveSupport::FileWatcher.new + called = [] + fw.watch("some_arbitrary_file.rb") do |file| + called << "omg" + end + fw.trigger(%w{ some_arbitrary_file.rb }) + assert_equal ['omg'], called + end + def test_one_change @backend.trigger("app/assets/main.scss" => :changed) assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first) -- cgit v1.2.3 From 51414a0893096709cdc3d02c72d6bfb67fa43319 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 10:48:01 -0800 Subject: use === so that regular expressions are not required --- activesupport/lib/active_support/file_watcher.rb | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/file_watcher.rb b/activesupport/lib/active_support/file_watcher.rb index 81b4b117c1..81e63e76a7 100644 --- a/activesupport/lib/active_support/file_watcher.rb +++ b/activesupport/lib/active_support/file_watcher.rb @@ -15,17 +15,16 @@ module ActiveSupport @regex_matchers = {} end - def watch_regex(regex, &block) - @regex_matchers[regex] = block + def watch(pattern, &block) + @regex_matchers[pattern] = block end - alias :watch :watch_regex def trigger(files) trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } } files.each do |file, state| - @regex_matchers.each do |regex, block| - trigger_files[block][state] << file if regex === file + @regex_matchers.each do |pattern, block| + trigger_files[block][state] << file if pattern === file end end -- cgit v1.2.3 From 3eb25fb8806c0b161d2d1d9cb22d0bdfc7b0ce63 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Wed, 9 Feb 2011 10:23:45 +0100 Subject: fix for AS Gzip returning a UTF-8 string in Ruby 1.9 when it is actually binary [#6386 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activesupport/lib/active_support/gzip.rb | 4 ++++ activesupport/test/gzip_test.rb | 10 ++++++++++ 2 files changed, 14 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb index 35a50e9a77..fddbfb0ab7 100644 --- a/activesupport/lib/active_support/gzip.rb +++ b/activesupport/lib/active_support/gzip.rb @@ -5,6 +5,10 @@ module ActiveSupport # A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip. module Gzip class Stream < StringIO + def initialize(*) + super + set_encoding "BINARY" if "".encoding_aware? + end def close; rewind; end end diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb index 2a24c0bd0d..6adfab0359 100644 --- a/activesupport/test/gzip_test.rb +++ b/activesupport/test/gzip_test.rb @@ -4,4 +4,14 @@ class GzipTest < Test::Unit::TestCase def test_compress_should_decompress_to_the_same_value assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World")) end + + def test_compress_should_return_a_binary_string + compressed = ActiveSupport::Gzip.compress('') + + if "".encoding_aware? + assert_equal Encoding.find('binary'), compressed.encoding + end + + assert !compressed.blank?, "a compressed blank string should not be blank" + end end \ No newline at end of file -- cgit v1.2.3 From 0faa7ee2a05b261ef89fb4652eaa0cfeef86c1d5 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino and Emilio Tagua Date: Wed, 9 Feb 2011 08:36:44 -0200 Subject: Add missing require --- activesupport/test/gzip_test.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb index 6adfab0359..f564e63f29 100644 --- a/activesupport/test/gzip_test.rb +++ b/activesupport/test/gzip_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/object/blank' class GzipTest < Test::Unit::TestCase def test_compress_should_decompress_to_the_same_value @@ -14,4 +15,4 @@ class GzipTest < Test::Unit::TestCase assert !compressed.blank?, "a compressed blank string should not be blank" end -end \ No newline at end of file +end -- cgit v1.2.3 From 3d0579fc03fe4adc97c770f148e035ee75745648 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 9 Feb 2011 13:46:47 -0800 Subject: speed up notification publishing by writing the delegate method --- activesupport/lib/active_support/notifications.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index fd79188ba4..116f28d360 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -45,7 +45,10 @@ module ActiveSupport class << self attr_writer :notifier - delegate :publish, :to => :notifier + + def publish(name, *args) + notifier.publish(name, *args) + end def instrument(name, payload = {}) if @instrumenters[name] -- cgit v1.2.3 From e50d43a2017bea8088ecf7aab7fa632f9b80f77f Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 9 Feb 2011 13:47:32 -0800 Subject: fixing indentation --- activesupport/lib/active_support/gzip.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb index fddbfb0ab7..62f9c9aa2e 100644 --- a/activesupport/lib/active_support/gzip.rb +++ b/activesupport/lib/active_support/gzip.rb @@ -6,9 +6,9 @@ module ActiveSupport module Gzip class Stream < StringIO def initialize(*) - super - set_encoding "BINARY" if "".encoding_aware? - end + super + set_encoding "BINARY" if "".encoding_aware? + end def close; rewind; end end @@ -26,4 +26,4 @@ module ActiveSupport output.string end end -end \ No newline at end of file +end -- cgit v1.2.3 From 3e02b3702ec640a521214109646bdebb5216bf96 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 9 Feb 2011 14:02:38 -0800 Subject: just use an attr_accessor so we do not pay ||= on every notification call --- activesupport/lib/active_support/notifications.rb | 8 +++----- activesupport/test/notifications_test.rb | 9 +++++++-- 2 files changed, 10 insertions(+), 7 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 116f28d360..30daf9dafc 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -44,7 +44,7 @@ module ActiveSupport @instrumenters = Hash.new { |h,k| h[k] = notifier.listening?(k) } class << self - attr_writer :notifier + attr_accessor :notifier def publish(name, *args) notifier.publish(name, *args) @@ -69,13 +69,11 @@ module ActiveSupport @instrumenters.clear end - def notifier - @notifier ||= Fanout.new - end - def instrumenter Thread.current[:"instrumentation_#{notifier.object_id}"] ||= Instrumenter.new(notifier) end end + + self.notifier = Fanout.new end end diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index 9faa11efbc..7b48b3f85b 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -3,14 +3,19 @@ require 'abstract_unit' module Notifications class TestCase < ActiveSupport::TestCase def setup - ActiveSupport::Notifications.notifier = nil - @notifier = ActiveSupport::Notifications.notifier + @old_notifier = ActiveSupport::Notifications.notifier + @notifier = ActiveSupport::Notifications::Fanout.new + ActiveSupport::Notifications.notifier = @notifier @events = [] @named_events = [] @subscription = @notifier.subscribe { |*args| @events << event(*args) } @named_subscription = @notifier.subscribe("named.subscription") { |*args| @named_events << event(*args) } end + def teardown + ActiveSupport::Notifications.notifier = @old_notifier + end + private def event(*args) -- cgit v1.2.3 From 37efb517cb87c0894d8ecaa2066c5be6283f5450 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 9 Feb 2011 14:33:56 -0800 Subject: fanout unsubscribe only accepted one argument, so taking *args here is probably bad --- activesupport/lib/active_support/notifications.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 30daf9dafc..77696eb1db 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -64,8 +64,8 @@ module ActiveSupport end end - def unsubscribe(*args) - notifier.unsubscribe(*args) + def unsubscribe(args) + notifier.unsubscribe(args) @instrumenters.clear end -- cgit v1.2.3 From f7221f5c7571da50d4d0199c0a7502cc7cd82b6e Mon Sep 17 00:00:00 2001 From: Paul Hieromnimon Date: Thu, 10 Feb 2011 20:38:14 +0800 Subject: Initial html_safe implemention for Array --- .../core_ext/string/output_safety.rb | 16 ++++++++ activesupport/test/core_ext/string_ext_test.rb | 44 ++++++++++++++++++++++ 2 files changed, 60 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index c930abc003..520aa4e67d 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -122,3 +122,19 @@ class String ActiveSupport::SafeBuffer.new(self) end end + +class Array + + alias_method :original_join, :join + + def join(sep=$,) + sep ||= "".html_safe + str = original_join(sep) + (sep.html_safe? && html_safe?) ? str.html_safe : str + end + + def html_safe? + self.detect {|e| !e.html_safe?}.nil? + end + +end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index bb865cae91..41a23641d4 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -434,6 +434,50 @@ class OutputSafetyTest < ActiveSupport::TestCase assert string.html_safe? end + test "Joining safe elements without a separator is safe" do + array = 5.times.collect {"some string".html_safe} + assert array.join.html_safe? + end + + test "Joining safe elements with a safe separator is safe" do + array = 5.times.collect {"some string".html_safe} + assert array.join("-".html_safe).html_safe? + end + + test "Joining safe elements with an unsafe separator is unsafe" do + array = 5.times.collect {"some string".html_safe} + assert_false array.join("-").html_safe? + end + + test "Joining is unsafe if any element is unsafe even with a safe separator" do + array = 5.times.collect {"some string".html_safe} + array << "some string" + assert_false array.join("-".html_safe).html_safe? + end + + test "Joining is unsafe if any element is unsafe and no separator is given" do + array = 5.times.collect {"some string".html_safe} + array << "some string" + assert_false array.join.html_safe? + end + + test "Joining is unsafe if any element is unsafe and the separator is unsafe" do + array = 5.times.collect {"some string".html_safe} + array << "some string" + assert_false array.join("-").html_safe? + end + + test "Array is safe if all elements are safe" do + array = 5.times.collect { "some string".html_safe } + assert array.html_safe? + end + + test "Array is unsafe if any element is unsafe" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert_false array.html_safe? + end + test 'emits normal string yaml' do assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1) end -- cgit v1.2.3 From 1a73407b8506b548a5343c66c16897140203472e Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Thu, 10 Feb 2011 22:03:53 +0800 Subject: Corrected the html_safe implementation for Array. Moved the html safe version of join to its own method (safe_join) as not to degrade the performance of join for unrelated html_safe use. [#6298 state:resolved] --- .../core_ext/string/output_safety.rb | 29 ++++++++++++++++------ activesupport/test/core_ext/string_ext_test.rb | 26 +++++++++---------- 2 files changed, 35 insertions(+), 20 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 520aa4e67d..0c8fc20ea5 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -124,17 +124,32 @@ class String end class Array - - alias_method :original_join, :join - - def join(sep=$,) + # If the separator and all the items in the array are html safe + # then an html safe string is returned using Array#join, + # otherwise the result of Array#join is returned without + # marking it as html safe. + # + # ["Mr", "Bojangles"].join.html_safe? + # # => false + # + # ["Mr".html_safe, "Bojangles".html_safe].join.html_safe? + # # => true + # + def safe_join(sep=$,) sep ||= "".html_safe - str = original_join(sep) + str = join(sep) (sep.html_safe? && html_safe?) ? str.html_safe : str end + # Returns +true+ if all items in the array are html safe. + # + # [""].html_safe? + # # => false + # + # ["".html_safe].html_safe? + # # => true + # def html_safe? - self.detect {|e| !e.html_safe?}.nil? + detect { |e| !e.html_safe? }.nil? end - end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 41a23641d4..15e39a06c3 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -435,36 +435,36 @@ class OutputSafetyTest < ActiveSupport::TestCase end test "Joining safe elements without a separator is safe" do - array = 5.times.collect {"some string".html_safe} - assert array.join.html_safe? + array = 5.times.collect { "some string".html_safe } + assert array.safe_join.html_safe? end test "Joining safe elements with a safe separator is safe" do - array = 5.times.collect {"some string".html_safe} - assert array.join("-".html_safe).html_safe? + array = 5.times.collect { "some string".html_safe } + assert array.safe_join("-".html_safe).html_safe? end test "Joining safe elements with an unsafe separator is unsafe" do - array = 5.times.collect {"some string".html_safe} - assert_false array.join("-").html_safe? + array = 5.times.collect { "some string".html_safe } + assert !array.safe_join("-").html_safe? end test "Joining is unsafe if any element is unsafe even with a safe separator" do - array = 5.times.collect {"some string".html_safe} + array = 5.times.collect { "some string".html_safe } array << "some string" - assert_false array.join("-".html_safe).html_safe? + assert !array.safe_join("-".html_safe).html_safe? end test "Joining is unsafe if any element is unsafe and no separator is given" do - array = 5.times.collect {"some string".html_safe} + array = 5.times.collect { "some string".html_safe } array << "some string" - assert_false array.join.html_safe? + assert !array.safe_join.html_safe? end test "Joining is unsafe if any element is unsafe and the separator is unsafe" do - array = 5.times.collect {"some string".html_safe} + array = 5.times.collect { "some string".html_safe } array << "some string" - assert_false array.join("-").html_safe? + assert !array.safe_join("-").html_safe? end test "Array is safe if all elements are safe" do @@ -475,7 +475,7 @@ class OutputSafetyTest < ActiveSupport::TestCase test "Array is unsafe if any element is unsafe" do array = 5.times.collect { "some string".html_safe } array << "some string" - assert_false array.html_safe? + assert !array.html_safe? end test 'emits normal string yaml' do -- cgit v1.2.3 From 98c0c5db50a7679b3d58769ac22cb0a27a62c930 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Thu, 10 Feb 2011 23:01:02 +0800 Subject: Removed Array#safe_join in AS core_ext and moved it to a view helper with the same same. --- .../core_ext/string/output_safety.rb | 31 --------------- activesupport/test/core_ext/string_ext_test.rb | 44 ---------------------- 2 files changed, 75 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 0c8fc20ea5..c930abc003 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -122,34 +122,3 @@ class String ActiveSupport::SafeBuffer.new(self) end end - -class Array - # If the separator and all the items in the array are html safe - # then an html safe string is returned using Array#join, - # otherwise the result of Array#join is returned without - # marking it as html safe. - # - # ["Mr", "Bojangles"].join.html_safe? - # # => false - # - # ["Mr".html_safe, "Bojangles".html_safe].join.html_safe? - # # => true - # - def safe_join(sep=$,) - sep ||= "".html_safe - str = join(sep) - (sep.html_safe? && html_safe?) ? str.html_safe : str - end - - # Returns +true+ if all items in the array are html safe. - # - # [""].html_safe? - # # => false - # - # ["".html_safe].html_safe? - # # => true - # - def html_safe? - detect { |e| !e.html_safe? }.nil? - end -end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 15e39a06c3..bb865cae91 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -434,50 +434,6 @@ class OutputSafetyTest < ActiveSupport::TestCase assert string.html_safe? end - test "Joining safe elements without a separator is safe" do - array = 5.times.collect { "some string".html_safe } - assert array.safe_join.html_safe? - end - - test "Joining safe elements with a safe separator is safe" do - array = 5.times.collect { "some string".html_safe } - assert array.safe_join("-".html_safe).html_safe? - end - - test "Joining safe elements with an unsafe separator is unsafe" do - array = 5.times.collect { "some string".html_safe } - assert !array.safe_join("-").html_safe? - end - - test "Joining is unsafe if any element is unsafe even with a safe separator" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.safe_join("-".html_safe).html_safe? - end - - test "Joining is unsafe if any element is unsafe and no separator is given" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.safe_join.html_safe? - end - - test "Joining is unsafe if any element is unsafe and the separator is unsafe" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.safe_join("-").html_safe? - end - - test "Array is safe if all elements are safe" do - array = 5.times.collect { "some string".html_safe } - assert array.html_safe? - end - - test "Array is unsafe if any element is unsafe" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.html_safe? - end - test 'emits normal string yaml' do assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1) end -- cgit v1.2.3 From 89a5f1463d7e9546ed7a0cf482afea99ba2040e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 10 Feb 2011 16:50:35 +0100 Subject: Revert "Removed Array#safe_join in AS core_ext and moved it to a view helper with the same same." Applied the wrong version. This reverts commit 98c0c5db50a7679b3d58769ac22cb0a27a62c930. --- .../core_ext/string/output_safety.rb | 31 +++++++++++++++ activesupport/test/core_ext/string_ext_test.rb | 44 ++++++++++++++++++++++ 2 files changed, 75 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index c930abc003..0c8fc20ea5 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -122,3 +122,34 @@ class String ActiveSupport::SafeBuffer.new(self) end end + +class Array + # If the separator and all the items in the array are html safe + # then an html safe string is returned using Array#join, + # otherwise the result of Array#join is returned without + # marking it as html safe. + # + # ["Mr", "Bojangles"].join.html_safe? + # # => false + # + # ["Mr".html_safe, "Bojangles".html_safe].join.html_safe? + # # => true + # + def safe_join(sep=$,) + sep ||= "".html_safe + str = join(sep) + (sep.html_safe? && html_safe?) ? str.html_safe : str + end + + # Returns +true+ if all items in the array are html safe. + # + # [""].html_safe? + # # => false + # + # ["".html_safe].html_safe? + # # => true + # + def html_safe? + detect { |e| !e.html_safe? }.nil? + end +end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index bb865cae91..15e39a06c3 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -434,6 +434,50 @@ class OutputSafetyTest < ActiveSupport::TestCase assert string.html_safe? end + test "Joining safe elements without a separator is safe" do + array = 5.times.collect { "some string".html_safe } + assert array.safe_join.html_safe? + end + + test "Joining safe elements with a safe separator is safe" do + array = 5.times.collect { "some string".html_safe } + assert array.safe_join("-".html_safe).html_safe? + end + + test "Joining safe elements with an unsafe separator is unsafe" do + array = 5.times.collect { "some string".html_safe } + assert !array.safe_join("-").html_safe? + end + + test "Joining is unsafe if any element is unsafe even with a safe separator" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !array.safe_join("-".html_safe).html_safe? + end + + test "Joining is unsafe if any element is unsafe and no separator is given" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !array.safe_join.html_safe? + end + + test "Joining is unsafe if any element is unsafe and the separator is unsafe" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !array.safe_join("-").html_safe? + end + + test "Array is safe if all elements are safe" do + array = 5.times.collect { "some string".html_safe } + assert array.html_safe? + end + + test "Array is unsafe if any element is unsafe" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !array.html_safe? + end + test 'emits normal string yaml' do assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1) end -- cgit v1.2.3 From 1814298d7590988d354955efdb0bc495b359293b Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Thu, 10 Feb 2011 16:45:39 +0100 Subject: Removed Array#safe_join in AS core_ext and moved it to a view helper with the same same. This also changes how safe_join works, if items or the separator are not html_safe they are html_escape'd, a html_safe string is always returned. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../core_ext/string/output_safety.rb | 31 --------------- activesupport/test/core_ext/string_ext_test.rb | 44 ---------------------- 2 files changed, 75 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 0c8fc20ea5..c930abc003 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -122,34 +122,3 @@ class String ActiveSupport::SafeBuffer.new(self) end end - -class Array - # If the separator and all the items in the array are html safe - # then an html safe string is returned using Array#join, - # otherwise the result of Array#join is returned without - # marking it as html safe. - # - # ["Mr", "Bojangles"].join.html_safe? - # # => false - # - # ["Mr".html_safe, "Bojangles".html_safe].join.html_safe? - # # => true - # - def safe_join(sep=$,) - sep ||= "".html_safe - str = join(sep) - (sep.html_safe? && html_safe?) ? str.html_safe : str - end - - # Returns +true+ if all items in the array are html safe. - # - # [""].html_safe? - # # => false - # - # ["".html_safe].html_safe? - # # => true - # - def html_safe? - detect { |e| !e.html_safe? }.nil? - end -end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 15e39a06c3..bb865cae91 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -434,50 +434,6 @@ class OutputSafetyTest < ActiveSupport::TestCase assert string.html_safe? end - test "Joining safe elements without a separator is safe" do - array = 5.times.collect { "some string".html_safe } - assert array.safe_join.html_safe? - end - - test "Joining safe elements with a safe separator is safe" do - array = 5.times.collect { "some string".html_safe } - assert array.safe_join("-".html_safe).html_safe? - end - - test "Joining safe elements with an unsafe separator is unsafe" do - array = 5.times.collect { "some string".html_safe } - assert !array.safe_join("-").html_safe? - end - - test "Joining is unsafe if any element is unsafe even with a safe separator" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.safe_join("-".html_safe).html_safe? - end - - test "Joining is unsafe if any element is unsafe and no separator is given" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.safe_join.html_safe? - end - - test "Joining is unsafe if any element is unsafe and the separator is unsafe" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.safe_join("-").html_safe? - end - - test "Array is safe if all elements are safe" do - array = 5.times.collect { "some string".html_safe } - assert array.html_safe? - end - - test "Array is unsafe if any element is unsafe" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !array.html_safe? - end - test 'emits normal string yaml' do assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1) end -- cgit v1.2.3 From b17d8d727fb510ad8b6eb4302984d290dc2e53b0 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Fri, 11 Feb 2011 16:47:25 +0100 Subject: Fixes an issue when decoding a json string which looks like a date but is invalid. This DateTime parse error is now caught and the original string is instead passed back [#6286 state:resolved] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/json/backends/jsongem.rb | 6 +++++- activesupport/lib/active_support/json/backends/yajl.rb | 6 +++++- activesupport/lib/active_support/json/backends/yaml.rb | 12 +++++++++++- activesupport/test/json/decoding_test.rb | 2 ++ 4 files changed, 23 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/backends/jsongem.rb b/activesupport/lib/active_support/json/backends/jsongem.rb index cfe28d7bb9..533ba25da3 100644 --- a/activesupport/lib/active_support/json/backends/jsongem.rb +++ b/activesupport/lib/active_support/json/backends/jsongem.rb @@ -26,7 +26,11 @@ module ActiveSupport when nil nil when DATE_REGEX - DateTime.parse(data) + begin + DateTime.parse(data) + rescue ArgumentError + data + end when Array data.map! { |d| convert_dates_from(d) } when Hash diff --git a/activesupport/lib/active_support/json/backends/yajl.rb b/activesupport/lib/active_support/json/backends/yajl.rb index 64e50e0d87..58818658c7 100644 --- a/activesupport/lib/active_support/json/backends/yajl.rb +++ b/activesupport/lib/active_support/json/backends/yajl.rb @@ -23,7 +23,11 @@ module ActiveSupport when nil nil when DATE_REGEX - DateTime.parse(data) + begin + DateTime.parse(data) + rescue ArgumentError + data + end when Array data.map! { |d| convert_dates_from(d) } when Hash diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index b1dd2a8107..077eda548a 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -36,7 +36,7 @@ module ActiveSupport quoting = char pos = scanner.pos elsif quoting == char - if json[pos..scanner.pos-2] =~ DATE_REGEX + if valid_date?(json[pos..scanner.pos-2]) # found a date, track the exact positions of the quotes so we can # overwrite them with spaces later. times << pos @@ -94,6 +94,16 @@ module ActiveSupport output end end + + private + def valid_date?(date_string) + begin + date_string =~ DATE_REGEX && DateTime.parse(date_string) + rescue ArgumentError + false + end + end + end end end diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 436861baad..77f24f0de3 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -19,6 +19,8 @@ class TestJSONDecoding < ActiveSupport::TestCase %({"a": "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)}, # no time zone %({"a": "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"}, + # invalid date + %({"a": "1089-10-40"}) => {'a' => "1089-10-40"}, # needs to be *exact* %({"a": " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "}, %({"a": "2007-01-01 : it's your birthday"}) => {'a' => "2007-01-01 : it's your birthday"}, -- cgit v1.2.3 From e8c870726a67a27965b2a5333a5ecf450d4f458f Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sat, 12 Feb 2011 16:29:17 +0100 Subject: Updated the json date regex to recognize xmlschema formatted date times during json decoding. [#3031 state:resolved] Signed-off-by: Santiago Pastorino and Emilio Tagua --- activesupport/lib/active_support/json/encoding.rb | 2 +- activesupport/test/json/decoding_test.rb | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index b2ea196003..82b8a7e148 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -23,7 +23,7 @@ module ActiveSupport module JSON # matches YAML-formatted dates - DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/ + DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/ # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. def self.encode(value, options = nil) diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 77f24f0de3..24d9f88c09 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -21,6 +21,10 @@ class TestJSONDecoding < ActiveSupport::TestCase %({"a": "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"}, # invalid date %({"a": "1089-10-40"}) => {'a' => "1089-10-40"}, + # xmlschema date notation + %({"a": "2009-08-10T19:01:02Z"}) => {'a' => Time.utc(2009, 8, 10, 19, 1, 2)}, + %({"a": "2009-08-10T19:01:02+02:00"}) => {'a' => Time.utc(2009, 8, 10, 17, 1, 2)}, + %({"a": "2009-08-10T19:01:02-05:00"}) => {'a' => Time.utc(2009, 8, 11, 00, 1, 2)}, # needs to be *exact* %({"a": " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "}, %({"a": "2007-01-01 : it's your birthday"}) => {'a' => "2007-01-01 : it's your birthday"}, -- cgit v1.2.3 From 944d314244676932eb1aa285d23f7d91f0678e68 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 13 Feb 2011 02:10:13 -0200 Subject: Add Date#rfc3339 and Date#iso8601 to AS --- activesupport/lib/active_support/core_ext/date/conversions.rb | 6 ++++++ activesupport/test/core_ext/date_ext_test.rb | 10 ++++++++++ 2 files changed, 16 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb index 06d868a3b0..769ead9544 100644 --- a/activesupport/lib/active_support/core_ext/date/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date/conversions.rb @@ -93,6 +93,12 @@ class Date ::DateTime.civil(year, month, day, 0, 0, 0, 0) end if RUBY_VERSION < '1.9' + def iso8601 + strftime('%F') + end if RUBY_VERSION < '1.9' + + alias_method :rfc3339, :iso8601 if RUBY_VERSION < '1.9' + def xmlschema to_time_in_current_zone.xmlschema end diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index 342a31cdef..b4d7633e5f 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -376,6 +376,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end + if RUBY_VERSION < '1.9' + def test_rfc3339 + assert_equal('1980-02-28', Date.new(1980, 2, 28).rfc3339) + end + + def test_iso8601 + assert_equal('1980-02-28', Date.new(1980, 2, 28).iso8601) + end + end + def test_today Date.stubs(:current).returns(Date.new(2000, 1, 1)) assert_equal false, Date.new(1999, 12, 31).today? -- cgit v1.2.3 From 25e3d2caf4a4d567c1087db326cee3dfe15151a3 Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Mon, 14 Feb 2011 20:41:32 -0500 Subject: Correct bad wording in description. --- activesupport/lib/active_support/core_ext/string/inflections.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb index 55b24b0925..2f0676f567 100644 --- a/activesupport/lib/active_support/core_ext/string/inflections.rb +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -3,7 +3,7 @@ require 'active_support/inflector/inflections' require 'active_support/inflector/transliterate' # String inflections define new methods on the String class to transform names for different purposes. -# For instance, you can figure out the name of a database from the name of a class. +# For instance, you can figure out the name of a table from the name of a class. # # "ScaleScore".tableize # => "scale_scores" # -- cgit v1.2.3 From ef573342106369b07bb5c97a0db0b121d6d18621 Mon Sep 17 00:00:00 2001 From: Joel Nimety Date: Tue, 15 Feb 2011 14:21:33 -0500 Subject: GcTime incorrectly checks GC.respond_to?(:total_time), it should check GC::Profiler.respond_to?(:total_time) [#6435 state:committed] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/testing/performance.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb index 64b436ba8c..8c91a061fb 100644 --- a/activesupport/lib/active_support/testing/performance.rb +++ b/activesupport/lib/active_support/testing/performance.rb @@ -401,7 +401,7 @@ begin Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME) # Ruby 1.9 with GC::Profiler - if GC.respond_to?(:total_time) + if defined?(GC::Profiler) && GC::Profiler.respond_to?(:total_time) def measure GC::Profiler.total_time end -- cgit v1.2.3 From 2eed9286ce3af77d29bdd20b4c2a5fa93baf03b1 Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Tue, 15 Feb 2011 21:32:27 -0500 Subject: Remove unused code. [#6437 state:committed] Signed-off-by: Santiago Pastorino --- activesupport/test/core_ext/module_test.rb | 3 --- 1 file changed, 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 75404ec0e1..9f9840834d 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -26,9 +26,6 @@ module Yz end end -class De -end - Somewhere = Struct.new(:street, :city) Someone = Struct.new(:name, :place) do -- cgit v1.2.3 From 1754bd9b208e8d9207c226d1ffb3cee490856a78 Mon Sep 17 00:00:00 2001 From: Dan Pickett Date: Mon, 7 Feb 2011 21:39:46 -0500 Subject: handle double pluralization for irregular plurals [#6363] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/inflections.rb | 4 ++++ activesupport/test/inflector_test.rb | 7 +++++++ activesupport/test/inflector_test_cases.rb | 1 + 3 files changed, 12 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb index e7b5387ed7..06ceccdb22 100644 --- a/activesupport/lib/active_support/inflections.rb +++ b/activesupport/lib/active_support/inflections.rb @@ -4,10 +4,12 @@ module ActiveSupport inflect.plural(/s$/i, 's') inflect.plural(/(ax|test)is$/i, '\1es') inflect.plural(/(octop|vir)us$/i, '\1i') + inflect.plural(/(octop|vir)i$/i, '\1i') inflect.plural(/(alias|status)$/i, '\1es') inflect.plural(/(bu)s$/i, '\1ses') inflect.plural(/(buffal|tomat)o$/i, '\1oes') inflect.plural(/([ti])um$/i, '\1a') + inflect.plural(/([ti])a$/i, '\1a') inflect.plural(/sis$/i, 'ses') inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves') inflect.plural(/(hive)$/i, '\1s') @@ -15,7 +17,9 @@ module ActiveSupport inflect.plural(/(x|ch|ss|sh)$/i, '\1es') inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices') inflect.plural(/([m|l])ouse$/i, '\1ice') + inflect.plural(/([m|l])ice$/i, '\1ice') inflect.plural(/^(ox)$/i, '\1en') + inflect.plural(/^(oxen)$/i, '\1') inflect.plural(/(quiz)$/i, '\1zes') inflect.singular(/s$/i, '') diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index 60714a152d..f55116dfab 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -63,6 +63,13 @@ class InflectorTest < Test::Unit::TestCase assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(plural.capitalize)) end end + + SingularToPlural.each do |singular, plural| + define_method "test_pluralize_#{plural}" do + assert_equal(plural, ActiveSupport::Inflector.pluralize(plural)) + assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(plural.capitalize)) + end + end def test_overwrite_previous_inflectors assert_equal("series", ActiveSupport::Inflector.singularize("series")) diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb index 59515dad32..2b144e5931 100644 --- a/activesupport/test/inflector_test_cases.rb +++ b/activesupport/test/inflector_test_cases.rb @@ -44,6 +44,7 @@ module InflectorTestCases "datum" => "data", "medium" => "media", + "stadium" => "stadia", "analysis" => "analyses", "node_child" => "node_children", -- cgit v1.2.3 From b131cfba055bfbf25f3785c5235c1edbf04ff9f1 Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Thu, 17 Feb 2011 00:09:49 -0500 Subject: Remove unused line in test setup. [#6442 state:committed] Signed-off-by: Santiago Pastorino --- activesupport/test/core_ext/module_test.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 9f9840834d..a95cf1591f 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -30,7 +30,6 @@ Somewhere = Struct.new(:street, :city) Someone = Struct.new(:name, :place) do delegate :street, :city, :to_f, :to => :place - delegate :state, :to => :@place delegate :upcase, :to => "place.city" end -- cgit v1.2.3 From d9eb007edf6999d2ad8ba09f9c5f03d1b0cea4e5 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 18 Feb 2011 16:05:24 -0300 Subject: WeakHash is not used, remove it. --- activesupport/lib/active_support/weak_hash.rb | 41 --------------------------- activesupport/test/weak_hash_test.rb | 33 --------------------- 2 files changed, 74 deletions(-) delete mode 100644 activesupport/lib/active_support/weak_hash.rb delete mode 100644 activesupport/test/weak_hash_test.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/weak_hash.rb b/activesupport/lib/active_support/weak_hash.rb deleted file mode 100644 index d6096e606e..0000000000 --- a/activesupport/lib/active_support/weak_hash.rb +++ /dev/null @@ -1,41 +0,0 @@ -module ActiveSupport - if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' - WeakHash = ::Weakling::WeakHash - else - class WeakHash - def initialize(cache = Hash.new) - @cache = cache - @key_map = {} - @rev_cache = Hash.new{|h,k| h[k] = {}} - @reclaim_value = lambda do |value_id| - if value = @rev_cache.delete(value_id) - value.each_key{|key| @cache.delete key} - end - end - end - - def [](key) - value_id = @cache[key] - value_id && ObjectSpace._id2ref(value_id) - rescue RangeError - nil - end - - def []=(key, value) - @rev_cache[value.object_id][key] = true - @cache[key] = value.object_id - @key_map[key.object_id] = key - - ObjectSpace.define_finalizer(value, @reclaim_value) - end - - def clear - @cache.clear - end - - def delete(key) - @cache.delete(key) - end - end - end -end diff --git a/activesupport/test/weak_hash_test.rb b/activesupport/test/weak_hash_test.rb deleted file mode 100644 index 7d1620dc34..0000000000 --- a/activesupport/test/weak_hash_test.rb +++ /dev/null @@ -1,33 +0,0 @@ -require 'abstract_unit' -require 'active_support/weak_hash' - -class WeakHashTest < ActiveSupport::TestCase - - def setup - @weak_hash = ActiveSupport::WeakHash.new - @str = "A"; - @obj = Object.new - end - - test "allows us to assign value, and return assigned value" do - a = @str; b = @obj - assert_equal @weak_hash[a] = b, b - end - - test "should allow us to assign and read value" do - a = @str; b = @obj - assert_equal @weak_hash[a] = b, b - assert_equal @weak_hash[a], b - end - - test "should use object_id to identify objects" do - a = Object.new - @weak_hash[a] = "b" - assert_nil @weak_hash[a.dup] - end - - test "should find objects that have same hash" do - @weak_hash["a"] = "b" - assert_equal "b", @weak_hash["a"] - end -end -- cgit v1.2.3 From b3e5e25829451acf28c64886b6d9117d2430f7be Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Sat, 19 Feb 2011 12:15:51 -0500 Subject: Add a clearer example for with_options (lifted from the Active Support guide). --- .../active_support/core_ext/object/with_options.rb | 24 +++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb index 3209cf7f11..33aeeb2391 100644 --- a/activesupport/lib/active_support/core_ext/object/with_options.rb +++ b/activesupport/lib/active_support/core_ext/object/with_options.rb @@ -7,13 +7,27 @@ class Object # provided. Each method called on the block variable must take an options # hash as its final argument. # - # with_options :order => 'created_at', :class_name => 'Comment' do |post| - # post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all - # post.has_many :unapproved_comments, :conditions => ['approved = ?', false] - # post.has_many :all_comments + # Without with_options, this code contains duplication: + # + # class Account < ActiveRecord::Base + # has_many :customers, :dependent => :destroy + # has_many :products, :dependent => :destroy + # has_many :invoices, :dependent => :destroy + # has_many :expenses, :dependent => :destroy + # end + # + # Using with_options, we can remove the duplication: + # + # class Account < ActiveRecord::Base + # with_options :dependent => :destroy do |assoc| + # assoc.has_many :customers + # assoc.has_many :products + # assoc.has_many :invoices + # assoc.has_many :expenses + # end # end # - # Can also be used with an explicit receiver: + # It also be used with an explicit receiver: # # map.with_options :controller => "people" do |people| # people.connect "/people", :action => "index" -- cgit v1.2.3 From 262dd965df5c46d674f76928a46a76c6132c9e35 Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Sat, 19 Feb 2011 12:56:55 -0500 Subject: Improve clarity of example. Make it follow guidelines for output display. --- .../core_ext/module/attr_accessor_with_default.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb index 0b6731883c..e3259a0a84 100644 --- a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb +++ b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb @@ -7,11 +7,11 @@ class Module # attr_accessor_with_default :age, 25 # end # - # some_person.age - # => 25 - # some_person.age = 26 - # some_person.age - # => 26 + # person = Person.new + # person.age # => 25 + # + # person.age = 26 + # person.age # => 26 # # To give attribute :element_name a dynamic default value, evaluated # in scope of self: -- cgit v1.2.3 From cff0aebbc4e4a3c586066eb289e667de0962aedb Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Sat, 19 Feb 2011 13:04:22 -0500 Subject: Add a forgotten word. --- activesupport/lib/active_support/core_ext/object/with_options.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb index 33aeeb2391..c23afabfdb 100644 --- a/activesupport/lib/active_support/core_ext/object/with_options.rb +++ b/activesupport/lib/active_support/core_ext/object/with_options.rb @@ -27,7 +27,7 @@ class Object # end # end # - # It also be used with an explicit receiver: + # It can also be used with an explicit receiver: # # map.with_options :controller => "people" do |people| # people.connect "/people", :action => "index" -- cgit v1.2.3 From b0da0dd8345b68a4e54c52e398cc65bbc0c4fbb5 Mon Sep 17 00:00:00 2001 From: Diego Carrion Date: Sat, 19 Feb 2011 21:13:07 -0200 Subject: added Range#count? for Ruby 1.8 Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/core_ext/range.rb | 1 + activesupport/lib/active_support/core_ext/range/cover.rb | 3 +++ activesupport/test/core_ext/range_ext_test.rb | 12 ++++++++++++ 3 files changed, 16 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/range/cover.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb index c0736f3a44..2428a02242 100644 --- a/activesupport/lib/active_support/core_ext/range.rb +++ b/activesupport/lib/active_support/core_ext/range.rb @@ -2,3 +2,4 @@ require 'active_support/core_ext/range/blockless_step' 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/cover' diff --git a/activesupport/lib/active_support/core_ext/range/cover.rb b/activesupport/lib/active_support/core_ext/range/cover.rb new file mode 100644 index 0000000000..3a182cddd2 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/range/cover.rb @@ -0,0 +1,3 @@ +class Range + alias_method(:cover?, :include?) unless instance_methods.include?(:cover?) +end diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb index 5701eeef28..1424fa4aca 100644 --- a/activesupport/test/core_ext/range_ext_test.rb +++ b/activesupport/test/core_ext/range_ext_test.rb @@ -62,4 +62,16 @@ class RangeTest < Test::Unit::TestCase (1..10).step(2) {|i| array << i } assert_equal [1,3,5,7,9], array end + + if RUBY_VERSION < '1.9' + def test_cover + assert((1..3).cover?(2)) + assert !(1..3).cover?(4) + end + else + def test_cover_is_not_override + range = (1..3) + assert range.method(:include?) != range.method(:cover?) + end + end end -- cgit v1.2.3 From 89e6b193564075c89b1e0fc24b8184240ea6d324 Mon Sep 17 00:00:00 2001 From: wycats Date: Sun, 20 Feb 2011 01:10:34 -0800 Subject: Add tests for an FSSM backend for the file system watcher using the FSSM polling support. --- activesupport/test/file_watcher_test.rb | 153 ++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) (limited to 'activesupport') diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb index 3e577df5af..1394c66d9f 100644 --- a/activesupport/test/file_watcher_test.rb +++ b/activesupport/test/file_watcher_test.rb @@ -1,4 +1,7 @@ require 'abstract_unit' +require 'fssm' +require "fileutils" + class FileWatcherTest < ActiveSupport::TestCase class DumbBackend < ActiveSupport::FileWatcher::Backend @@ -73,3 +76,153 @@ class FileWatcherTest < ActiveSupport::TestCase assert_equal [:changed => ["app/assets/main.scss", "app/assets/print.scss"]], @payload end end + +module FSSM::Backends + class Polling + def initialize(options={}) + @handlers = [] + @latency = options[:latency] || 0.1 + end + + def add_handler(handler, preload=true) + handler.refresh(nil, true) if preload + @handlers << handler + end + + def run + begin + loop do + start = Time.now.to_f + @handlers.each { |handler| handler.refresh } + nap_time = @latency - (Time.now.to_f - start) + sleep nap_time if nap_time > 0 + end + rescue Interrupt + end + end + end +end + +class FSSMFileWatcherTest < ActiveSupport::TestCase + class FSSMBackend < ActiveSupport::FileWatcher::Backend + def initialize(path, watcher) + super + + monitor = FSSM::Monitor.new + monitor.path(path, '**/*') do |monitor| + monitor.update { |base, relative| trigger relative => :changed } + monitor.delete { |base, relative| trigger relative => :deleted } + monitor.create { |base, relative| trigger relative => :created } + end + + @thread = Thread.new do + monitor.run + end + end + + def stop + @thread.kill + end + end + + def setup + Thread.abort_on_exception = true + + @watcher = ActiveSupport::FileWatcher.new + + @path = path = File.expand_path("../tmp", __FILE__) + FileUtils.rm_rf path + + create "app/assets/main.scss", true + create "app/assets/javascripts/foo.coffee", true + create "app/assets/print.scss", true + create "app/assets/videos.scss", true + + @backend = FSSMBackend.new(path, @watcher) + + @payload = [] + + @watcher.watch %r{^app/assets/.*\.scss$} do |pay| + pay.each do |status, files| + files.sort! + end + @payload << pay + end + end + + def teardown + @backend.stop + Thread.abort_on_exception = false + end + + def create(path, past = false) + path = File.join(@path, path) + FileUtils.mkdir_p(File.dirname(path)) + + FileUtils.touch(path) + File.utime(Time.now - 100, Time.now - 100, path) if past + sleep 0.1 unless past + end + + def change(path) + FileUtils.touch(File.join(@path, path)) + sleep 0.1 + end + + def delete(path) + FileUtils.rm(File.join(@path, path)) + sleep 0.1 + end + + def test_one_change + change "app/assets/main.scss" + assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first) + end + + def test_multiple_changes + change "app/assets/main.scss" + change "app/assets/javascripts/foo.coffee" + assert_equal([{:changed => ["app/assets/main.scss"]}], @payload) + end + + def test_multiple_changes_match + change "app/assets/main.scss" + change "app/assets/print.scss" + change "app/assets/javascripts/foo.coffee" + assert_equal([{:changed => ["app/assets/main.scss"]}, {:changed => ["app/assets/print.scss"]}], @payload) + end + + def test_multiple_state_changes + create "app/assets/new.scss" + change "app/assets/print.scss" + delete "app/assets/videos.scss" + assert_equal([{:created => ["app/assets/new.scss"]}, {:changed => ["app/assets/print.scss"]}, {:deleted => ["app/assets/videos.scss"]}], @payload) + end + + def test_delete + + end + + def test_more_blocks + payload = [] + @watcher.watch %r{^config/routes\.rb$} do |pay| + payload << pay + end + + create "config/routes.rb" + assert_equal [{:created => ["config/routes.rb"]}], payload + assert_equal [], @payload + end + + def test_overlapping_watchers + payload = [] + @watcher.watch %r{^app/assets/main\.scss$} do |pay| + payload << pay + end + + change "app/assets/main.scss" + change "app/assets/print.scss" + assert_equal [{:changed => ["app/assets/main.scss"]}], payload + assert_equal [{:changed => ["app/assets/main.scss"]}, {:changed => ["app/assets/print.scss"]}], @payload + end +end -- cgit v1.2.3 From e984fd43d56797874c532b7d45af8240decfd5ba Mon Sep 17 00:00:00 2001 From: wycats Date: Sun, 20 Feb 2011 01:37:37 -0800 Subject: Allow tests to proceed as soon as the payload changes, instead of always having to wait for a timeout --- activesupport/test/file_watcher_test.rb | 52 +++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 15 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb index 1394c66d9f..027453f86a 100644 --- a/activesupport/test/file_watcher_test.rb +++ b/activesupport/test/file_watcher_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' require 'fssm' require "fileutils" +require "timeout" class FileWatcherTest < ActiveSupport::TestCase @@ -128,6 +129,9 @@ class FSSMFileWatcherTest < ActiveSupport::TestCase def setup Thread.abort_on_exception = true + @payload = [] + @triggered = false + @watcher = ActiveSupport::FileWatcher.new @path = path = File.expand_path("../tmp", __FILE__) @@ -140,13 +144,12 @@ class FSSMFileWatcherTest < ActiveSupport::TestCase @backend = FSSMBackend.new(path, @watcher) - @payload = [] - @watcher.watch %r{^app/assets/.*\.scss$} do |pay| pay.each do |status, files| files.sort! end @payload << pay + trigger end end @@ -156,22 +159,43 @@ class FSSMFileWatcherTest < ActiveSupport::TestCase end def create(path, past = false) - path = File.join(@path, path) - FileUtils.mkdir_p(File.dirname(path)) + wait(past) do + path = File.join(@path, path) + FileUtils.mkdir_p(File.dirname(path)) - FileUtils.touch(path) - File.utime(Time.now - 100, Time.now - 100, path) if past - sleep 0.1 unless past + FileUtils.touch(path) + File.utime(Time.now - 100, Time.now - 100, path) if past + end end def change(path) - FileUtils.touch(File.join(@path, path)) - sleep 0.1 + wait do + FileUtils.touch(File.join(@path, path)) + end end def delete(path) - FileUtils.rm(File.join(@path, path)) - sleep 0.1 + wait do + FileUtils.rm(File.join(@path, path)) + end + end + + def wait(past = false) + yield + return if past + + begin + Timeout.timeout(1) do + sleep 0.05 until @triggered + end + rescue Timeout::Error + end + + @triggered = false + end + + def trigger + @triggered = true end def test_one_change @@ -199,14 +223,11 @@ class FSSMFileWatcherTest < ActiveSupport::TestCase assert_equal([{:created => ["app/assets/new.scss"]}, {:changed => ["app/assets/print.scss"]}, {:deleted => ["app/assets/videos.scss"]}], @payload) end - def test_delete - - end - def test_more_blocks payload = [] @watcher.watch %r{^config/routes\.rb$} do |pay| payload << pay + trigger end create "config/routes.rb" @@ -218,6 +239,7 @@ class FSSMFileWatcherTest < ActiveSupport::TestCase payload = [] @watcher.watch %r{^app/assets/main\.scss$} do |pay| payload << pay + trigger end change "app/assets/main.scss" -- cgit v1.2.3 From 6c30530b000c69f6283381d6ff85dcfef916ebbc Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 20 Feb 2011 11:01:07 +0100 Subject: adds Range#cover? to the CHANGELOG --- activesupport/CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 6e8cce0d27..1b8bcf649c 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.1.0 (unreleased)* +* Backports Range#cover? as an alias for Range#include? in Ruby 1.8 [Diego Carrion, fxn] + * Added weeks_ago and prev_week to Date/DateTime/Time. [Rob Zolkos, fxn] * Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White] -- cgit v1.2.3 From 839d06f5f28740a9641a1b91e5df94f64e224547 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Wed, 5 Jan 2011 03:58:45 +0700 Subject: We're in 2011, let's update our license Signed-off-by: Santiago Pastorino --- activesupport/MIT-LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/MIT-LICENSE b/activesupport/MIT-LICENSE index cd928b856d..5e8b7a9450 100644 --- a/activesupport/MIT-LICENSE +++ b/activesupport/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2005-2010 David Heinemeier Hansson +Copyright (c) 2005-2011 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the -- cgit v1.2.3 From 3265bbb65998d8175f3cd087f355a007bf4d2d47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 22 Feb 2011 22:51:02 +0100 Subject: Fix tests on 1.8. --- activesupport/test/buffered_logger_test.rb | 4 +--- activesupport/test/file_watcher_test.rb | 31 +++++++----------------------- 2 files changed, 8 insertions(+), 27 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb index 97c0ef14db..8d1b1c02c6 100644 --- a/activesupport/test/buffered_logger_test.rb +++ b/activesupport/test/buffered_logger_test.rb @@ -115,11 +115,9 @@ class BufferedLoggerTest < Test::Unit::TestCase def test_should_create_the_log_directory_if_it_doesnt_exist tmp_directory = File.join(File.dirname(__FILE__), "tmp") log_file = File.join(tmp_directory, "development.log") - assert !File.exist?(tmp_directory) + FileUtils.rm_rf(tmp_directory) @logger = Logger.new(log_file) assert File.exist?(tmp_directory) - ensure - FileUtils.rm_rf(tmp_directory) end def test_logger_should_maintain_separate_buffers_for_each_thread diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb index 027453f86a..7b4d4be24f 100644 --- a/activesupport/test/file_watcher_test.rb +++ b/activesupport/test/file_watcher_test.rb @@ -80,27 +80,10 @@ end module FSSM::Backends class Polling - def initialize(options={}) - @handlers = [] - @latency = options[:latency] || 0.1 - end - - def add_handler(handler, preload=true) - handler.refresh(nil, true) if preload - @handlers << handler - end - - def run - begin - loop do - start = Time.now.to_f - @handlers.each { |handler| handler.refresh } - nap_time = @latency - (Time.now.to_f - start) - sleep nap_time if nap_time > 0 - end - rescue Interrupt - end + def initialize_with_low_latency(options={}) + initialize_without_low_latency(options.merge(:latency => 0.1)) end + alias_method_chain :initialize, :low_latency end end @@ -110,10 +93,10 @@ class FSSMFileWatcherTest < ActiveSupport::TestCase super monitor = FSSM::Monitor.new - monitor.path(path, '**/*') do |monitor| - monitor.update { |base, relative| trigger relative => :changed } - monitor.delete { |base, relative| trigger relative => :deleted } - monitor.create { |base, relative| trigger relative => :created } + monitor.path(path, '**/*') do |p| + p.update { |base, relative| trigger relative => :changed } + p.delete { |base, relative| trigger relative => :deleted } + p.create { |base, relative| trigger relative => :created } end @thread = Thread.new do -- cgit v1.2.3 From f42562f97bb791a7662fce0106a93eec211b2803 Mon Sep 17 00:00:00 2001 From: "Oriol Gual and Josep M. Bach" Date: Mon, 28 Feb 2011 14:31:29 +0100 Subject: Make ActiveSupport::Configurable work with modules [#6486 state:committed] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/configurable.rb | 2 +- activesupport/test/configurable_test.rb | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb index 644db0b205..be19189c04 100644 --- a/activesupport/lib/active_support/configurable.rb +++ b/activesupport/lib/active_support/configurable.rb @@ -26,7 +26,7 @@ module ActiveSupport module ClassMethods def config - @_config ||= if superclass.respond_to?(:config) + @_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config) superclass.config.inheritable_copy else # create a new "anonymous" class that will host the compiled reader methods diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb index 9c773c1944..2b28e61815 100644 --- a/activesupport/test/configurable_test.rb +++ b/activesupport/test/configurable_test.rb @@ -21,6 +21,12 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase assert_equal({ :foo => :bar }, Parent.config) end + test "adds a configuration hash to a module as well" do + mixin = Module.new { include ActiveSupport::Configurable } + mixin.config.foo = :bar + assert_equal({ :foo => :bar }, mixin.config) + end + test "configuration hash is inheritable" do assert_equal :bar, Child.config.foo assert_equal :bar, Parent.config.foo @@ -57,4 +63,4 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase assert_respond_to child.config, :bar assert_respond_to child.new.config, :bar end -end \ No newline at end of file +end -- cgit v1.2.3 From 726599df984daca45afe5b969c74b416fcd6c11a Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Mon, 28 Feb 2011 10:52:09 -0500 Subject: Remove redundant to_sym call. [#6483 state:committed] Signed-off-by: Santiago Pastorino --- activesupport/lib/active_support/ordered_options.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb index 124e1a74f8..b40cbceb7e 100644 --- a/activesupport/lib/active_support/ordered_options.rb +++ b/activesupport/lib/active_support/ordered_options.rb @@ -31,7 +31,7 @@ module ActiveSupport #:nodoc: def method_missing(name, *args) if name.to_s =~ /(.*)=$/ - self[$1.to_sym] = args.first + self[$1] = args.first else self[name] end -- cgit v1.2.3 From 0f8d2794f229175447163d2b5e16d94d2cee5468 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sun, 27 Feb 2011 20:24:39 +0100 Subject: updated Time, Date and DateTime current methods in AS to use Time.zone and not Time.zone_default. [#6410 state:committed] --- .../active_support/core_ext/date/calculations.rb | 4 +-- .../lib/active_support/core_ext/date/zones.rb | 6 ++-- .../core_ext/date_time/calculations.rb | 3 +- .../active_support/core_ext/time/calculations.rb | 4 +-- activesupport/test/core_ext/date_ext_test.rb | 32 +++++++++++----------- activesupport/test/core_ext/date_time_ext_test.rb | 8 +++--- activesupport/test/core_ext/duration_test.rb | 10 +++---- activesupport/test/core_ext/numeric_ext_test.rb | 10 +++---- activesupport/test/core_ext/time_with_zone_test.rb | 15 +++++----- 9 files changed, 47 insertions(+), 45 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb index f34185f22c..724e076407 100644 --- a/activesupport/lib/active_support/core_ext/date/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date/calculations.rb @@ -36,9 +36,9 @@ class Date ::Date.current.tomorrow end - # Returns Time.zone.today when config.time_zone is set, otherwise just returns Date.today. + # Returns Time.zone.today when Time.zone or config.time_zone are set, otherwise just returns Date.today. def current - ::Time.zone_default ? ::Time.zone.today : ::Date.today + ::Time.zone ? ::Time.zone.today : ::Date.today end end diff --git a/activesupport/lib/active_support/core_ext/date/zones.rb b/activesupport/lib/active_support/core_ext/date/zones.rb index 3a83af6be2..a70b47b7bc 100644 --- a/activesupport/lib/active_support/core_ext/date/zones.rb +++ b/activesupport/lib/active_support/core_ext/date/zones.rb @@ -2,10 +2,10 @@ require 'date' require 'active_support/core_ext/time/zones' class Date - # Converts Date to a TimeWithZone in the current zone if Time.zone_default is set, - # otherwise converts Date to a Time via Date#to_time + # 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 def to_time_in_current_zone - if ::Time.zone_default + if ::Time.zone ::Time.zone.local(year, month, day) else to_time 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 1dc3933e12..8d01376f1d 100644 --- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb @@ -9,8 +9,9 @@ class DateTime ::Time.local(2007).utc_offset.to_r / 86400 end + # Returns Time.zone.now.to_datetime when Time.zone or config.time_zone are set, otherwise returns Time.now.to_datetime. def current - ::Time.zone_default ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime + ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime end end diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb index fa052fa86b..6e4b69f681 100644 --- a/activesupport/lib/active_support/core_ext/time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/time/calculations.rb @@ -41,9 +41,9 @@ class Time time_with_datetime_fallback(:local, *args) end - # Returns Time.zone.now when config.time_zone is set, otherwise just returns Time.now. + # Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now. def current - ::Time.zone_default ? ::Time.zone.now : ::Time.now + ::Time.zone ? ::Time.zone.now : ::Time.now end end diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index b4d7633e5f..03b84ae2e5 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -259,7 +259,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Date.current - 1, Date.yesterday end - def test_yesterday_constructor_when_zone_default_is_not_set + def test_yesterday_constructor_when_zone_is_not_set with_env_tz 'UTC' do with_tz_default do Time.stubs(:now).returns Time.local(2000, 1, 1) @@ -268,7 +268,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end - def test_yesterday_constructor_when_zone_default_is_set + def test_yesterday_constructor_when_zone_is_set with_env_tz 'UTC' do with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5 Time.stubs(:now).returns Time.local(2000, 1, 1) @@ -281,7 +281,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Date.current + 1, Date.tomorrow end - def test_tomorrow_constructor_when_zone_default_is_not_set + def test_tomorrow_constructor_when_zone_is_not_set with_env_tz 'UTC' do with_tz_default do Time.stubs(:now).returns Time.local(1999, 12, 31) @@ -290,7 +290,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end - def test_tomorrow_constructor_when_zone_default_is_set + def test_tomorrow_constructor_when_zone_is_set with_env_tz 'UTC' do with_tz_default ActiveSupport::TimeZone['Europe/Paris'] do # UTC +1 Time.stubs(:now).returns Time.local(1999, 12, 31, 23) @@ -303,7 +303,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,2,21,0,0,45), Date.new(2005,2,21).since(45) end - def test_since_when_zone_default_is_set + def test_since_when_zone_is_set zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'UTC' do with_tz_default zone do @@ -317,7 +317,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,2,20,23,59,15), Date.new(2005,2,21).ago(45) end - def test_ago_when_zone_default_is_set + def test_ago_when_zone_is_set zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'UTC' do with_tz_default zone do @@ -331,7 +331,7 @@ 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_beginning_of_day_when_zone_default_is_set + def test_beginning_of_day_when_zone_is_set zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'UTC' do with_tz_default zone do @@ -345,7 +345,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,2,21,23,59,59,999999.999), Date.new(2005,2,21).end_of_day end - def test_end_of_day_when_zone_default_is_set + def test_end_of_day_when_zone_is_set zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'UTC' do with_tz_default zone do @@ -367,7 +367,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end - def test_xmlschema_when_zone_default_is_set + def test_xmlschema_when_zone_is_set with_env_tz 'UTC' do with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5 assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema) @@ -407,7 +407,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal true, Date.new(2000,1,2).future? end - def test_current_returns_date_today_when_zone_default_not_set + def test_current_returns_date_today_when_zone_not_set with_env_tz 'US/Central' do Time.stubs(:now).returns Time.local(1999, 12, 31, 23) assert_equal Date.new(1999, 12, 31), Date.today @@ -415,15 +415,15 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end - def test_current_returns_time_zone_today_when_zone_default_set - Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + def test_current_returns_time_zone_today_when_zone_is_set + Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'US/Central' do Time.stubs(:now).returns Time.local(1999, 12, 31, 23) assert_equal Date.new(1999, 12, 31), Date.today assert_equal Date.new(2000, 1, 1), Date.current end ensure - Time.zone_default = nil + Time.zone = nil end def test_date_advance_should_not_change_passed_options_hash @@ -441,11 +441,11 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end def with_tz_default(tz = nil) - old_tz = Time.zone_default - Time.zone_default = tz + old_tz = Time.zone + Time.zone = tz yield ensure - Time.zone_default = old_tz + Time.zone = old_tz 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 8edb95b63a..456736cbad 100644 --- a/activesupport/test/core_ext/date_time_ext_test.rb +++ b/activesupport/test/core_ext/date_time_ext_test.rb @@ -282,21 +282,21 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase assert_equal true, DateTime.civil(2005,2,10,20,30,46).future? end - def test_current_returns_date_today_when_zone_default_not_set + def test_current_returns_date_today_when_zone_is_not_set with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59) assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current end end - def test_current_returns_time_zone_today_when_zone_default_set - Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + def test_current_returns_time_zone_today_when_zone_is_set + Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59) assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current end ensure - Time.zone_default = nil + Time.zone = nil end def test_current_without_time_zone diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index 6a01eeed6b..c0b529d9f8 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -89,8 +89,8 @@ class DurationTest < ActiveSupport::TestCase assert_in_delta((7 * 24 * 1.7).hours.ago(t), 1.7.weeks.ago(t), 1) end - def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set - Time.zone_default = nil + def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set + Time.zone = nil with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(2000) # since @@ -102,8 +102,8 @@ class DurationTest < ActiveSupport::TestCase end end - def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set - Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set + Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(2000) # since @@ -116,7 +116,7 @@ class DurationTest < ActiveSupport::TestCase assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name end ensure - Time.zone_default = nil + Time.zone = nil end def test_adding_hours_across_dst_boundary diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb index 6ef4e37b26..3a2452b4b0 100644 --- a/activesupport/test/core_ext/numeric_ext_test.rb +++ b/activesupport/test/core_ext/numeric_ext_test.rb @@ -89,8 +89,8 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10) + 1.year end - def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set - Time.zone_default = nil + def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set + Time.zone = nil with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(2000) # since @@ -102,8 +102,8 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase end end - def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set - Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set + Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(2000) # since @@ -116,7 +116,7 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase assert_equal 'Eastern Time (US & Canada)', 5.ago.time_zone.name end ensure - Time.zone_default = nil + Time.zone = nil end protected diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 5c226c2d09..bafa335a09 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -768,10 +768,10 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase end def test_localtime - Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] assert_equal @dt.in_time_zone.localtime, @dt.in_time_zone.utc.to_time.getlocal ensure - Time.zone_default = nil + Time.zone = nil end def test_use_zone @@ -801,7 +801,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase assert_equal nil, Time.zone end - def test_time_zone_getter_and_setter_with_zone_default + def test_time_zone_getter_and_setter_with_zone_default_set Time.zone_default = ActiveSupport::TimeZone['Alaska'] assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone Time.zone = ActiveSupport::TimeZone['Hawaii'] @@ -809,6 +809,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase Time.zone = nil assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone ensure + Time.zone = nil Time.zone_default = nil end @@ -849,7 +850,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase assert_nil Time.zone end - def test_current_returns_time_now_when_zone_default_not_set + def test_current_returns_time_now_when_zone_not_set with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(2000) assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone) @@ -857,8 +858,8 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase end end - def test_current_returns_time_zone_now_when_zone_default_set - Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + def test_current_returns_time_zone_now_when_zone_set + Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'US/Eastern' do Time.stubs(:now).returns Time.local(2000) assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone) @@ -866,7 +867,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase assert_equal Time.utc(2000), Time.current.time end ensure - Time.zone_default = nil + Time.zone = nil end protected -- cgit v1.2.3