From 42a06d2d6253eed3b9f4fb4edfa251c9508a2e20 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 09:10:14 -0700 Subject: stdlib autoloads were hanging on 1.9.1 --- activesupport/lib/active_support/core_ext/string/iterators.rb | 5 ++--- activesupport/lib/active_support/json/decoding.rb | 6 ++---- activesupport/test/json/decoding_test.rb | 4 ++-- 3 files changed, 6 insertions(+), 9 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/iterators.rb b/activesupport/lib/active_support/core_ext/string/iterators.rb index 472de7bc24..2f8aa84024 100644 --- a/activesupport/lib/active_support/core_ext/string/iterators.rb +++ b/activesupport/lib/active_support/core_ext/string/iterators.rb @@ -1,11 +1,10 @@ unless '1.9'.respond_to?(:each_char) - autoload :StringScanner, 'strscan' unless defined? :StringScanner - class String # Yields a single-character string for each character in the string. # When $KCODE = 'UTF8', multi-byte characters are yielded appropriately. def each_char - scanner, char = StringScanner.new(self), /./mu + require 'strscan' unless defined? ::StringScanner + scanner, char = ::StringScanner.new(self), /./mu while c = scanner.scan(char) yield c end diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb index c66500aa9c..70e9f40fc7 100644 --- a/activesupport/lib/active_support/json/decoding.rb +++ b/activesupport/lib/active_support/json/decoding.rb @@ -1,6 +1,3 @@ -autoload :YAML, 'yaml' unless defined? YAML -autoload :StringScanner, 'strscan' unless defined? StringScanner - require 'active_support/core_ext/string/starts_ends_with' module ActiveSupport @@ -22,7 +19,8 @@ module ActiveSupport # Ensure that ":" and "," are always followed by a space def convert_json_to_yaml(json) #:nodoc: - scanner, quoting, marks, pos, times = StringScanner.new(json), false, [], nil, [] + require 'strscan' unless defined? ::StringScanner + scanner, quoting, marks, pos, times = ::StringScanner.new(json), false, [], nil, [] while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/) case char = scanner[1] when '"', "'" diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 8fe40557d6..7d8a07654d 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -1,7 +1,7 @@ # encoding: UTF-8 require 'abstract_unit' -class TestJSONDecoding < Test::Unit::TestCase +class TestJSONDecoding < ActiveSupport::TestCase TESTS = { %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, %q({returnTo:{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, @@ -36,7 +36,7 @@ class TestJSONDecoding < Test::Unit::TestCase } TESTS.each do |json, expected| - define_method :"test_json_decoding_#{json}" do + test "json decodes #{json}" do assert_nothing_raised do assert_equal expected, ActiveSupport::JSON.decode(json) end -- cgit v1.2.3 From ab321268f86d9013cbd4ecd0b5f46e7b05ec55a9 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 16:10:49 -0700 Subject: No more free lunch --- activesupport/CHANGELOG | 2 ++ activesupport/lib/active_support.rb | 3 --- activesupport/lib/active_support/core/all.rb | 1 + activesupport/lib/active_support/core_ext/kernel/requires.rb | 4 +++- 4 files changed, 6 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index e208f56455..cd7b47d780 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *Edge* +* require 'active_support' no longer orders the whole menu of core extensions. Ask for just what you need: e.g. require 'active_support/core/time' to use timezones, durations, and stdlib date/time extensions. [Jeremy Kemper] + * Removed rarely-used DRb cache store. [Jeremy Kemper] * TimeWithZone.name returns 'Time', to further thwart type checking [Geoff Buesing] diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 21b730fa0c..84bf372163 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -50,10 +50,7 @@ module ActiveSupport autoload :XmlMini, 'active_support/xml_mini' end -require 'active_support/core/all' - require 'active_support/vendor' -require 'active_support/core_ext' require 'active_support/dependencies' require 'active_support/json' diff --git a/activesupport/lib/active_support/core/all.rb b/activesupport/lib/active_support/core/all.rb index f397f48e9c..55e8b4cfac 100644 --- a/activesupport/lib/active_support/core/all.rb +++ b/activesupport/lib/active_support/core/all.rb @@ -1,3 +1,4 @@ +require 'active_support/core_ext' require 'active_support/core' Dir["#{File.dirname(__FILE__)}/*.rb"].sort.each do |path| require "active_support/core/#{File.basename(path, '.rb')}" diff --git a/activesupport/lib/active_support/core_ext/kernel/requires.rb b/activesupport/lib/active_support/core_ext/kernel/requires.rb index 323fea49fe..d2238898d6 100644 --- a/activesupport/lib/active_support/core_ext/kernel/requires.rb +++ b/activesupport/lib/active_support/core_ext/kernel/requires.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/kernel/reporting' + module Kernel # Require a library with fallback to RubyGems. Warnings during library # loading are silenced to increase signal/noise for application warnings. @@ -21,4 +23,4 @@ module Kernel end end end -end \ No newline at end of file +end -- cgit v1.2.3 From f5d720fb96f2e085acc4ed17f63272c4d38e567e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 16:41:06 -0700 Subject: Opt in to Dependencies --- activesupport/lib/active_support.rb | 1 - .../core_ext/class/delegating_attributes.rb | 2 ++ activesupport/lib/active_support/dependencies.rb | 1 + activesupport/lib/active_support/json.rb | 2 ++ .../lib/active_support/testing/deprecation.rb | 18 +++++++++--------- .../test/core_ext/module/attribute_aliasing_test.rb | 1 + activesupport/test/dependencies_test.rb | 1 + 7 files changed, 16 insertions(+), 10 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 84bf372163..f240cbf5e4 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -51,7 +51,6 @@ module ActiveSupport end require 'active_support/vendor' -require 'active_support/dependencies' require 'active_support/json' I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml" diff --git a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb index da798c67e7..b0784d8416 100644 --- a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/blank' + class Class def superclass_delegating_reader(*names) class_name_to_stop_searching_on = superclass.name.blank? ? "Object" : superclass.name diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 41b7e00c0c..1804c14618 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -1,4 +1,5 @@ require 'set' +require 'thread' require 'active_support/inflector' require 'active_support/core_ext/name_error' require 'active_support/core_ext/object/blank' diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index 2bdb4a7b11..91f19f8a70 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/attribute_accessors' + module ActiveSupport # If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format. mattr_accessor :use_standard_json_time_format diff --git a/activesupport/lib/active_support/testing/deprecation.rb b/activesupport/lib/active_support/testing/deprecation.rb index e9220605bd..0135185a47 100644 --- a/activesupport/lib/active_support/testing/deprecation.rb +++ b/activesupport/lib/active_support/testing/deprecation.rb @@ -1,3 +1,5 @@ +require 'active_support/deprecation' + module ActiveSupport module Testing module Deprecation #:nodoc: @@ -35,21 +37,19 @@ end begin require 'test/unit/error' - +rescue LoadError + # Using miniunit, ignore. +else module Test module Unit - class Error # :nodoc: + class Error #:nodoc: # Silence warnings when reporting test errors. def message_with_silenced_deprecation - ActiveSupport::Deprecation.silence do - message_without_silenced_deprecation - end + ActiveSupport::Deprecation.silence { message_without_silenced_deprecation } end - - alias_method_chain :message, :silenced_deprecation + alias_method :message_without_silenced_deprecation, :message + alias_method :message, :message_with_silenced_deprecation end end end -rescue LoadError - # Using miniunit, ignore. end diff --git a/activesupport/test/core_ext/module/attribute_aliasing_test.rb b/activesupport/test/core_ext/module/attribute_aliasing_test.rb index 570ac3b8d5..f17d031662 100644 --- a/activesupport/test/core_ext/module/attribute_aliasing_test.rb +++ b/activesupport/test/core_ext/module/attribute_aliasing_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/module/aliasing' module AttributeAliasing class Content diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index a21f09403f..01c1d67f4c 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'pp' +require 'active_support/dependencies' module ModuleWithMissing mattr_accessor :missing_count -- cgit v1.2.3 From 6fee981fa4ea2654f825c58b58327fc15fddf3a6 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 16:48:58 -0700 Subject: Opt in to JSON --- activesupport/lib/active_support.rb | 1 - activesupport/test/json/decoding_test.rb | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 84bf372163..5392faa993 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -52,6 +52,5 @@ end require 'active_support/vendor' require 'active_support/dependencies' -require 'active_support/json' I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml" diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 7d8a07654d..9b4b207c88 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -1,5 +1,6 @@ # encoding: UTF-8 require 'abstract_unit' +require 'active_support/json' class TestJSONDecoding < ActiveSupport::TestCase TESTS = { -- cgit v1.2.3 From b2d6fdae353be4fca41d7ac1839f30d9737162fd Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 17:00:33 -0700 Subject: Fix tests on 1.9 --- activesupport/lib/active_support/core_ext/class/attribute_accessors.rb | 2 ++ .../lib/active_support/core_ext/class/delegating_attributes.rb | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb index 75e481fc54..74ce85a1c2 100644 --- a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb +++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/array/extract_options' + # Extends the class object with class and instance accessors for class attributes, # just like the native attr* accessors for instance attributes. # diff --git a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb index b0784d8416..fd029544c3 100644 --- a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/blank' +require 'active_support/core_ext/object/blank' class Class def superclass_delegating_reader(*names) -- cgit v1.2.3 From 5c4ba6e3fc66a779c28a70b8d7bde14b49e7c36c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 17:17:31 -0700 Subject: new_callbacks core extensions --- activesupport/lib/active_support/new_callbacks.rb | 3 +++ activesupport/test/new_callbacks_test.rb | 10 +++++----- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 356d70b650..7a48dbac04 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -1,3 +1,6 @@ +require 'active_support/core_ext/array/wrap' +require 'active_support/core_ext/class/inheritable_attributes' + module ActiveSupport # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic # before or after an alteration of the object state. diff --git a/activesupport/test/new_callbacks_test.rb b/activesupport/test/new_callbacks_test.rb index 5cde078b65..abe7790ebf 100644 --- a/activesupport/test/new_callbacks_test.rb +++ b/activesupport/test/new_callbacks_test.rb @@ -19,11 +19,11 @@ module NewCallbacksTest class << self def callback_symbol(callback_method) - returning(:"#{callback_method}_method") do |method_name| - define_method(method_name) do - history << [callback_method, :symbol] - end + method_name = :"#{callback_method}_method" + define_method(method_name) do + history << [callback_method, :symbol] end + method_name end def callback_string(callback_method) @@ -381,4 +381,4 @@ module NewCallbacksTest assert_equal ["first", "second", "third", "second", "first"], terminator.history end end -end \ No newline at end of file +end -- cgit v1.2.3 From f28bd9557c669cd63c31704202a46dd83f0a4102 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 22 Apr 2009 17:41:28 -0700 Subject: Fix dependencies revealed by testing in isolation --- activesupport/Rakefile | 6 ++++++ activesupport/lib/active_support/cache.rb | 1 + .../lib/active_support/cache/strategy/local_cache.rb | 2 ++ activesupport/lib/active_support/callbacks.rb | 2 ++ .../lib/active_support/core_ext/array/conversions.rb | 6 +++++- .../core_ext/class/inheritable_attributes.rb | 4 +++- activesupport/lib/active_support/core_ext/class/removal.rb | 3 +++ .../lib/active_support/core_ext/date/calculations.rb | 2 ++ .../lib/active_support/core_ext/date/conversions.rb | 2 ++ activesupport/lib/active_support/core_ext/date_time.rb | 3 +-- .../lib/active_support/core_ext/hash/conversions.rb | 2 ++ activesupport/lib/active_support/core_ext/logger.rb | 5 +++-- .../lib/active_support/core_ext/module/attr_internal.rb | 8 ++++---- .../lib/active_support/core_ext/module/introspection.rb | 6 ++++-- .../lib/active_support/core_ext/module/model_naming.rb | 8 +++++--- .../lib/active_support/core_ext/module/synchronization.rb | 2 ++ activesupport/lib/active_support/core_ext/numeric/time.rb | 2 ++ activesupport/lib/active_support/core_ext/object.rb | 1 + .../lib/active_support/core_ext/range/blockless_step.rb | 2 ++ .../lib/active_support/core_ext/string/conversions.rb | 1 + .../lib/active_support/core_ext/string/multibyte.rb | 1 + activesupport/lib/active_support/dependencies.rb | 8 +++++--- .../lib/active_support/deprecation/method_wrappers.rb | 1 + .../lib/active_support/deprecation/proxy_wrappers.rb | 4 +++- activesupport/lib/active_support/duration.rb | 1 + activesupport/lib/active_support/inflector.rb | 3 ++- activesupport/lib/active_support/json/encoders/time.rb | 2 ++ activesupport/lib/active_support/memoizable.rb | 2 ++ activesupport/lib/active_support/multibyte.rb | 2 ++ activesupport/lib/active_support/testing/assertions.rb | 2 ++ activesupport/lib/active_support/time_with_zone.rb | 2 +- activesupport/lib/active_support/xml_mini.rb | 2 ++ activesupport/lib/active_support/xml_mini/rexml.rb | 2 ++ activesupport/test/buffered_logger_test.rb | 14 ++++++++------ activesupport/test/core_ext/array_ext_test.rb | 3 +++ activesupport/test/core_ext/blank_test.rb | 1 + .../test/core_ext/class/attribute_accessor_test.rb | 1 + .../core_ext/class/class_inheritable_attributes_test.rb | 1 + activesupport/test/core_ext/date_time_ext_test.rb | 1 + activesupport/test/core_ext/duplicable_test.rb | 2 ++ activesupport/test/core_ext/duration_test.rb | 1 + activesupport/test/core_ext/exception_test.rb | 1 + activesupport/test/core_ext/hash_ext_test.rb | 2 ++ .../core_ext/module/attr_accessor_with_default_test.rb | 1 + activesupport/test/core_ext/module/attr_internal_test.rb | 7 ++++--- .../test/core_ext/module/attribute_accessor_test.rb | 1 + activesupport/test/core_ext/module/model_naming_test.rb | 1 + activesupport/test/core_ext/name_error_test.rb | 1 + activesupport/test/core_ext/numeric_ext_test.rb | 5 +++-- activesupport/test/core_ext/object_and_class_ext_test.rb | 2 ++ activesupport/test/core_ext/proc_test.rb | 1 + activesupport/test/core_ext/range_ext_test.rb | 1 + activesupport/test/core_ext/string_ext_test.rb | 1 + activesupport/test/core_ext/time_ext_test.rb | 1 + activesupport/test/core_ext/time_with_zone_test.rb | 1 + activesupport/test/dependencies_test.rb | 2 ++ activesupport/test/i18n_test.rb | 2 ++ activesupport/test/inflector_test.rb | 2 ++ activesupport/test/test_test.rb | 1 + activesupport/test/time_zone_test.rb | 1 + activesupport/test/xml_mini/nokogiri_engine_test.rb | 1 + 61 files changed, 127 insertions(+), 32 deletions(-) (limited to 'activesupport') diff --git a/activesupport/Rakefile b/activesupport/Rakefile index f7fd52c7d8..a4e8200a43 100644 --- a/activesupport/Rakefile +++ b/activesupport/Rakefile @@ -21,6 +21,12 @@ Rake::TestTask.new { |t| t.verbose = true t.warning = true } +task :isolated_test do + Dir['test/**/*_test.rb'].all? do |file| + ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) + system(ruby, '-Ilib:test', file) + end or raise "Failures" +end # Create compressed packages dist_dirs = [ "lib", "test"] diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 4b2eebb007..feb6b1f2cf 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -2,6 +2,7 @@ require 'benchmark' require 'active_support/core_ext/benchmark' require 'active_support/core_ext/exception' require 'active_support/core_ext/class/attribute_accessors' +require 'active_support/core_ext' # FIXME: pulling in all to_param extensions module ActiveSupport # See ActiveSupport::Cache::Store for documentation. diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb index 84d9a0e6d8..4bbcd8e4c4 100644 --- a/activesupport/lib/active_support/cache/strategy/local_cache.rb +++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/object/duplicable' + module ActiveSupport module Cache module Strategy diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 4bac8292e2..f049189b9a 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/array/extract_options' + module ActiveSupport # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic # before or after an alteration of the object state. diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb index 81e466779e..5f1ce4142f 100644 --- a/activesupport/lib/active_support/core_ext/array/conversions.rb +++ b/activesupport/lib/active_support/core_ext/array/conversions.rb @@ -1,3 +1,7 @@ +require 'active_support/core_ext/hash/keys' +require 'active_support/core_ext/hash/reverse_merge' +require 'active_support/inflector' + class Array # Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options: # * :words_connector - The sign or word used to join the elements in arrays with two or more elements (default: ", ") @@ -155,7 +159,7 @@ class Array raise "Not all elements respond to to_xml" unless all? { |e| e.respond_to? :to_xml } require 'builder' unless defined?(Builder) - options[:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? first.class.to_s.underscore.pluralize : "records" + options[:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? ActiveSupport::Inflector.pluralize(ActiveSupport::Inflector.underscore(first.class.name)) : "records" options[:children] ||= options[:root].singularize options[:indent] ||= 2 options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb index 2f18666ab9..cca93a0b9f 100644 --- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/object/duplicable' + # Retain for backward compatibility. Methods are now included in Class. module ClassInheritableAttributes # :nodoc: end @@ -216,4 +218,4 @@ class Class extlib_inheritable_reader(*syms) extlib_inheritable_writer(*syms) end -end \ No newline at end of file +end diff --git a/activesupport/lib/active_support/core_ext/class/removal.rb b/activesupport/lib/active_support/core_ext/class/removal.rb index 10660edb2c..2dea3c24d5 100644 --- a/activesupport/lib/active_support/core_ext/class/removal.rb +++ b/activesupport/lib/active_support/core_ext/class/removal.rb @@ -1,3 +1,6 @@ +require 'active_support/core_ext/object/extending' +require 'active_support/core_ext/module/introspection' + class Class #:nodoc: # Unassociates the class with its subclasses and removes the subclasses diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb index 59efdbd1b6..04a32edefd 100644 --- a/activesupport/lib/active_support/core_ext/date/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date/calculations.rb @@ -1,3 +1,5 @@ +require 'active_support/duration' + class Date class << self # Returns a new Date representing the date 1 day ago (i.e. yesterday's date). diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb index f6c870035b..54facf4430 100644 --- a/activesupport/lib/active_support/core_ext/date/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date/conversions.rb @@ -1,4 +1,6 @@ require 'active_support/inflector' +require 'active_support/core_ext/time/conversions' +require 'active_support/core_ext/date_time/conversions' class Date DATE_FORMATS = { diff --git a/activesupport/lib/active_support/core_ext/date_time.rb b/activesupport/lib/active_support/core_ext/date_time.rb index 83a11da1c7..004fd0ad29 100644 --- a/activesupport/lib/active_support/core_ext/date_time.rb +++ b/activesupport/lib/active_support/core_ext/date_time.rb @@ -1,5 +1,4 @@ -require 'date' - +require 'active_support/core_ext/time' require 'active_support/core_ext/date_time/acts_like' require 'active_support/core_ext/date_time/calculations' require 'active_support/core_ext/date_time/conversions' diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index fa171720f9..f9dddec687 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -1,6 +1,8 @@ require 'date' require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/array/conversions' +require 'active_support/core_ext/hash/reverse_merge' +require 'active_support/core/time' class Hash # This module exists to decorate files deserialized using Hash.from_xml with diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb index 858da7aa07..22749229a3 100644 --- a/activesupport/lib/active_support/core_ext/logger.rb +++ b/activesupport/lib/active_support/core_ext/logger.rb @@ -1,6 +1,7 @@ -# Adds the 'around_level' method to Logger. +require 'active_support/core_ext/class/attribute_accessors' -class Logger +# Adds the 'around_level' method to Logger. +class Logger #:nodoc: def self.define_around_helper(level) module_eval <<-end_eval def around_#{level}(before_message, after_message, &block) # def around_debug(before_message, after_message, &block) diff --git a/activesupport/lib/active_support/core_ext/module/attr_internal.rb b/activesupport/lib/active_support/core_ext/module/attr_internal.rb index b66c0d7500..d052bfed2d 100644 --- a/activesupport/lib/active_support/core_ext/module/attr_internal.rb +++ b/activesupport/lib/active_support/core_ext/module/attr_internal.rb @@ -22,11 +22,11 @@ class Module alias_method :attr_internal, :attr_internal_accessor - private - mattr_accessor :attr_internal_naming_format - self.attr_internal_naming_format = '@_%s' + class << self; attr_accessor :attr_internal_naming_format end + self.attr_internal_naming_format = '@_%s' + private def attr_internal_ivar_name(attr) - attr_internal_naming_format % attr + Module.attr_internal_naming_format % attr end end diff --git a/activesupport/lib/active_support/core_ext/module/introspection.rb b/activesupport/lib/active_support/core_ext/module/introspection.rb index 7708d573fa..23a1063901 100644 --- a/activesupport/lib/active_support/core_ext/module/introspection.rb +++ b/activesupport/lib/active_support/core_ext/module/introspection.rb @@ -1,3 +1,5 @@ +require 'active_support/inflector' + class Module # Returns the name of the module containing this one. # @@ -26,7 +28,7 @@ class Module # p Module.new.parent # => Object # def parent - parent_name ? parent_name.constantize : Object + parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object end # Returns all the parents of this module according to its name, ordered from @@ -47,7 +49,7 @@ class Module if parent_name parts = parent_name.split('::') until parts.empty? - parents << (parts * '::').constantize + parents << ActiveSupport::Inflector.constantize(parts * '::') parts.pop end end diff --git a/activesupport/lib/active_support/core_ext/module/model_naming.rb b/activesupport/lib/active_support/core_ext/module/model_naming.rb index 004b96a3c1..36fde87b23 100644 --- a/activesupport/lib/active_support/core_ext/module/model_naming.rb +++ b/activesupport/lib/active_support/core_ext/module/model_naming.rb @@ -1,13 +1,15 @@ +require 'active_support/inflector' + module ActiveSupport class ModelName < String attr_reader :singular, :plural, :cache_key, :partial_path def initialize(name) super - @singular = underscore.tr('/', '_').freeze - @plural = @singular.pluralize.freeze + @singular = ActiveSupport::Inflector.underscore(self).tr('/', '_').freeze + @plural = ActiveSupport::Inflector.pluralize(@singular).freeze @cache_key = tableize.freeze - @partial_path = "#{@cache_key}/#{demodulize.underscore}".freeze + @partial_path = "#{@cache_key}/#{ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))}".freeze end end end diff --git a/activesupport/lib/active_support/core_ext/module/synchronization.rb b/activesupport/lib/active_support/core_ext/module/synchronization.rb index 069db3fed0..f72d512340 100644 --- a/activesupport/lib/active_support/core_ext/module/synchronization.rb +++ b/activesupport/lib/active_support/core_ext/module/synchronization.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/aliasing' + class Module # Synchronize access around a method, delegating synchronization to a # particular mutex. A mutex (either a Mutex, or any object that responds to diff --git a/activesupport/lib/active_support/core_ext/numeric/time.rb b/activesupport/lib/active_support/core_ext/numeric/time.rb index 2955e8ff1d..d1062805c5 100644 --- a/activesupport/lib/active_support/core_ext/numeric/time.rb +++ b/activesupport/lib/active_support/core_ext/numeric/time.rb @@ -1,3 +1,5 @@ +require 'active_support/duration' + class Numeric # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years. # diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb index 96385d2b87..04e8f06b3d 100644 --- a/activesupport/lib/active_support/core_ext/object.rb +++ b/activesupport/lib/active_support/core_ext/object.rb @@ -1,3 +1,4 @@ +require 'active_support/core_ext/object/acts_like' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/duplicable' require 'active_support/core_ext/object/try' diff --git a/activesupport/lib/active_support/core_ext/range/blockless_step.rb b/activesupport/lib/active_support/core_ext/range/blockless_step.rb index f4792d03b7..db42ef5c47 100644 --- a/activesupport/lib/active_support/core_ext/range/blockless_step.rb +++ b/activesupport/lib/active_support/core_ext/range/blockless_step.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/aliasing' + class Range begin (1..2).step diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 39c2b1b8ed..3f05db62c3 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -1,4 +1,5 @@ require 'date' +require 'active_support/core_ext/time/calculations' class String # 'a'.ord == 'a'[0] for Ruby 1.9 forward compatibility. diff --git a/activesupport/lib/active_support/core_ext/string/multibyte.rb b/activesupport/lib/active_support/core_ext/string/multibyte.rb index 0f0dfb2443..13208c6ee2 100644 --- a/activesupport/lib/active_support/core_ext/string/multibyte.rb +++ b/activesupport/lib/active_support/core_ext/string/multibyte.rb @@ -1,4 +1,5 @@ # encoding: utf-8 +require 'active_support/multibyte' class String unless '1.9'.respond_to?(:force_encoding) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 1804c14618..855b720ef1 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -1,11 +1,13 @@ require 'set' require 'thread' -require 'active_support/inflector' -require 'active_support/core_ext/name_error' -require 'active_support/core_ext/object/blank' require 'active_support/core_ext/module/aliasing' require 'active_support/core_ext/module/attribute_accessors' require 'active_support/core_ext/module/introspection' +require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/load_error' +require 'active_support/core_ext/name_error' +require 'active_support/core_ext/string/starts_ends_with' +require 'active_support/inflector' module ActiveSupport #:nodoc: module Dependencies #:nodoc: diff --git a/activesupport/lib/active_support/deprecation/method_wrappers.rb b/activesupport/lib/active_support/deprecation/method_wrappers.rb index b35d4daf9a..b9eb539aa7 100644 --- a/activesupport/lib/active_support/deprecation/method_wrappers.rb +++ b/activesupport/lib/active_support/deprecation/method_wrappers.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/module/deprecation' +require 'active_support/core_ext/module/aliasing' module ActiveSupport class << Deprecation diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb index 1c268d0d9c..ec54efe08e 100644 --- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb +++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb @@ -1,3 +1,5 @@ +require 'active_support/inflector' + module ActiveSupport module Deprecation class DeprecationProxy #:nodoc: @@ -61,7 +63,7 @@ module ActiveSupport private def target - @new_const.to_s.constantize + ActiveSupport::Inflector.constantize(@new_const.to_s) end def warn(callstack, called, args) diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index f64661c5b1..a33586f77f 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -1,4 +1,5 @@ require 'active_support/basic_object' +require 'active_support/core_ext/array/conversions' module ActiveSupport # Provides accurate date and time measurements using Date#advance and diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 614afa1bd6..ff70d6d76e 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -1,6 +1,7 @@ # encoding: utf-8 require 'iconv' - +require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/string/access' require 'active_support/core_ext/string/multibyte' module ActiveSupport diff --git a/activesupport/lib/active_support/json/encoders/time.rb b/activesupport/lib/active_support/json/encoders/time.rb index f45a0059e8..7d97c38d77 100644 --- a/activesupport/lib/active_support/json/encoders/time.rb +++ b/activesupport/lib/active_support/json/encoders/time.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/time/conversions' + class Time # Returns a JSON string representing the time. If ActiveSupport.use_standard_json_time_format is set to true, the # ISO 8601 format is used. diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb index 2b85fd7be4..edf626802a 100644 --- a/activesupport/lib/active_support/memoizable.rb +++ b/activesupport/lib/active_support/memoizable.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/object/metaclass' + module ActiveSupport module SafelyMemoizable def safely_memoize(*symbols) diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb index 65a96af49a..d8d58f3bce 100644 --- a/activesupport/lib/active_support/multibyte.rb +++ b/activesupport/lib/active_support/multibyte.rb @@ -4,6 +4,8 @@ require 'active_support/multibyte/chars' require 'active_support/multibyte/exceptions' require 'active_support/multibyte/unicode_database' +require 'active_support/core_ext/module/attribute_accessors' + module ActiveSupport #:nodoc: module Multibyte # A list of all available normalization forms. See http://www.unicode.org/reports/tr15/tr15-29.html for more diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb index ca51adba1e..c529b92240 100644 --- a/activesupport/lib/active_support/testing/assertions.rb +++ b/activesupport/lib/active_support/testing/assertions.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/array/wrap' + module ActiveSupport module Testing module Assertions diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index aa448debda..0d4c75d272 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -131,7 +131,7 @@ module ActiveSupport # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json # # => "2005/02/01 15:15:10 +0000" def to_json(options = nil) - if ActiveSupport.use_standard_json_time_format + if !ActiveSupport.respond_to?(:use_standard_json_time_format) || ActiveSupport.use_standard_json_time_format xmlschema.inspect else %("#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb index ccd1349491..f22fbcc0e1 100644 --- a/activesupport/lib/active_support/xml_mini.rb +++ b/activesupport/lib/active_support/xml_mini.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/delegation' + module ActiveSupport # = XmlMini # diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb index 771109514c..5033210aae 100644 --- a/activesupport/lib/active_support/xml_mini/rexml.rb +++ b/activesupport/lib/active_support/xml_mini/rexml.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/object/blank' + # = XmlMini ReXML implementation module ActiveSupport module XmlMini_REXML #:nodoc: diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb index d48c7fcc54..7a0ec2e910 100644 --- a/activesupport/test/buffered_logger_test.rb +++ b/activesupport/test/buffered_logger_test.rb @@ -4,11 +4,13 @@ require 'fileutils' require 'active_support/buffered_logger' class BufferedLoggerTest < Test::Unit::TestCase + Logger = ActiveSupport::BufferedLogger + def setup @message = "A debug message" @integer_message = 12345 @output = StringIO.new - @logger = ActiveSupport::BufferedLogger.new(@output) + @logger = Logger.new(@output) end def test_should_log_debugging_message_when_debugging @@ -76,9 +78,9 @@ class BufferedLoggerTest < Test::Unit::TestCase define_method "test_disabling_auto_flush_with_#{disable.inspect}_should_flush_at_max_buffer_size_as_failsafe" do @logger.auto_flushing = disable - assert_equal ActiveSupport::BufferedLogger::MAX_BUFFER_SIZE, @logger.auto_flushing + assert_equal Logger::MAX_BUFFER_SIZE, @logger.auto_flushing - (ActiveSupport::BufferedLogger::MAX_BUFFER_SIZE - 1).times do + (Logger::MAX_BUFFER_SIZE - 1).times do @logger.info 'wait for it..' assert @output.string.empty?, @output.string end @@ -89,8 +91,8 @@ class BufferedLoggerTest < Test::Unit::TestCase end def test_should_know_if_its_loglevel_is_below_a_given_level - ActiveSupport::BufferedLogger::Severity.constants.each do |level| - @logger.level = ActiveSupport::BufferedLogger::Severity.const_get(level) - 1 + Logger::Severity.constants.each do |level| + @logger.level = Logger::Severity.const_get(level) - 1 assert @logger.send("#{level.downcase}?"), "didn't know if it was #{level.downcase}? or below" end end @@ -111,7 +113,7 @@ class BufferedLoggerTest < Test::Unit::TestCase tmp_directory = File.join(File.dirname(__FILE__), "tmp") log_file = File.join(tmp_directory, "development.log") assert !File.exist?(tmp_directory) - @logger = ActiveSupport::BufferedLogger.new(log_file) + @logger = Logger.new(log_file) assert File.exist?(tmp_directory) ensure FileUtils.rm_rf(tmp_directory) diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index 112cb998b1..24d33896ce 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -1,6 +1,9 @@ require 'abstract_unit' require 'active_support/core_ext/array' require 'active_support/core_ext/big_decimal' +require 'active_support/core_ext/object/conversions' + +require 'active_support/core_ext' # FIXME: pulling in all to_xml extensions class ArrayExtAccessTests < Test::Unit::TestCase def test_from diff --git a/activesupport/test/core_ext/blank_test.rb b/activesupport/test/core_ext/blank_test.rb index 00fea74639..1dbbf3ff30 100644 --- a/activesupport/test/core_ext/blank_test.rb +++ b/activesupport/test/core_ext/blank_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/object/blank' class EmptyTrue def empty?() true; end diff --git a/activesupport/test/core_ext/class/attribute_accessor_test.rb b/activesupport/test/core_ext/class/attribute_accessor_test.rb index 85d0dd89e2..2214ba9894 100644 --- a/activesupport/test/core_ext/class/attribute_accessor_test.rb +++ b/activesupport/test/core_ext/class/attribute_accessor_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/class/attribute_accessors' class ClassAttributeAccessorTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb b/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb index 7f859772e7..eeda468d9c 100644 --- a/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb +++ b/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/class/inheritable_attributes' class ClassInheritableAttributesTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb index 45eb52c720..a7b179b2be 100644 --- a/activesupport/test/core_ext/date_time_ext_test.rb +++ b/activesupport/test/core_ext/date_time_ext_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/date_time' class DateTimeExtCalculationsTest < Test::Unit::TestCase def test_to_s diff --git a/activesupport/test/core_ext/duplicable_test.rb b/activesupport/test/core_ext/duplicable_test.rb index 8b6127f31e..6e1f876959 100644 --- a/activesupport/test/core_ext/duplicable_test.rb +++ b/activesupport/test/core_ext/duplicable_test.rb @@ -1,4 +1,6 @@ require 'abstract_unit' +require 'bigdecimal' +require 'active_support/core_ext/object/duplicable' class DuplicableTest < Test::Unit::TestCase NO = [nil, false, true, :symbol, 1, 2.3, BigDecimal.new('4.56'), Class.new] diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index d4a4627e3e..ea6979bc6b 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core/time' class DurationTest < ActiveSupport::TestCase def test_inspect diff --git a/activesupport/test/core_ext/exception_test.rb b/activesupport/test/core_ext/exception_test.rb index dabd8c7c06..e63842c0bd 100644 --- a/activesupport/test/core_ext/exception_test.rb +++ b/activesupport/test/core_ext/exception_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/exception' class ExceptionExtTests < Test::Unit::TestCase diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index bbb1c631f9..d65a5323bf 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -1,5 +1,7 @@ require 'abstract_unit' require 'active_support/core_ext/hash' +require 'bigdecimal' +require 'active_support/core_ext/string/access' class HashExtTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb b/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb index 7c59348af9..7c0d0bb242 100644 --- a/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb +++ b/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/module/attr_accessor_with_default' class AttrAccessorWithDefaultTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/core_ext/module/attr_internal_test.rb b/activesupport/test/core_ext/module/attr_internal_test.rb index 52833019e7..93578c9610 100644 --- a/activesupport/test/core_ext/module/attr_internal_test.rb +++ b/activesupport/test/core_ext/module/attr_internal_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/module/attr_internal' class AttrInternalTest < Test::Unit::TestCase def setup @@ -37,8 +38,8 @@ class AttrInternalTest < Test::Unit::TestCase end def test_naming_format - assert_equal '@_%s', @target.attr_internal_naming_format - assert_nothing_raised { @target.attr_internal_naming_format = '@abc%sdef' } + assert_equal '@_%s', Module.attr_internal_naming_format + assert_nothing_raised { Module.attr_internal_naming_format = '@abc%sdef' } @target.attr_internal :foo assert !@instance.instance_variable_defined?('@_foo') @@ -47,6 +48,6 @@ class AttrInternalTest < Test::Unit::TestCase assert !@instance.instance_variable_defined?('@_foo') assert @instance.instance_variable_defined?('@abcfoodef') ensure - @target.attr_internal_naming_format = '@_%s' + Module.attr_internal_naming_format = '@_%s' end end diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb index 96975085cf..bd9461e62c 100644 --- a/activesupport/test/core_ext/module/attribute_accessor_test.rb +++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/module/attribute_accessors' class ModuleAttributeAccessorTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/core_ext/module/model_naming_test.rb b/activesupport/test/core_ext/module/model_naming_test.rb index d08349dd97..da3b6c4932 100644 --- a/activesupport/test/core_ext/module/model_naming_test.rb +++ b/activesupport/test/core_ext/module/model_naming_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/module/model_naming' class ModelNamingTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/core_ext/name_error_test.rb b/activesupport/test/core_ext/name_error_test.rb index bae004809f..10913e2ade 100644 --- a/activesupport/test/core_ext/name_error_test.rb +++ b/activesupport/test/core_ext/name_error_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/name_error' class NameErrorTest < Test::Unit::TestCase def test_name_error_should_set_missing_name diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb index 9cca4d3aaf..74b086fa9c 100644 --- a/activesupport/test/core_ext/numeric_ext_test.rb +++ b/activesupport/test/core_ext/numeric_ext_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' - -require 'active_support/core_ext/numeric/bytes' +require 'active_support/core_ext/numeric' +require 'active_support/core_ext/integer' +require 'active_support/core/time' class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase def setup 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 c919698c0f..8869b053e6 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -1,5 +1,7 @@ require 'abstract_unit' require 'active_support/core_ext/object' +require 'active_support/core_ext/class/removal' +require 'active_support/core/time' class ClassA; end class ClassB < ClassA; end diff --git a/activesupport/test/core_ext/proc_test.rb b/activesupport/test/core_ext/proc_test.rb index 29f85371de..dc7b2c957d 100644 --- a/activesupport/test/core_ext/proc_test.rb +++ b/activesupport/test/core_ext/proc_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/proc' class ProcTests < Test::Unit::TestCase def test_bind_returns_method_with_changed_self diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb index 76e05e9954..2565c56b8a 100644 --- a/activesupport/test/core_ext/range_ext_test.rb +++ b/activesupport/test/core_ext/range_ext_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'active_support/core_ext/range' +require 'active_support/core_ext/date/conversions' class RangeTest < Test::Unit::TestCase def test_to_s_from_dates diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index a357ba5852..237a843f9a 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -4,6 +4,7 @@ require 'abstract_unit' require 'inflector_test_cases' require 'active_support/core_ext/string' +require 'active_support/core_ext/time' class StringInflectionsTest < Test::Unit::TestCase include InflectorTestCases diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 8ee4904036..3bf7b789ce 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core/time' class TimeExtCalculationsTest < Test::Unit::TestCase def test_seconds_since_midnight diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 3dec4c95f4..612a50c225 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'active_support/time_with_zone' +require 'active_support/json' class TimeWithZoneTest < Test::Unit::TestCase diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 01c1d67f4c..99c53924c2 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -1,6 +1,8 @@ require 'abstract_unit' require 'pp' require 'active_support/dependencies' +require 'active_support/core_ext/module/loading' +require 'active_support/core_ext/kernel/reporting' module ModuleWithMissing mattr_accessor :missing_count diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb index 7535f4ad7a..2a08abfb3e 100644 --- a/activesupport/test/i18n_test.rb +++ b/activesupport/test/i18n_test.rb @@ -1,4 +1,6 @@ require 'abstract_unit' +require 'active_support/core/time' +require 'active_support/core_ext/array/conversions' class I18nTest < Test::Unit::TestCase def setup diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index 6b9fbd3156..8c4d831a39 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -1,4 +1,6 @@ require 'abstract_unit' +require 'active_support/inflector' + require 'inflector_test_cases' module Ace diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb index d250b10822..40d3d612e7 100644 --- a/activesupport/test/test_test.rb +++ b/activesupport/test/test_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/kernel/reporting' class AssertDifferenceTest < ActiveSupport::TestCase def setup diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb index 7e8047566e..87d6ccc30d 100644 --- a/activesupport/test/time_zone_test.rb +++ b/activesupport/test/time_zone_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core/time' class TimeZoneTest < Test::Unit::TestCase def test_utc_to_local diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb index e5174a0b57..886a9d1aba 100644 --- a/activesupport/test/xml_mini/nokogiri_engine_test.rb +++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'active_support/xml_mini' +require 'active_support/core_ext/hash/conversions' begin gem 'nokogiri', '>= 1.1.1' -- cgit v1.2.3 From 3c4c6bd0df598f865f49a983b4c65c415af4bcfc Mon Sep 17 00:00:00 2001 From: rick Date: Thu, 23 Apr 2009 00:08:40 -0700 Subject: * Add pluggable JSON backends with support for the JSON gem. [rick] Example: ActiveSupport::JSON.backend = "JSONGem" All internal Rails JSON encoding is now handled by ActiveSupport::JSON.encode(). Use of #to_json is not recommended, as it may clash with other libraries that overwrite it. However, you can recover Rails specific functionality if you really want to use #to_json. gem 'json' ActiveSupport::JSON.backend = "JSONGem" class ActiveRecord::Base alias to_json rails_to_json end --- activesupport/CHANGELOG | 15 ++++ activesupport/lib/active_support/json.rb | 34 ++++++++- .../lib/active_support/json/backends/jsongem.rb | 36 ++++++++++ .../lib/active_support/json/backends/yaml.rb | 83 ++++++++++++++++++++++ activesupport/lib/active_support/json/decoding.rb | 82 --------------------- .../lib/active_support/json/encoders/date.rb | 4 +- .../lib/active_support/json/encoders/date_time.rb | 4 +- .../lib/active_support/json/encoders/enumerable.rb | 6 +- .../active_support/json/encoders/false_class.rb | 4 +- .../lib/active_support/json/encoders/hash.rb | 8 ++- .../lib/active_support/json/encoders/nil_class.rb | 4 +- .../lib/active_support/json/encoders/numeric.rb | 4 +- .../lib/active_support/json/encoders/object.rb | 4 +- .../lib/active_support/json/encoders/regexp.rb | 4 +- .../lib/active_support/json/encoders/string.rb | 4 +- .../lib/active_support/json/encoders/symbol.rb | 4 +- .../lib/active_support/json/encoders/time.rb | 4 +- .../lib/active_support/json/encoders/true_class.rb | 4 +- activesupport/lib/active_support/json/encoding.rb | 2 +- activesupport/lib/active_support/json/variable.rb | 2 +- activesupport/lib/active_support/time_with_zone.rb | 4 +- activesupport/test/core_ext/time_with_zone_test.rb | 4 +- activesupport/test/json/decoding_test.rb | 76 +++++++++++++------- activesupport/test/json/encoding_test.rb | 38 +++++----- 24 files changed, 285 insertions(+), 149 deletions(-) create mode 100644 activesupport/lib/active_support/json/backends/jsongem.rb create mode 100644 activesupport/lib/active_support/json/backends/yaml.rb delete mode 100644 activesupport/lib/active_support/json/decoding.rb (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index cd7b47d780..ca5ab13a46 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,20 @@ *Edge* +* Add ActiveSupport.parse_json_times to disable time parsing in JSON backends that don't support it or don't need it. [rick] + +* Add pluggable JSON backends with support for the JSON gem. [rick] + Example: ActiveSupport::JSON.backend = "JSONGem" + + All internal Rails JSON encoding is now handled by ActiveSupport::JSON.encode(). Use of #to_json is not recommended, as it may clash with other libraries that overwrite it. However, you can recover Rails specific functionality + if you really want to use #to_json. + + gem 'json' + ActiveSupport::JSON.backend = "JSONGem" + + class ActiveRecord::Base + alias to_json rails_to_json + end + * require 'active_support' no longer orders the whole menu of core extensions. Ask for just what you need: e.g. require 'active_support/core/time' to use timezones, durations, and stdlib date/time extensions. [Jeremy Kemper] * Removed rarely-used DRb cache store. [Jeremy Kemper] diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index 91f19f8a70..fc433de582 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -1,8 +1,37 @@ +require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/module/attribute_accessors' module ActiveSupport # If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format. mattr_accessor :use_standard_json_time_format + # Look for and parse json strings that look like ISO 8601 times. + mattr_accessor :parse_json_times + + 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})?))$/ + + class << self + attr_reader :backend + delegate :decode, :to => :backend + + def backend=(name) + if name.is_a?(Module) + @backend = name + else + require "active_support/json/backends/#{name.to_s.downcase}.rb" + @backend = ActiveSupport::JSON::Backends::const_get(name) + end + end + + def with_backend(name) + old_backend, self.backend = backend, name + yield + ensure + self.backend = old_backend + end + end + end class << self def escape_html_entities_in_json @@ -19,7 +48,8 @@ module ActiveSupport @escape_html_entities_in_json = value end end + + JSON.backend = 'Yaml' end -require 'active_support/json/encoding' -require 'active_support/json/decoding' +require 'active_support/json/encoding' \ No newline at end of file diff --git a/activesupport/lib/active_support/json/backends/jsongem.rb b/activesupport/lib/active_support/json/backends/jsongem.rb new file mode 100644 index 0000000000..de847e30a3 --- /dev/null +++ b/activesupport/lib/active_support/json/backends/jsongem.rb @@ -0,0 +1,36 @@ +module ActiveSupport + module JSON + ParseError = ::JSON::ParserError + + module Backends + module JSONGem + extend self + + # Converts a JSON string into a Ruby object. + def decode(json) + data = ::JSON.parse(json) + if ActiveSupport.parse_json_times + convert_dates_from(data) + else + data + end + end + + private + def convert_dates_from(data) + case data + when DATE_REGEX + DateTime.parse(data) + when Array + data.map! { |d| convert_dates_from(d) } + when Hash + data.each do |key, value| + data[key] = convert_dates_from(value) + end + else data + end + end + end + end + end +end \ No newline at end of file diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb new file mode 100644 index 0000000000..c7db508c23 --- /dev/null +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -0,0 +1,83 @@ +require 'active_support/core_ext/string/starts_ends_with' + +module ActiveSupport + module JSON + class ParseError < StandardError + end + + module Backends + module Yaml + extend self + + # Converts a JSON string into a Ruby object. + def decode(json) + YAML.load(convert_json_to_yaml(json)) + rescue ArgumentError => e + raise ParseError, "Invalid JSON string" + end + + protected + # Ensure that ":" and "," are always followed by a space + def convert_json_to_yaml(json) #:nodoc: + require 'strscan' unless defined? ::StringScanner + scanner, quoting, marks, pos, times = ::StringScanner.new(json), false, [], nil, [] + while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/) + case char = scanner[1] + when '"', "'" + if !quoting + quoting = char + pos = scanner.pos + elsif quoting == char + if json[pos..scanner.pos-2] =~ DATE_REGEX + # found a date, track the exact positions of the quotes so we can remove them later. + # oh, and increment them for each current mark, each one is an extra padded space that bumps + # the position in the final YAML output + total_marks = marks.size + times << pos+total_marks << scanner.pos+total_marks + end + quoting = false + end + when ":","," + marks << scanner.pos - 1 unless quoting + end + end + + if marks.empty? + json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do + ustr = $1 + if ustr.start_with?('u') + [ustr[1..-1].to_i(16)].pack("U") + elsif ustr == '\\' + '\\\\' + else + ustr + end + end + else + left_pos = [-1].push(*marks) + right_pos = marks << scanner.pos + scanner.rest_size + output = [] + left_pos.each_with_index do |left, i| + scanner.pos = left.succ + output << scanner.peek(right_pos[i] - scanner.pos + 1).gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do + ustr = $1 + if ustr.start_with?('u') + [ustr[1..-1].to_i(16)].pack("U") + elsif ustr == '\\' + '\\\\' + else + ustr + end + end + end + output = output * " " + + times.each { |i| output[i-1] = ' ' } + output.gsub!(/\\\//, '/') + output + end + end + end + end + end +end diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb deleted file mode 100644 index 70e9f40fc7..0000000000 --- a/activesupport/lib/active_support/json/decoding.rb +++ /dev/null @@ -1,82 +0,0 @@ -require 'active_support/core_ext/string/starts_ends_with' - -module ActiveSupport - module JSON - class ParseError < StandardError - end - - class << self - # Converts a JSON string into a Ruby object. - def decode(json) - YAML.load(convert_json_to_yaml(json)) - rescue ArgumentError => e - raise ParseError, "Invalid JSON string" - end - - protected - # 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})?)?)$/ - - # Ensure that ":" and "," are always followed by a space - def convert_json_to_yaml(json) #:nodoc: - require 'strscan' unless defined? ::StringScanner - scanner, quoting, marks, pos, times = ::StringScanner.new(json), false, [], nil, [] - while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/) - case char = scanner[1] - when '"', "'" - if !quoting - quoting = char - pos = scanner.pos - elsif quoting == char - if json[pos..scanner.pos-2] =~ DATE_REGEX - # found a date, track the exact positions of the quotes so we can remove them later. - # oh, and increment them for each current mark, each one is an extra padded space that bumps - # the position in the final YAML output - total_marks = marks.size - times << pos+total_marks << scanner.pos+total_marks - end - quoting = false - end - when ":","," - marks << scanner.pos - 1 unless quoting - end - end - - if marks.empty? - json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do - ustr = $1 - if ustr.start_with?('u') - [ustr[1..-1].to_i(16)].pack("U") - elsif ustr == '\\' - '\\\\' - else - ustr - end - end - else - left_pos = [-1].push(*marks) - right_pos = marks << scanner.pos + scanner.rest_size - output = [] - left_pos.each_with_index do |left, i| - scanner.pos = left.succ - output << scanner.peek(right_pos[i] - scanner.pos + 1).gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do - ustr = $1 - if ustr.start_with?('u') - [ustr[1..-1].to_i(16)].pack("U") - elsif ustr == '\\' - '\\\\' - else - ustr - end - end - end - output = output * " " - - times.each { |i| output[i-1] = ' ' } - output.gsub!(/\\\//, '/') - output - end - end - end - end -end diff --git a/activesupport/lib/active_support/json/encoders/date.rb b/activesupport/lib/active_support/json/encoders/date.rb index cc84de1388..79c3957362 100644 --- a/activesupport/lib/active_support/json/encoders/date.rb +++ b/activesupport/lib/active_support/json/encoders/date.rb @@ -11,11 +11,13 @@ class Date # # With ActiveSupport.use_standard_json_time_format = false # Date.new(2005,2,1).to_json # # => "2005/02/01" - def to_json(options = nil) + def rails_to_json(options = nil) if ActiveSupport.use_standard_json_time_format %("#{strftime("%Y-%m-%d")}") else %("#{strftime("%Y/%m/%d")}") end end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/date_time.rb b/activesupport/lib/active_support/json/encoders/date_time.rb index 6c85824105..cdfc39b9f3 100644 --- a/activesupport/lib/active_support/json/encoders/date_time.rb +++ b/activesupport/lib/active_support/json/encoders/date_time.rb @@ -11,11 +11,13 @@ class DateTime # # With ActiveSupport.use_standard_json_time_format = false # DateTime.civil(2005,2,1,15,15,10).to_json # # => "2005/02/01 15:15:10 +0000" - def to_json(options = nil) + def rails_to_json(options = nil) if ActiveSupport.use_standard_json_time_format xmlschema.inspect else strftime('"%Y/%m/%d %H:%M:%S %z"') end end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/enumerable.rb b/activesupport/lib/active_support/json/encoders/enumerable.rb index 881b1d62c1..e1c3ec249d 100644 --- a/activesupport/lib/active_support/json/encoders/enumerable.rb +++ b/activesupport/lib/active_support/json/encoders/enumerable.rb @@ -6,7 +6,9 @@ module Enumerable # # => users.to_json(:only => :name) # # will pass the :only => :name option to each user. - def to_json(options = {}) #:nodoc: - "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ', '}]" + def rails_to_json(options = {}) #:nodoc: + "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ','}]" end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/false_class.rb b/activesupport/lib/active_support/json/encoders/false_class.rb index bf0844334b..a7657cca37 100644 --- a/activesupport/lib/active_support/json/encoders/false_class.rb +++ b/activesupport/lib/active_support/json/encoders/false_class.rb @@ -1,5 +1,7 @@ class FalseClass - def to_json(options = nil) #:nodoc: + def rails_to_json(options = nil) #:nodoc: 'false' end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb index d87b880743..19b97d7b8c 100644 --- a/activesupport/lib/active_support/json/encoders/hash.rb +++ b/activesupport/lib/active_support/json/encoders/hash.rb @@ -30,7 +30,7 @@ class Hash # would pass the :include => :posts option to users, # allowing the posts association in the User model to be converted to JSON # as well. - def to_json(options = {}) #:nodoc: + def rails_to_json(options = {}) #:nodoc: hash_keys = self.keys if except = options[:except] @@ -41,8 +41,10 @@ class Hash result = '{' result << hash_keys.map do |key| - "#{ActiveSupport::JSON.encode(key.to_s)}: #{ActiveSupport::JSON.encode(self[key], options)}" - end * ', ' + "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(self[key], options)}" + end * ',' result << '}' end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/nil_class.rb b/activesupport/lib/active_support/json/encoders/nil_class.rb index 4763471ac4..b31e1dd249 100644 --- a/activesupport/lib/active_support/json/encoders/nil_class.rb +++ b/activesupport/lib/active_support/json/encoders/nil_class.rb @@ -1,5 +1,7 @@ class NilClass - def to_json(options = nil) #:nodoc: + def rails_to_json(options = nil) #:nodoc: 'null' end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/numeric.rb b/activesupport/lib/active_support/json/encoders/numeric.rb index 38713fb369..491b330c39 100644 --- a/activesupport/lib/active_support/json/encoders/numeric.rb +++ b/activesupport/lib/active_support/json/encoders/numeric.rb @@ -1,5 +1,7 @@ class Numeric - def to_json(options = nil) #:nodoc: + def rails_to_json(options = nil) #:nodoc: to_s end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/object.rb b/activesupport/lib/active_support/json/encoders/object.rb index 0475967aee..d68f50562e 100644 --- a/activesupport/lib/active_support/json/encoders/object.rb +++ b/activesupport/lib/active_support/json/encoders/object.rb @@ -2,7 +2,9 @@ require 'active_support/core_ext/object/instance_variables' class Object # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. - def to_json(options = {}) + def rails_to_json(options = {}) ActiveSupport::JSON.encode(instance_values, options) end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/regexp.rb b/activesupport/lib/active_support/json/encoders/regexp.rb index b6116b70b5..63ccd7c490 100644 --- a/activesupport/lib/active_support/json/encoders/regexp.rb +++ b/activesupport/lib/active_support/json/encoders/regexp.rb @@ -1,5 +1,7 @@ class Regexp - def to_json(options = nil) #:nodoc: + def rails_to_json(options = nil) #:nodoc: inspect end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/string.rb b/activesupport/lib/active_support/json/encoders/string.rb index 5ef797955a..27bef3b9cc 100644 --- a/activesupport/lib/active_support/json/encoders/string.rb +++ b/activesupport/lib/active_support/json/encoders/string.rb @@ -22,7 +22,7 @@ end ActiveSupport.escape_html_entities_in_json = true class String - def to_json(options = nil) #:nodoc: + def rails_to_json(options = nil) #:nodoc: json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s| ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s] } @@ -33,4 +33,6 @@ class String s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&') } + '"' end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/symbol.rb b/activesupport/lib/active_support/json/encoders/symbol.rb index 485112f97c..6487bf8cb7 100644 --- a/activesupport/lib/active_support/json/encoders/symbol.rb +++ b/activesupport/lib/active_support/json/encoders/symbol.rb @@ -1,5 +1,7 @@ class Symbol - def to_json(options = {}) #:nodoc: + def rails_to_json(options = {}) #:nodoc: ActiveSupport::JSON.encode(to_s, options) end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/time.rb b/activesupport/lib/active_support/json/encoders/time.rb index 7d97c38d77..2699672949 100644 --- a/activesupport/lib/active_support/json/encoders/time.rb +++ b/activesupport/lib/active_support/json/encoders/time.rb @@ -13,11 +13,13 @@ class Time # # With ActiveSupport.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).to_json # # => "2005/02/01 15:15:10 +0000" - def to_json(options = nil) + def rails_to_json(options = nil) if ActiveSupport.use_standard_json_time_format xmlschema.inspect else %("#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") end end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/true_class.rb b/activesupport/lib/active_support/json/encoders/true_class.rb index 037d812b3f..ac7c7d1e87 100644 --- a/activesupport/lib/active_support/json/encoders/true_class.rb +++ b/activesupport/lib/active_support/json/encoders/true_class.rb @@ -1,5 +1,7 @@ class TrueClass - def to_json(options = nil) #:nodoc: + def rails_to_json(options = nil) #:nodoc: 'true' end + + alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index aaaa3cdfd2..42a217cedc 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -8,7 +8,7 @@ module ActiveSupport seen = (options[:seen] ||= []) raise CircularReferenceError, 'object references itself' if seen.include?(value) seen << value - value.send(:to_json, options) + value.send(:rails_to_json, options) ensure seen.pop end diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb index 7fd23b0a9e..3ee152ee3c 100644 --- a/activesupport/lib/active_support/json/variable.rb +++ b/activesupport/lib/active_support/json/variable.rb @@ -2,7 +2,7 @@ module ActiveSupport module JSON # A string that returns itself as its JSON-encoded form. class Variable < String - def to_json(options=nil) + def rails_to_json(options=nil) self end end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 0d4c75d272..1949ce0ad3 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -130,7 +130,7 @@ module ActiveSupport # # With ActiveSupport.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json # # => "2005/02/01 15:15:10 +0000" - def to_json(options = nil) + def rails_to_json(options = nil) if !ActiveSupport.respond_to?(:use_standard_json_time_format) || ActiveSupport.use_standard_json_time_format xmlschema.inspect else @@ -138,6 +138,8 @@ module ActiveSupport end end + alias to_json rails_to_json + def to_yaml(options = {}) if options.kind_of?(YAML::Emitter) utc.to_yaml(options) diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 612a50c225..0380c28c17 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -57,12 +57,12 @@ class TimeWithZoneTest < Test::Unit::TestCase end def test_to_json - assert_equal "\"1999/12/31 19:00:00 -0500\"", @twz.to_json + assert_equal "\"1999/12/31 19:00:00 -0500\"", ActiveSupport::JSON.encode(@twz) end def test_to_json_with_use_standard_json_time_format_config_set_to_true old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, true - assert_equal "\"1999-12-31T19:00:00-05:00\"", @twz.to_json + assert_equal "\"1999-12-31T19:00:00-05:00\"", ActiveSupport::JSON.encode(@twz) ensure ActiveSupport.use_standard_json_time_format = old end diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 9b4b207c88..7e1bfcca84 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -1,49 +1,75 @@ # encoding: UTF-8 require 'abstract_unit' require 'active_support/json' +require 'active_support/core_ext/kernel/reporting' class TestJSONDecoding < ActiveSupport::TestCase TESTS = { %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, - %q({returnTo:{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, %q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}}, %q({"returnTo":{"\/categories":1}}) => {"returnTo" => {"/categories" => 1}}, %({"returnTo":[1,"a"]}) => {"returnTo" => [1, "a"]}, %({"returnTo":[1,"\\"a\\",", "b"]}) => {"returnTo" => [1, "\"a\",", "b"]}, - %({a: "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"}, - %({a: "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"}, + %({"a": "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"}, + %({"a": "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"}, # multibyte %({"matzue": "松江", "asakusa": "浅草"}) => {"matzue" => "松江", "asakusa" => "浅草"}, - %({a: "2007-01-01"}) => {'a' => Date.new(2007, 1, 1)}, - %({a: "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)}, + %({"a": "2007-01-01"}) => {'a' => Date.new(2007, 1, 1)}, + %({"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"}, + %({"a": "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"}, # 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"}, + %({"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"}, %([]) => [], %({}) => {}, - %(1) => 1, - %("") => "", - %("\\"") => "\"", - %(null) => nil, - %(true) => true, - %(false) => false, - %q("http:\/\/test.host\/posts\/1") => "http://test.host/posts/1", - %q("\u003cunicode\u0020escape\u003e") => "", - %q("\\\\u0020skip double backslashes") => "\\u0020skip double backslashes", - %q({a: "\u003cbr /\u003e"}) => {'a' => "
"}, - %q({b:["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => {'b' => ["","",""]} + %({"a":1}) => {"a" => 1}, + %({"a": ""}) => {"a" => ""}, + %({"a":"\\""}) => {"a" => "\""}, + %({"a": null}) => {"a" => nil}, + %({"a": true}) => {"a" => true}, + %({"a": false}) => {"a" => false}, + %q({"a": "http:\/\/test.host\/posts\/1"}) => {"a" => "http://test.host/posts/1"}, + %q({"a": "\u003cunicode\u0020escape\u003e"}) => {"a" => ""}, + %q({"a": "\\\\u0020skip double backslashes"}) => {"a" => "\\u0020skip double backslashes"}, + %q({"a": "\u003cbr /\u003e"}) => {'a' => "
"}, + %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => {'b' => ["","",""]} } - - TESTS.each do |json, expected| - test "json decodes #{json}" do - assert_nothing_raised do - assert_equal expected, ActiveSupport::JSON.decode(json) + + backends = %w(Yaml) + begin + gem 'json', '>= 1.1' + require 'json' + backends << "JSONGem" + rescue Gem::LoadError + # Skip JSON gem tests + end + + backends.each do |backend| + TESTS.each do |json, expected| + test "json decodes #{json} with the #{backend} backend" do + 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 + end + end + end + end + end + + if backends.include?("JSONGem") + test "json decodes time json with time parsing disabled" do + ActiveSupport.parse_json_times = false + expected = {"a" => "2007-01-01 01:12:34 Z"} + ActiveSupport::JSON.with_backend "JSONGem" do + assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"})) end end end - + def test_failed_json_decoding assert_raise(ActiveSupport::JSON::ParseError) { ActiveSupport::JSON.decode(%({: 1})) } end diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 9e6b4fa501..db24b3d96a 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -19,14 +19,14 @@ class TestJSONEncoding < Test::Unit::TestCase [ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ], [ 'http://test.host/posts/1', %("http://test.host/posts/1")]] - ArrayTests = [[ ['a', 'b', 'c'], %([\"a\", \"b\", \"c\"]) ], - [ [1, 'a', :b, nil, false], %([1, \"a\", \"b\", null, false]) ]] + ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ], + [ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]] SymbolTests = [[ :a, %("a") ], [ :this, %("this") ], [ :"a b", %("a b") ]] - ObjectTests = [[ Foo.new(1, 2), %({\"a\": 1, \"b\": 2}) ]] + ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]] VariableTests = [[ ActiveSupport::JSON::Variable.new('foo'), 'foo'], [ ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")']] @@ -47,7 +47,7 @@ class TestJSONEncoding < Test::Unit::TestCase ActiveSupport.escape_html_entities_in_json = class_tests !~ /^Standard/ ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/ self.class.const_get(class_tests).each do |pair| - assert_equal pair.last, pair.first.to_json + assert_equal pair.last, ActiveSupport::JSON.encode(pair.first) end ensure ActiveSupport.escape_html_entities_in_json = false @@ -57,45 +57,45 @@ class TestJSONEncoding < Test::Unit::TestCase end def test_hash_encoding - assert_equal %({\"a\": \"b\"}), { :a => :b }.to_json - assert_equal %({\"a\": 1}), { 'a' => 1 }.to_json - assert_equal %({\"a\": [1, 2]}), { 'a' => [1,2] }.to_json - assert_equal %({"1": 2}), { 1 => 2 }.to_json + assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b) + assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1) + assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode('a' => [1,2]) + assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2) - sorted_json = '{' + {:a => :b, :c => :d}.to_json[1..-2].split(', ').sort.join(', ') + '}' - assert_equal %({\"a\": \"b\", \"c\": \"d\"}), sorted_json + sorted_json = '{' + ActiveSupport::JSON.encode(:a => :b, :c => :d)[1..-2].split(',').sort.join(',') + '}' + assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json end def test_utf8_string_encoded_properly_when_kcode_is_utf8 with_kcode 'UTF8' do - assert_equal '"\\u20ac2.99"', '€2.99'.to_json - assert_equal '"\\u270e\\u263a"', '✎☺'.to_json + assert_equal '"\\u20ac2.99"', ActiveSupport::JSON.encode('€2.99') + assert_equal '"\\u270e\\u263a"', ActiveSupport::JSON.encode('✎☺') end end def test_exception_raised_when_encoding_circular_reference a = [1] a << a - assert_raise(ActiveSupport::JSON::CircularReferenceError) { a.to_json } + assert_raise(ActiveSupport::JSON::CircularReferenceError) { ActiveSupport::JSON.encode(a) } end def test_hash_key_identifiers_are_always_quoted values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"} - assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(values.to_json) + assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values)) end def test_hash_should_allow_key_filtering_with_only - assert_equal %({"a": 1}), { 'a' => 1, :b => 2, :c => 3 }.to_json(:only => 'a') + assert_equal %({"a":1}), ActiveSupport::JSON.encode({'a' => 1, :b => 2, :c => 3}, :only => 'a') end def test_hash_should_allow_key_filtering_with_except - assert_equal %({"b": 2}), { 'foo' => 'bar', :b => 2, :c => 3 }.to_json(:except => ['foo', :c]) + assert_equal %({"b":2}), ActiveSupport::JSON.encode({'foo' => 'bar', :b => 2, :c => 3}, :except => ['foo', :c]) end def test_time_to_json_includes_local_offset ActiveSupport.use_standard_json_time_format = true with_env_tz 'US/Eastern' do - assert_equal %("2005-02-01T15:15:10-05:00"), Time.local(2005,2,1,15,15,10).to_json + assert_equal %("2005-02-01T15:15:10-05:00"), ActiveSupport::JSON.encode(Time.local(2005,2,1,15,15,10)) end ensure ActiveSupport.use_standard_json_time_format = false @@ -109,7 +109,7 @@ class TestJSONEncoding < Test::Unit::TestCase :latitude => 123.234 } } - result = hash.to_json + result = ActiveSupport::JSON.encode(hash) end end @@ -134,6 +134,6 @@ class JsonOptionsTests < Test::Unit::TestCase ActiveSupport::JSON.expects(:encode).with(2, json_options) ActiveSupport::JSON.expects(:encode).with('foo', json_options) - [1, 2, 'foo'].to_json(json_options) + [1, 2, 'foo'].rails_to_json(json_options) end end -- cgit v1.2.3 From da3a80dd4fadde9b3bd671c72b5bee737fb70e39 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 15:04:02 -0700 Subject: Track object ids so the objects needn't respond to == --- activesupport/lib/active_support/json/encoding.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index 42a217cedc..e8e9308495 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -6,8 +6,8 @@ module ActiveSupport # Converts a Ruby object into a JSON string. def self.encode(value, options = {}) seen = (options[:seen] ||= []) - raise CircularReferenceError, 'object references itself' if seen.include?(value) - seen << value + raise CircularReferenceError, 'object references itself' if seen.include?(value.object_id) + seen << value.object_id value.send(:rails_to_json, options) ensure seen.pop -- cgit v1.2.3 From 8d64085138b1a2ff36b94267d0236868b287610e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 15:18:33 -0700 Subject: Only Object to_json alias is needed. Prefer nil options. --- activesupport/lib/active_support/json/encoders/date.rb | 2 -- .../lib/active_support/json/encoders/date_time.rb | 2 -- .../lib/active_support/json/encoders/enumerable.rb | 4 +--- .../lib/active_support/json/encoders/false_class.rb | 2 -- activesupport/lib/active_support/json/encoders/hash.rb | 14 +++++++------- .../lib/active_support/json/encoders/nil_class.rb | 2 -- activesupport/lib/active_support/json/encoders/numeric.rb | 2 -- activesupport/lib/active_support/json/encoders/object.rb | 2 +- activesupport/lib/active_support/json/encoders/regexp.rb | 2 -- activesupport/lib/active_support/json/encoders/string.rb | 2 -- activesupport/lib/active_support/json/encoders/symbol.rb | 4 +--- activesupport/lib/active_support/json/encoders/time.rb | 2 -- .../lib/active_support/json/encoders/true_class.rb | 2 -- activesupport/lib/active_support/json/encoding.rb | 3 ++- 14 files changed, 12 insertions(+), 33 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoders/date.rb b/activesupport/lib/active_support/json/encoders/date.rb index 79c3957362..1aebdd2764 100644 --- a/activesupport/lib/active_support/json/encoders/date.rb +++ b/activesupport/lib/active_support/json/encoders/date.rb @@ -18,6 +18,4 @@ class Date %("#{strftime("%Y/%m/%d")}") end end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/date_time.rb b/activesupport/lib/active_support/json/encoders/date_time.rb index cdfc39b9f3..096e0dd36b 100644 --- a/activesupport/lib/active_support/json/encoders/date_time.rb +++ b/activesupport/lib/active_support/json/encoders/date_time.rb @@ -18,6 +18,4 @@ class DateTime strftime('"%Y/%m/%d %H:%M:%S %z"') end end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/enumerable.rb b/activesupport/lib/active_support/json/encoders/enumerable.rb index e1c3ec249d..6e0c3b6b9c 100644 --- a/activesupport/lib/active_support/json/encoders/enumerable.rb +++ b/activesupport/lib/active_support/json/encoders/enumerable.rb @@ -6,9 +6,7 @@ module Enumerable # # => users.to_json(:only => :name) # # will pass the :only => :name option to each user. - def rails_to_json(options = {}) #:nodoc: + def rails_to_json(options = nil) #:nodoc: "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ','}]" end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/false_class.rb b/activesupport/lib/active_support/json/encoders/false_class.rb index a7657cca37..4c47b3372e 100644 --- a/activesupport/lib/active_support/json/encoders/false_class.rb +++ b/activesupport/lib/active_support/json/encoders/false_class.rb @@ -2,6 +2,4 @@ class FalseClass def rails_to_json(options = nil) #:nodoc: 'false' end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb index 19b97d7b8c..cd8639c1dd 100644 --- a/activesupport/lib/active_support/json/encoders/hash.rb +++ b/activesupport/lib/active_support/json/encoders/hash.rb @@ -30,13 +30,15 @@ class Hash # would pass the :include => :posts option to users, # allowing the posts association in the User model to be converted to JSON # as well. - def rails_to_json(options = {}) #:nodoc: + def rails_to_json(options = nil) #:nodoc: hash_keys = self.keys - if except = options[:except] - hash_keys = hash_keys - Array.wrap(except) - elsif only = options[:only] - hash_keys = hash_keys & Array.wrap(only) + if options + if except = options[:except] + hash_keys = hash_keys - Array.wrap(except) + elsif only = options[:only] + hash_keys = hash_keys & Array.wrap(only) + end end result = '{' @@ -45,6 +47,4 @@ class Hash end * ',' result << '}' end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/nil_class.rb b/activesupport/lib/active_support/json/encoders/nil_class.rb index b31e1dd249..b7b63e26d5 100644 --- a/activesupport/lib/active_support/json/encoders/nil_class.rb +++ b/activesupport/lib/active_support/json/encoders/nil_class.rb @@ -2,6 +2,4 @@ class NilClass def rails_to_json(options = nil) #:nodoc: 'null' end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/numeric.rb b/activesupport/lib/active_support/json/encoders/numeric.rb index 491b330c39..b969902da0 100644 --- a/activesupport/lib/active_support/json/encoders/numeric.rb +++ b/activesupport/lib/active_support/json/encoders/numeric.rb @@ -2,6 +2,4 @@ class Numeric def rails_to_json(options = nil) #:nodoc: to_s end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/object.rb b/activesupport/lib/active_support/json/encoders/object.rb index d68f50562e..57603bd1e6 100644 --- a/activesupport/lib/active_support/json/encoders/object.rb +++ b/activesupport/lib/active_support/json/encoders/object.rb @@ -2,7 +2,7 @@ require 'active_support/core_ext/object/instance_variables' class Object # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. - def rails_to_json(options = {}) + def rails_to_json(options = nil) ActiveSupport::JSON.encode(instance_values, options) end diff --git a/activesupport/lib/active_support/json/encoders/regexp.rb b/activesupport/lib/active_support/json/encoders/regexp.rb index 63ccd7c490..ff7dd67544 100644 --- a/activesupport/lib/active_support/json/encoders/regexp.rb +++ b/activesupport/lib/active_support/json/encoders/regexp.rb @@ -2,6 +2,4 @@ class Regexp def rails_to_json(options = nil) #:nodoc: inspect end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/string.rb b/activesupport/lib/active_support/json/encoders/string.rb index 27bef3b9cc..da16111fd5 100644 --- a/activesupport/lib/active_support/json/encoders/string.rb +++ b/activesupport/lib/active_support/json/encoders/string.rb @@ -33,6 +33,4 @@ class String s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&') } + '"' end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/symbol.rb b/activesupport/lib/active_support/json/encoders/symbol.rb index 6487bf8cb7..c39eda81c1 100644 --- a/activesupport/lib/active_support/json/encoders/symbol.rb +++ b/activesupport/lib/active_support/json/encoders/symbol.rb @@ -1,7 +1,5 @@ class Symbol - def rails_to_json(options = {}) #:nodoc: + def rails_to_json(options = nil) #:nodoc: ActiveSupport::JSON.encode(to_s, options) end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/time.rb b/activesupport/lib/active_support/json/encoders/time.rb index 2699672949..1cb0808490 100644 --- a/activesupport/lib/active_support/json/encoders/time.rb +++ b/activesupport/lib/active_support/json/encoders/time.rb @@ -20,6 +20,4 @@ class Time %("#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") end end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoders/true_class.rb b/activesupport/lib/active_support/json/encoders/true_class.rb index ac7c7d1e87..a22c487a93 100644 --- a/activesupport/lib/active_support/json/encoders/true_class.rb +++ b/activesupport/lib/active_support/json/encoders/true_class.rb @@ -2,6 +2,4 @@ class TrueClass def rails_to_json(options = nil) #:nodoc: 'true' end - - alias to_json rails_to_json end diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index e8e9308495..acccb62aea 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -4,7 +4,8 @@ module ActiveSupport end # Converts a Ruby object into a JSON string. - def self.encode(value, options = {}) + def self.encode(value, options = nil) + options ||= {} seen = (options[:seen] ||= []) raise CircularReferenceError, 'object references itself' if seen.include?(value.object_id) seen << value.object_id -- cgit v1.2.3 From 4a8d2ef0a552e04d6cb35b91e23dd3979783b586 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 15:53:32 -0700 Subject: Extract json string escaping --- activesupport/lib/active_support/json.rb | 38 ++++++++++++++++++---- .../lib/active_support/json/encoders/string.rb | 33 +------------------ 2 files changed, 33 insertions(+), 38 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index fc433de582..b2ebe9adc8 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -11,6 +11,33 @@ module ActiveSupport # 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})?))$/ + module Encoding #:nodoc: + mattr_accessor :escape_regex + + ESCAPED_CHARS = { + "\010" => '\b', + "\f" => '\f', + "\n" => '\n', + "\r" => '\r', + "\t" => '\t', + '"' => '\"', + '\\' => '\\\\', + '>' => '\u003E', + '<' => '\u003C', + '&' => '\u0026' + } + + def self.escape(string) + json = '"' + string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] } + json.force_encoding('ascii-8bit') if respond_to?(:force_encoding) + json.gsub(/([\xC0-\xDF][\x80-\xBF]| + [\xE0-\xEF][\x80-\xBF]{2}| + [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s| + s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&') + } + '"' + end + end + class << self attr_reader :backend delegate :decode, :to => :backend @@ -34,9 +61,7 @@ module ActiveSupport end class << self - def escape_html_entities_in_json - @escape_html_entities_in_json - end + attr_reader :escape_html_entities_in_json def escape_html_entities_in_json=(value) ActiveSupport::JSON::Encoding.escape_regex = \ @@ -48,8 +73,9 @@ module ActiveSupport @escape_html_entities_in_json = value end end - - JSON.backend = 'Yaml' end -require 'active_support/json/encoding' \ No newline at end of file +ActiveSupport.escape_html_entities_in_json = true +ActiveSupport::JSON.backend = 'Yaml' + +require 'active_support/json/encoding' diff --git a/activesupport/lib/active_support/json/encoders/string.rb b/activesupport/lib/active_support/json/encoders/string.rb index da16111fd5..ea82ca29fb 100644 --- a/activesupport/lib/active_support/json/encoders/string.rb +++ b/activesupport/lib/active_support/json/encoders/string.rb @@ -1,36 +1,5 @@ -module ActiveSupport - module JSON - module Encoding - mattr_accessor :escape_regex - - ESCAPED_CHARS = { - "\010" => '\b', - "\f" => '\f', - "\n" => '\n', - "\r" => '\r', - "\t" => '\t', - '"' => '\"', - '\\' => '\\\\', - '>' => '\u003E', - '<' => '\u003C', - '&' => '\u0026' - } - end - end -end - -ActiveSupport.escape_html_entities_in_json = true - class String def rails_to_json(options = nil) #:nodoc: - json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s| - ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s] - } - json.force_encoding('ascii-8bit') if respond_to?(:force_encoding) - json.gsub(/([\xC0-\xDF][\x80-\xBF]| - [\xE0-\xEF][\x80-\xBF]{2}| - [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s| - s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&') - } + '"' + ActiveSupport::JSON::Encoding.escape(self) end end -- cgit v1.2.3 From 3bd32754e24c4894abd2316eb0be3aeed08cf906 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 15:54:28 -0700 Subject: Privatize rails_to_json --- .../lib/active_support/json/encoders/date.rb | 37 ++++----- .../lib/active_support/json/encoders/date_time.rb | 37 ++++----- .../lib/active_support/json/encoders/enumerable.rb | 21 +++--- .../active_support/json/encoders/false_class.rb | 7 +- .../lib/active_support/json/encoders/hash.rb | 87 +++++++++++----------- .../lib/active_support/json/encoders/nil_class.rb | 7 +- .../lib/active_support/json/encoders/numeric.rb | 7 +- .../lib/active_support/json/encoders/object.rb | 9 ++- .../lib/active_support/json/encoders/regexp.rb | 7 +- .../lib/active_support/json/encoders/string.rb | 7 +- .../lib/active_support/json/encoders/symbol.rb | 7 +- .../lib/active_support/json/encoders/time.rb | 37 ++++----- .../lib/active_support/json/encoders/true_class.rb | 7 +- activesupport/lib/active_support/json/variable.rb | 7 +- activesupport/lib/active_support/time_with_zone.rb | 42 +++++------ activesupport/test/json/encoding_test.rb | 2 +- 16 files changed, 171 insertions(+), 157 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoders/date.rb b/activesupport/lib/active_support/json/encoders/date.rb index 1aebdd2764..f1479e11e0 100644 --- a/activesupport/lib/active_support/json/encoders/date.rb +++ b/activesupport/lib/active_support/json/encoders/date.rb @@ -1,21 +1,22 @@ class Date - # Returns a JSON string representing the date. If ActiveSupport.use_standard_json_time_format is set to true, the - # ISO 8601 format is used. - # - # ==== Examples - # - # # With ActiveSupport.use_standard_json_time_format = true - # Date.new(2005,2,1).to_json - # # => "2005-02-01" - # - # # With ActiveSupport.use_standard_json_time_format = false - # Date.new(2005,2,1).to_json - # # => "2005/02/01" - def rails_to_json(options = nil) - if ActiveSupport.use_standard_json_time_format - %("#{strftime("%Y-%m-%d")}") - else - %("#{strftime("%Y/%m/%d")}") + private + # Returns a JSON string representing the date. If ActiveSupport.use_standard_json_time_format is set to true, the + # ISO 8601 format is used. + # + # ==== Examples + # + # # With ActiveSupport.use_standard_json_time_format = true + # Date.new(2005,2,1).to_json + # # => "2005-02-01" + # + # # With ActiveSupport.use_standard_json_time_format = false + # Date.new(2005,2,1).to_json + # # => "2005/02/01" + def rails_to_json(options = nil) + if ActiveSupport.use_standard_json_time_format + %("#{strftime("%Y-%m-%d")}") + else + %("#{strftime("%Y/%m/%d")}") + end end - end end diff --git a/activesupport/lib/active_support/json/encoders/date_time.rb b/activesupport/lib/active_support/json/encoders/date_time.rb index 096e0dd36b..343612afe9 100644 --- a/activesupport/lib/active_support/json/encoders/date_time.rb +++ b/activesupport/lib/active_support/json/encoders/date_time.rb @@ -1,21 +1,22 @@ class DateTime - # Returns a JSON string representing the datetime. If ActiveSupport.use_standard_json_time_format is set to true, the - # ISO 8601 format is used. - # - # ==== Examples - # - # # With ActiveSupport.use_standard_json_time_format = true - # DateTime.civil(2005,2,1,15,15,10).to_json - # # => "2005-02-01T15:15:10+00:00" - # - # # With ActiveSupport.use_standard_json_time_format = false - # DateTime.civil(2005,2,1,15,15,10).to_json - # # => "2005/02/01 15:15:10 +0000" - def rails_to_json(options = nil) - if ActiveSupport.use_standard_json_time_format - xmlschema.inspect - else - strftime('"%Y/%m/%d %H:%M:%S %z"') + private + # Returns a JSON string representing the datetime. If ActiveSupport.use_standard_json_time_format is set to true, the + # ISO 8601 format is used. + # + # ==== Examples + # + # # With ActiveSupport.use_standard_json_time_format = true + # DateTime.civil(2005,2,1,15,15,10).to_json + # # => "2005-02-01T15:15:10+00:00" + # + # # With ActiveSupport.use_standard_json_time_format = false + # DateTime.civil(2005,2,1,15,15,10).to_json + # # => "2005/02/01 15:15:10 +0000" + def rails_to_json(options = nil) + if ActiveSupport.use_standard_json_time_format + xmlschema.inspect + else + strftime('"%Y/%m/%d %H:%M:%S %z"') + end end - end end diff --git a/activesupport/lib/active_support/json/encoders/enumerable.rb b/activesupport/lib/active_support/json/encoders/enumerable.rb index 6e0c3b6b9c..adde7445b3 100644 --- a/activesupport/lib/active_support/json/encoders/enumerable.rb +++ b/activesupport/lib/active_support/json/encoders/enumerable.rb @@ -1,12 +1,13 @@ module Enumerable - # Returns a JSON string representing the enumerable. Any +options+ - # given will be passed on to its elements. For example: - # - # users = User.find(:all) - # # => users.to_json(:only => :name) - # - # will pass the :only => :name option to each user. - def rails_to_json(options = nil) #:nodoc: - "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ','}]" - end + private + # Returns a JSON string representing the enumerable. Any +options+ + # given will be passed on to its elements. For example: + # + # users = User.find(:all) + # # => users.to_json(:only => :name) + # + # will pass the :only => :name option to each user. + def rails_to_json(options = nil) #:nodoc: + "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ','}]" + end end diff --git a/activesupport/lib/active_support/json/encoders/false_class.rb b/activesupport/lib/active_support/json/encoders/false_class.rb index 4c47b3372e..673465860a 100644 --- a/activesupport/lib/active_support/json/encoders/false_class.rb +++ b/activesupport/lib/active_support/json/encoders/false_class.rb @@ -1,5 +1,6 @@ class FalseClass - def rails_to_json(options = nil) #:nodoc: - 'false' - end + private + def rails_to_json(options = nil) + 'false' + end end diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb index cd8639c1dd..5aec547b9b 100644 --- a/activesupport/lib/active_support/json/encoders/hash.rb +++ b/activesupport/lib/active_support/json/encoders/hash.rb @@ -1,50 +1,51 @@ require 'active_support/core_ext/array/wrap' class Hash - # Returns a JSON string representing the hash. - # - # Without any +options+, the returned JSON string will include all - # the hash keys. For example: - # - # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json - # # => {"name": "Konata Izumi", "1": 2, "age": 16} - # - # The keys in the JSON string are unordered due to the nature of hashes. - # - # The :only and :except options can be used to limit the - # attributes included, and will accept 1 or more hash keys to include/exclude. - # - # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:only => [:name, 'age']) - # # => {"name": "Konata Izumi", "age": 16} - # - # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1) - # # => {"name": "Konata Izumi", "age": 16} - # - # The +options+ also filter down to any hash values. This is particularly - # useful for converting hashes containing ActiveRecord objects or any object - # that responds to options in their to_json method. For example: - # - # users = User.find(:all) - # { :users => users, :count => users.size }.to_json(:include => :posts) - # - # would pass the :include => :posts option to users, - # allowing the posts association in the User model to be converted to JSON - # as well. - def rails_to_json(options = nil) #:nodoc: - hash_keys = self.keys + private + # Returns a JSON string representing the hash. + # + # Without any +options+, the returned JSON string will include all + # the hash keys. For example: + # + # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json + # # => {"name": "Konata Izumi", "1": 2, "age": 16} + # + # The keys in the JSON string are unordered due to the nature of hashes. + # + # The :only and :except options can be used to limit the + # attributes included, and will accept 1 or more hash keys to include/exclude. + # + # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:only => [:name, 'age']) + # # => {"name": "Konata Izumi", "age": 16} + # + # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1) + # # => {"name": "Konata Izumi", "age": 16} + # + # The +options+ also filter down to any hash values. This is particularly + # useful for converting hashes containing ActiveRecord objects or any object + # that responds to options in their to_json method. For example: + # + # users = User.find(:all) + # { :users => users, :count => users.size }.to_json(:include => :posts) + # + # would pass the :include => :posts option to users, + # allowing the posts association in the User model to be converted to JSON + # as well. + def rails_to_json(options = nil) #:nodoc: + hash_keys = self.keys - if options - if except = options[:except] - hash_keys = hash_keys - Array.wrap(except) - elsif only = options[:only] - hash_keys = hash_keys & Array.wrap(only) + if options + if except = options[:except] + hash_keys = hash_keys - Array.wrap(except) + elsif only = options[:only] + hash_keys = hash_keys & Array.wrap(only) + end end - end - result = '{' - result << hash_keys.map do |key| - "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(self[key], options)}" - end * ',' - result << '}' - end + result = '{' + result << hash_keys.map do |key| + "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(self[key], options)}" + end * ',' + result << '}' + end end diff --git a/activesupport/lib/active_support/json/encoders/nil_class.rb b/activesupport/lib/active_support/json/encoders/nil_class.rb index b7b63e26d5..5343badc9c 100644 --- a/activesupport/lib/active_support/json/encoders/nil_class.rb +++ b/activesupport/lib/active_support/json/encoders/nil_class.rb @@ -1,5 +1,6 @@ class NilClass - def rails_to_json(options = nil) #:nodoc: - 'null' - end + private + def rails_to_json(options = nil) + 'null' + end end diff --git a/activesupport/lib/active_support/json/encoders/numeric.rb b/activesupport/lib/active_support/json/encoders/numeric.rb index b969902da0..42de2f4ea7 100644 --- a/activesupport/lib/active_support/json/encoders/numeric.rb +++ b/activesupport/lib/active_support/json/encoders/numeric.rb @@ -1,5 +1,6 @@ class Numeric - def rails_to_json(options = nil) #:nodoc: - to_s - end + private + def rails_to_json(options = nil) + to_s + end end diff --git a/activesupport/lib/active_support/json/encoders/object.rb b/activesupport/lib/active_support/json/encoders/object.rb index 57603bd1e6..4722feb7db 100644 --- a/activesupport/lib/active_support/json/encoders/object.rb +++ b/activesupport/lib/active_support/json/encoders/object.rb @@ -2,9 +2,12 @@ require 'active_support/core_ext/object/instance_variables' class Object # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. - def rails_to_json(options = nil) - ActiveSupport::JSON.encode(instance_values, options) + def to_json(options = nil) + rails_to_json(options) end - alias to_json rails_to_json + private + def rails_to_json(options = nil) + ActiveSupport::JSON.encode(instance_values, options) + end end diff --git a/activesupport/lib/active_support/json/encoders/regexp.rb b/activesupport/lib/active_support/json/encoders/regexp.rb index ff7dd67544..62be810be5 100644 --- a/activesupport/lib/active_support/json/encoders/regexp.rb +++ b/activesupport/lib/active_support/json/encoders/regexp.rb @@ -1,5 +1,6 @@ class Regexp - def rails_to_json(options = nil) #:nodoc: - inspect - end + private + def rails_to_json(options = nil) + inspect + end end diff --git a/activesupport/lib/active_support/json/encoders/string.rb b/activesupport/lib/active_support/json/encoders/string.rb index ea82ca29fb..6b9dcd97bf 100644 --- a/activesupport/lib/active_support/json/encoders/string.rb +++ b/activesupport/lib/active_support/json/encoders/string.rb @@ -1,5 +1,6 @@ class String - def rails_to_json(options = nil) #:nodoc: - ActiveSupport::JSON::Encoding.escape(self) - end + private + def rails_to_json(options = nil) + ActiveSupport::JSON::Encoding.escape(self) + end end diff --git a/activesupport/lib/active_support/json/encoders/symbol.rb b/activesupport/lib/active_support/json/encoders/symbol.rb index c39eda81c1..333cf773c1 100644 --- a/activesupport/lib/active_support/json/encoders/symbol.rb +++ b/activesupport/lib/active_support/json/encoders/symbol.rb @@ -1,5 +1,6 @@ class Symbol - def rails_to_json(options = nil) #:nodoc: - ActiveSupport::JSON.encode(to_s, options) - end + private + def rails_to_json(options = nil) + ActiveSupport::JSON.encode(to_s, options) + end end diff --git a/activesupport/lib/active_support/json/encoders/time.rb b/activesupport/lib/active_support/json/encoders/time.rb index 1cb0808490..c1cf3398c2 100644 --- a/activesupport/lib/active_support/json/encoders/time.rb +++ b/activesupport/lib/active_support/json/encoders/time.rb @@ -1,23 +1,24 @@ require 'active_support/core_ext/time/conversions' class Time - # Returns a JSON string representing the time. If ActiveSupport.use_standard_json_time_format is set to true, the - # ISO 8601 format is used. - # - # ==== Examples - # - # # With ActiveSupport.use_standard_json_time_format = true - # Time.utc(2005,2,1,15,15,10).to_json - # # => "2005-02-01T15:15:10Z" - # - # # With ActiveSupport.use_standard_json_time_format = false - # Time.utc(2005,2,1,15,15,10).to_json - # # => "2005/02/01 15:15:10 +0000" - def rails_to_json(options = nil) - if ActiveSupport.use_standard_json_time_format - xmlschema.inspect - else - %("#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") + private + # Returns a JSON string representing the time. If ActiveSupport.use_standard_json_time_format is set to true, the + # ISO 8601 format is used. + # + # ==== Examples + # + # # With ActiveSupport.use_standard_json_time_format = true + # Time.utc(2005,2,1,15,15,10).to_json + # # => "2005-02-01T15:15:10Z" + # + # # With ActiveSupport.use_standard_json_time_format = false + # Time.utc(2005,2,1,15,15,10).to_json + # # => "2005/02/01 15:15:10 +0000" + def rails_to_json(options = nil) + if ActiveSupport.use_standard_json_time_format + xmlschema.inspect + else + %("#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") + end end - end end diff --git a/activesupport/lib/active_support/json/encoders/true_class.rb b/activesupport/lib/active_support/json/encoders/true_class.rb index a22c487a93..6d5d063254 100644 --- a/activesupport/lib/active_support/json/encoders/true_class.rb +++ b/activesupport/lib/active_support/json/encoders/true_class.rb @@ -1,5 +1,6 @@ class TrueClass - def rails_to_json(options = nil) #:nodoc: - 'true' - end + private + def rails_to_json(options = nil) + 'true' + end end diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb index 3ee152ee3c..2c7b449a50 100644 --- a/activesupport/lib/active_support/json/variable.rb +++ b/activesupport/lib/active_support/json/variable.rb @@ -2,9 +2,10 @@ module ActiveSupport module JSON # A string that returns itself as its JSON-encoded form. class Variable < String - def rails_to_json(options=nil) - self - end + private + def rails_to_json(options = nil) + self + end end end end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 1949ce0ad3..c02ee1a524 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -118,28 +118,6 @@ module ActiveSupport end alias_method :iso8601, :xmlschema - # Returns a JSON string representing the TimeWithZone. If ActiveSupport.use_standard_json_time_format is set to - # true, the ISO 8601 format is used. - # - # ==== Examples - # - # # With ActiveSupport.use_standard_json_time_format = true - # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json - # # => "2005-02-01T15:15:10Z" - # - # # With ActiveSupport.use_standard_json_time_format = false - # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json - # # => "2005/02/01 15:15:10 +0000" - def rails_to_json(options = nil) - if !ActiveSupport.respond_to?(:use_standard_json_time_format) || ActiveSupport.use_standard_json_time_format - xmlschema.inspect - else - %("#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") - end - end - - alias to_json rails_to_json - def to_yaml(options = {}) if options.kind_of?(YAML::Emitter) utc.to_yaml(options) @@ -323,6 +301,26 @@ module ActiveSupport end private + # Returns a JSON string representing the TimeWithZone. If ActiveSupport.use_standard_json_time_format is set to + # true, the ISO 8601 format is used. + # + # ==== Examples + # + # # With ActiveSupport.use_standard_json_time_format = true + # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json + # # => "2005-02-01T15:15:10Z" + # + # # With ActiveSupport.use_standard_json_time_format = false + # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json + # # => "2005/02/01 15:15:10 +0000" + def rails_to_json(options = nil) + if !ActiveSupport.respond_to?(:use_standard_json_time_format) || ActiveSupport.use_standard_json_time_format + xmlschema.inspect + else + %("#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") + end + end + def get_period_and_ensure_valid_local_time # we don't want a Time.local instance enforcing its own DST rules as well, # so transfer time values to a utc constructor if necessary diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index db24b3d96a..1a0e6d543c 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -134,6 +134,6 @@ class JsonOptionsTests < Test::Unit::TestCase ActiveSupport::JSON.expects(:encode).with(2, json_options) ActiveSupport::JSON.expects(:encode).with('foo', json_options) - [1, 2, 'foo'].rails_to_json(json_options) + [1, 2, 'foo'].send(:rails_to_json, json_options) end end -- cgit v1.2.3 From ea712364e202816ce99f53824f01d0aa6f178247 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 15:56:08 -0700 Subject: Don't undefine object_id --- activesupport/lib/active_support/deprecation/proxy_wrappers.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb index ec54efe08e..dec56715be 100644 --- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb +++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb @@ -3,7 +3,7 @@ require 'active_support/inflector' module ActiveSupport module Deprecation class DeprecationProxy #:nodoc: - instance_methods.each { |m| undef_method m unless m =~ /^__/ } + instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ } # Don't give a deprecation warning on inspect since test/unit and error # logs rely on it for diagnostics. -- cgit v1.2.3 From 1d71a34afa206e611d2dc5368c55cc4aed25ba01 Mon Sep 17 00:00:00 2001 From: Stephen Bannasch Date: Sun, 15 Mar 2009 06:32:29 -0400 Subject: add JRuby-JDOM backend for XmlMini Signed-off-by: Jeremy Kemper --- activesupport/lib/active_support/xml_mini/jdom.rb | 162 ++++++++++++++++++++++ activesupport/test/xml_mini/jdom_engine_test.rb | 153 ++++++++++++++++++++ 2 files changed, 315 insertions(+) create mode 100644 activesupport/lib/active_support/xml_mini/jdom.rb create mode 100644 activesupport/test/xml_mini/jdom_engine_test.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb new file mode 100644 index 0000000000..d795d55690 --- /dev/null +++ b/activesupport/lib/active_support/xml_mini/jdom.rb @@ -0,0 +1,162 @@ +raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM =~ /java/ + +require 'jruby' +include Java + +import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory +import java.io.StringReader unless defined? StringReader +import org.xml.sax.InputSource unless defined? InputSource +import org.xml.sax.Attributes unless defined? Attributes +import org.w3c.dom.Node unless defined? Node + +# = XmlMini JRuby JDOM implementation +module ActiveSupport + module XmlMini_JDOM #:nodoc: + extend self + + CONTENT_KEY = '__content__'.freeze + + NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE + DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE + PROCESSING_INSTRUCTION_NODE TEXT_NODE} + + node_type_map = {} + NODE_TYPE_NAMES.each { |type| node_type_map[Node.send(type)] = type } + + # Parse an XML Document string into a simple hash using Java's jdom. + # string:: + # XML Document string to parse + def parse(string) + if string.blank? + {} + else + @dbf = DocumentBuilderFactory.new_instance + xml_string_reader = StringReader.new(string) + xml_input_source = InputSource.new(xml_string_reader) + doc = @dbf.new_document_builder.parse(xml_input_source) + merge_element!({}, doc.document_element) + end + end + + private + + # Convert an XML element and merge into the hash + # + # hash:: + # Hash to merge the converted element into. + # element:: + # XML element to merge into hash + def merge_element!(hash, element) + merge!(hash, element.tag_name, collapse(element)) + end + + # Actually converts an XML document element into a data structure. + # + # element:: + # The document element to be collapsed. + def collapse(element) + hash = get_attributes(element) + + child_nodes = element.child_nodes + if child_nodes.length > 0 + for i in 0...child_nodes.length + child = child_nodes.item(i) + merge_element!(hash, child) unless child.node_type == Node.TEXT_NODE + end + merge_texts!(hash, element) unless empty_content?(element) + hash + else + merge_texts!(hash, element) + end + end + + # Merge all the texts of an element into the hash + # + # hash:: + # Hash to add the converted emement to. + # element:: + # XML element whose texts are to me merged into the hash + def merge_texts!(hash, element) + text_children = texts(element) + if text_children.join.empty? + hash + else + # must use value to prevent double-escaping + merge!(hash, CONTENT_KEY, text_children.join) + end + end + + # Adds a new key/value pair to an existing Hash. If the key to be added + # already exists and the existing value associated with key is not + # an Array, it will be wrapped in an Array. Then the new value is + # appended to that Array. + # + # hash:: + # Hash to add key/value pair to. + # key:: + # Key to be added. + # value:: + # Value to be associated with key. + def merge!(hash, key, value) + if hash.has_key?(key) + if hash[key].instance_of?(Array) + hash[key] << value + else + hash[key] = [hash[key], value] + end + elsif value.instance_of?(Array) + hash[key] = [value] + else + hash[key] = value + end + hash + end + + # Converts the attributes array of an XML element into a hash. + # Returns an empty Hash if node has no attributes. + # + # element:: + # XML element to extract attributes from. + def get_attributes(element) + attribute_hash = {} + attributes = element.attributes + for i in 0...attributes.length + attribute_hash[attributes.item(i).name] = attributes.item(i).value + end + attribute_hash + end + + # Determines if a document element has text content + # + # element:: + # XML element to be checked. + def texts(element) + texts = [] + child_nodes = element.child_nodes + for i in 0...child_nodes.length + item = child_nodes.item(i) + if item.node_type == Node.TEXT_NODE + texts << item.get_data + end + end + texts + end + + # Determines if a document element has text content + # + # element:: + # XML element to be checked. + def empty_content?(element) + text = '' + child_nodes = element.child_nodes + for i in 0...child_nodes.length + item = child_nodes.item(i) + if item.node_type == Node.TEXT_NODE + text << item.get_data.strip + end + end + text.strip.length == 0 + end + end +end diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb new file mode 100644 index 0000000000..b745228994 --- /dev/null +++ b/activesupport/test/xml_mini/jdom_engine_test.rb @@ -0,0 +1,153 @@ +require 'abstract_unit' +require 'active_support/xml_mini' + +if RUBY_PLATFORM =~ /java/ + +class JDOMEngineTest < Test::Unit::TestCase + include ActiveSupport + + def setup + @default_backend = XmlMini.backend + XmlMini.backend = 'JDOM' + end + + def teardown + XmlMini.backend = @default_backend + end + + # def test_file_from_xml + # hash = Hash.from_xml(<<-eoxml) + # + # + # + # + # eoxml + # assert hash.has_key?('blog') + # assert hash['blog'].has_key?('logo') + # + # file = hash['blog']['logo'] + # assert_equal 'logo.png', file.original_filename + # assert_equal 'image/png', file.content_type + # end + + def test_exception_thrown_on_expansion_attack + assert_raise NativeException do + attack_xml = <<-EOT + + + + + + + + + ]> + + &a; + + EOT + Hash.from_xml(attack_xml) + end + end + + def test_setting_JDOM_as_backend + XmlMini.backend = 'JDOM' + assert_equal XmlMini_JDOM, XmlMini.backend + end + + def test_blank_returns_empty_hash + assert_equal({}, XmlMini.parse(nil)) + assert_equal({}, XmlMini.parse('')) + end + + def test_array_type_makes_an_array + assert_equal_rexml(<<-eoxml) + + + a post + another post + + + eoxml + end + + def test_one_node_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end + + def test_one_node_with_attributes_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end + + def test_products_node_with_book_node_as_hash + assert_equal_rexml(<<-eoxml) + + + + eoxml + end + + def test_products_node_with_two_book_nodes_as_hash + assert_equal_rexml(<<-eoxml) + + + + + eoxml + end + + def test_single_node_with_content_as_hash + assert_equal_rexml(<<-eoxml) + + hello world + + eoxml + end + + def test_children_with_children + assert_equal_rexml(<<-eoxml) + + + + + + eoxml + end + + def test_children_with_text + assert_equal_rexml(<<-eoxml) + + + hello everyone + + + eoxml + end + + def test_children_with_non_adjacent_text + assert_equal_rexml(<<-eoxml) + + good + + hello everyone + + morning + + eoxml + end + + private + def assert_equal_rexml(xml) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, XmlMini.parse(xml)) + end +end + +else + # don't run these test because we aren't running in JRuby +end -- cgit v1.2.3 From 8aaed3d456bad8a0bdf4789b69b41f7d817f981c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 16:21:57 -0700 Subject: Convert encoding before escaping --- activesupport/lib/active_support/json.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index b2ebe9adc8..5072992cdf 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -28,13 +28,14 @@ module ActiveSupport } def self.escape(string) - json = '"' + string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] } - json.force_encoding('ascii-8bit') if respond_to?(:force_encoding) - json.gsub(/([\xC0-\xDF][\x80-\xBF]| + string = string.dup.force_encoding(::Encoding::BINARY) if string.respond_to?(:force_encoding) + json = string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }. + gsub(/([\xC0-\xDF][\x80-\xBF]| [\xE0-\xEF][\x80-\xBF]{2}| [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s| - s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&') - } + '"' + s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&') + } + %("#{json}") end end -- cgit v1.2.3 From ee46ffedb88f812467485167036c7d254d0ce757 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 20:04:47 -0700 Subject: Now that we have a separate internal rails_to_json, use a separate circular reference stack instead of sticking it in the options hash --- activesupport/lib/active_support/json/encoders/date.rb | 2 +- activesupport/lib/active_support/json/encoders/date_time.rb | 2 +- .../lib/active_support/json/encoders/enumerable.rb | 4 ++-- .../lib/active_support/json/encoders/false_class.rb | 2 +- activesupport/lib/active_support/json/encoders/hash.rb | 4 ++-- activesupport/lib/active_support/json/encoders/nil_class.rb | 2 +- activesupport/lib/active_support/json/encoders/numeric.rb | 2 +- activesupport/lib/active_support/json/encoders/object.rb | 6 +++--- activesupport/lib/active_support/json/encoders/regexp.rb | 2 +- activesupport/lib/active_support/json/encoders/string.rb | 2 +- activesupport/lib/active_support/json/encoders/symbol.rb | 4 ++-- activesupport/lib/active_support/json/encoders/time.rb | 2 +- .../lib/active_support/json/encoders/true_class.rb | 2 +- activesupport/lib/active_support/json/encoding.rb | 13 +++++++------ activesupport/lib/active_support/json/variable.rb | 2 +- activesupport/lib/active_support/time_with_zone.rb | 2 +- 16 files changed, 27 insertions(+), 26 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoders/date.rb b/activesupport/lib/active_support/json/encoders/date.rb index f1479e11e0..9adb3c20e2 100644 --- a/activesupport/lib/active_support/json/encoders/date.rb +++ b/activesupport/lib/active_support/json/encoders/date.rb @@ -12,7 +12,7 @@ class Date # # With ActiveSupport.use_standard_json_time_format = false # Date.new(2005,2,1).to_json # # => "2005/02/01" - def rails_to_json(options = nil) + def rails_to_json(*) if ActiveSupport.use_standard_json_time_format %("#{strftime("%Y-%m-%d")}") else diff --git a/activesupport/lib/active_support/json/encoders/date_time.rb b/activesupport/lib/active_support/json/encoders/date_time.rb index 343612afe9..3a29292b24 100644 --- a/activesupport/lib/active_support/json/encoders/date_time.rb +++ b/activesupport/lib/active_support/json/encoders/date_time.rb @@ -12,7 +12,7 @@ class DateTime # # With ActiveSupport.use_standard_json_time_format = false # DateTime.civil(2005,2,1,15,15,10).to_json # # => "2005/02/01 15:15:10 +0000" - def rails_to_json(options = nil) + def rails_to_json(*) if ActiveSupport.use_standard_json_time_format xmlschema.inspect else diff --git a/activesupport/lib/active_support/json/encoders/enumerable.rb b/activesupport/lib/active_support/json/encoders/enumerable.rb index adde7445b3..898990a59c 100644 --- a/activesupport/lib/active_support/json/encoders/enumerable.rb +++ b/activesupport/lib/active_support/json/encoders/enumerable.rb @@ -7,7 +7,7 @@ module Enumerable # # => users.to_json(:only => :name) # # will pass the :only => :name option to each user. - def rails_to_json(options = nil) #:nodoc: - "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ','}]" + def rails_to_json(options = nil, *args) #:nodoc: + "[#{map { |value| ActiveSupport::JSON.encode(value, options, *args) } * ','}]" end end diff --git a/activesupport/lib/active_support/json/encoders/false_class.rb b/activesupport/lib/active_support/json/encoders/false_class.rb index 673465860a..eb975fe542 100644 --- a/activesupport/lib/active_support/json/encoders/false_class.rb +++ b/activesupport/lib/active_support/json/encoders/false_class.rb @@ -1,6 +1,6 @@ class FalseClass private - def rails_to_json(options = nil) + def rails_to_json(*) 'false' end end diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb index 5aec547b9b..4771484843 100644 --- a/activesupport/lib/active_support/json/encoders/hash.rb +++ b/activesupport/lib/active_support/json/encoders/hash.rb @@ -31,7 +31,7 @@ class Hash # would pass the :include => :posts option to users, # allowing the posts association in the User model to be converted to JSON # as well. - def rails_to_json(options = nil) #:nodoc: + def rails_to_json(options = nil, *args) #:nodoc: hash_keys = self.keys if options @@ -44,7 +44,7 @@ class Hash result = '{' result << hash_keys.map do |key| - "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(self[key], options)}" + "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(self[key], options, *args)}" end * ',' result << '}' end diff --git a/activesupport/lib/active_support/json/encoders/nil_class.rb b/activesupport/lib/active_support/json/encoders/nil_class.rb index 5343badc9c..8c51dba384 100644 --- a/activesupport/lib/active_support/json/encoders/nil_class.rb +++ b/activesupport/lib/active_support/json/encoders/nil_class.rb @@ -1,6 +1,6 @@ class NilClass private - def rails_to_json(options = nil) + def rails_to_json(*) 'null' end end diff --git a/activesupport/lib/active_support/json/encoders/numeric.rb b/activesupport/lib/active_support/json/encoders/numeric.rb index 42de2f4ea7..c7cd0df1d7 100644 --- a/activesupport/lib/active_support/json/encoders/numeric.rb +++ b/activesupport/lib/active_support/json/encoders/numeric.rb @@ -1,6 +1,6 @@ class Numeric private - def rails_to_json(options = nil) + def rails_to_json(*) to_s end end diff --git a/activesupport/lib/active_support/json/encoders/object.rb b/activesupport/lib/active_support/json/encoders/object.rb index 4722feb7db..9cc12d91ac 100644 --- a/activesupport/lib/active_support/json/encoders/object.rb +++ b/activesupport/lib/active_support/json/encoders/object.rb @@ -3,11 +3,11 @@ require 'active_support/core_ext/object/instance_variables' class Object # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. def to_json(options = nil) - rails_to_json(options) + ActiveSupport::JSON.encode(self, options) end private - def rails_to_json(options = nil) - ActiveSupport::JSON.encode(instance_values, options) + def rails_to_json(*args) + ActiveSupport::JSON.encode(instance_values, *args) end end diff --git a/activesupport/lib/active_support/json/encoders/regexp.rb b/activesupport/lib/active_support/json/encoders/regexp.rb index 62be810be5..ee42db4d02 100644 --- a/activesupport/lib/active_support/json/encoders/regexp.rb +++ b/activesupport/lib/active_support/json/encoders/regexp.rb @@ -1,6 +1,6 @@ class Regexp private - def rails_to_json(options = nil) + def rails_to_json(*) inspect end end diff --git a/activesupport/lib/active_support/json/encoders/string.rb b/activesupport/lib/active_support/json/encoders/string.rb index 6b9dcd97bf..4a6b21c1c0 100644 --- a/activesupport/lib/active_support/json/encoders/string.rb +++ b/activesupport/lib/active_support/json/encoders/string.rb @@ -1,6 +1,6 @@ class String private - def rails_to_json(options = nil) + def rails_to_json(*) ActiveSupport::JSON::Encoding.escape(self) end end diff --git a/activesupport/lib/active_support/json/encoders/symbol.rb b/activesupport/lib/active_support/json/encoders/symbol.rb index 333cf773c1..d575350a4e 100644 --- a/activesupport/lib/active_support/json/encoders/symbol.rb +++ b/activesupport/lib/active_support/json/encoders/symbol.rb @@ -1,6 +1,6 @@ class Symbol private - def rails_to_json(options = nil) - ActiveSupport::JSON.encode(to_s, options) + def rails_to_json(*args) + ActiveSupport::JSON.encode(to_s, *args) end end diff --git a/activesupport/lib/active_support/json/encoders/time.rb b/activesupport/lib/active_support/json/encoders/time.rb index c1cf3398c2..d434b9aace 100644 --- a/activesupport/lib/active_support/json/encoders/time.rb +++ b/activesupport/lib/active_support/json/encoders/time.rb @@ -14,7 +14,7 @@ class Time # # With ActiveSupport.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).to_json # # => "2005/02/01 15:15:10 +0000" - def rails_to_json(options = nil) + def rails_to_json(*) if ActiveSupport.use_standard_json_time_format xmlschema.inspect else diff --git a/activesupport/lib/active_support/json/encoders/true_class.rb b/activesupport/lib/active_support/json/encoders/true_class.rb index 6d5d063254..bc25a6db78 100644 --- a/activesupport/lib/active_support/json/encoders/true_class.rb +++ b/activesupport/lib/active_support/json/encoders/true_class.rb @@ -1,6 +1,6 @@ class TrueClass private - def rails_to_json(options = nil) + def rails_to_json(*) 'true' end end diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index acccb62aea..5441145dfd 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -4,12 +4,13 @@ module ActiveSupport end # Converts a Ruby object into a JSON string. - def self.encode(value, options = nil) - options ||= {} - seen = (options[:seen] ||= []) - raise CircularReferenceError, 'object references itself' if seen.include?(value.object_id) - seen << value.object_id - value.send(:rails_to_json, options) + def self.encode(value, options = nil, seen = nil) + seen ||= [] + if seen.any? { |object| object.equal?(value) } + raise CircularReferenceError, 'object references itself' + end + seen << value + value.send(:rails_to_json, options, seen) ensure seen.pop end diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb index 2c7b449a50..daa7449b71 100644 --- a/activesupport/lib/active_support/json/variable.rb +++ b/activesupport/lib/active_support/json/variable.rb @@ -3,7 +3,7 @@ module ActiveSupport # A string that returns itself as its JSON-encoded form. class Variable < String private - def rails_to_json(options = nil) + def rails_to_json(*) self end end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index c02ee1a524..069842c6c3 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -313,7 +313,7 @@ module ActiveSupport # # With ActiveSupport.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json # # => "2005/02/01 15:15:10 +0000" - def rails_to_json(options = nil) + def rails_to_json(*) if !ActiveSupport.respond_to?(:use_standard_json_time_format) || ActiveSupport.use_standard_json_time_format xmlschema.inspect else -- cgit v1.2.3 From f58c322e7e08003b2bb4d2281b2db1e78930e8ff Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 26 Apr 2009 20:05:17 -0700 Subject: Use __send__ for BasicObject friendliness --- activesupport/lib/active_support/json/encoding.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index 5441145dfd..5fefe5b88b 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -10,7 +10,7 @@ module ActiveSupport raise CircularReferenceError, 'object references itself' end seen << value - value.send(:rails_to_json, options, seen) + value.__send__(:rails_to_json, options, seen) ensure seen.pop end -- cgit v1.2.3 From cecafc52ee0a4a53c903ddbaba95683261f88e5f Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Thu, 23 Apr 2009 15:58:38 -0700 Subject: Refactor ActionView::Template ActionView::Template is now completely independent from template storage, which allows different back ends such as the database. ActionView::Template's only responsibility is to take in the template source (passed in from ActionView::Path), compile it, and render it. --- activesupport/lib/active_support/core_ext/module/delegation.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index fb4b5f0f3c..a44344806d 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -110,8 +110,10 @@ class Module allow_nil = options[:allow_nil] && "#{to} && " + file, line = caller[0].split(":") + methods.each do |method| - module_eval(<<-EOS, "(__DELEGATION__)", 1) + module_eval(<<-EOS, file, line.to_i) def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block) #{allow_nil}#{to}.__send__(#{method.inspect}, *args, &block) # client && client.__send__(:name, *args, &block) end # end -- cgit v1.2.3 From 091965c0fc7384c17cce9e71a80f515b1139d460 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 29 Apr 2009 23:12:34 -0700 Subject: Prefer behavior check to RUBY_VERSION to catch 1.8 backports --- activesupport/lib/active_support/core_ext/integer/even_odd.rb | 4 ++-- activesupport/lib/active_support/core_ext/string/conversions.rb | 2 +- activesupport/lib/active_support/core_ext/time/conversions.rb | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/integer/even_odd.rb b/activesupport/lib/active_support/core_ext/integer/even_odd.rb index 6d005268a3..8f9a97b44c 100644 --- a/activesupport/lib/active_support/core_ext/integer/even_odd.rb +++ b/activesupport/lib/active_support/core_ext/integer/even_odd.rb @@ -7,10 +7,10 @@ class Integer # Is the integer a multiple of 2? def even? multiple_of? 2 - end if RUBY_VERSION < '1.9' + end unless method_defined?(:even?) # Is the integer not a multiple of 2? def odd? !even? - end if RUBY_VERSION < '1.9' + end unless method_defined?(:odd?) end diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 3f05db62c3..2b9f8c70f6 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -5,7 +5,7 @@ class String # 'a'.ord == 'a'[0] for Ruby 1.9 forward compatibility. def ord self[0] - end if RUBY_VERSION < '1.9' + end unless method_defined?(:ord) # Form can be either :utc (default) or :local. def to_time(form = :utc) diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb index 18261e139f..94e01597a9 100644 --- a/activesupport/lib/active_support/core_ext/time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/time/conversions.rb @@ -63,7 +63,7 @@ class Time # your_time.to_date # => Tue, 13 Jan 2009 def to_date ::Date.new(year, month, day) - end + 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+. @@ -80,5 +80,5 @@ class Time # 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 + end unless method_defined?(:to_datetime) end -- cgit v1.2.3 From 79420e71e0e75d6f81e5284184bac4e7d0b02c30 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 30 Apr 2009 01:33:07 -0700 Subject: Work around Float faux precision --- activesupport/test/core_ext/duration_test.rb | 20 ++++++++++---------- activesupport/test/core_ext/time_ext_test.rb | 8 ++++---- activesupport/test/core_ext/time_with_zone_test.rb | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) (limited to 'activesupport') diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index ea6979bc6b..30d4152729 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -42,23 +42,23 @@ class DurationTest < ActiveSupport::TestCase end def test_since_and_ago_with_fractional_days - Time.stubs(:now).returns Time.local(2000) + t = Time.local(2000) # since - assert_equal 36.hours.since, 1.5.days.since - assert_equal((24 * 1.7).hours.since, 1.7.days.since) + assert_equal 36.hours.since(t), 1.5.days.since(t) + assert_in_delta((24 * 1.7).hours.since(t), 1.7.days.since(t), 1) # ago - assert_equal 36.hours.ago, 1.5.days.ago - assert_equal((24 * 1.7).hours.ago, 1.7.days.ago) + assert_equal 36.hours.ago(t), 1.5.days.ago(t) + assert_in_delta((24 * 1.7).hours.ago(t), 1.7.days.ago(t), 1) end def test_since_and_ago_with_fractional_weeks - Time.stubs(:now).returns Time.local(2000) + t = Time.local(2000) # since - assert_equal((7 * 36).hours.since, 1.5.weeks.since) - assert_equal((7 * 24 * 1.7).hours.since, 1.7.weeks.since) + assert_equal((7 * 36).hours.since(t), 1.5.weeks.since(t)) + assert_in_delta((7 * 24 * 1.7).hours.since(t), 1.7.weeks.since(t), 1) # ago - assert_equal((7 * 36).hours.ago, 1.5.weeks.ago) - assert_equal((7 * 24 * 1.7).hours.ago, 1.7.weeks.ago) + assert_equal((7 * 36).hours.ago(t), 1.5.weeks.ago(t)) + 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 diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 3bf7b789ce..e265423f06 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -424,10 +424,10 @@ class TimeExtCalculationsTest < Test::Unit::TestCase assert_equal Time.local(2005,6,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:months => 4) assert_equal Time.local(2005,3,21,15,15,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3) assert_equal Time.local(2005,3,25,3,15,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.5) - assert_equal Time.local(2005,3,26,12,51,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.7) + assert_in_delta Time.local(2005,3,26,12,51,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.7), 1 assert_equal Time.local(2005,3,5,15,15,10), Time.local(2005,2,28,15,15,10).advance(:days => 5) assert_equal Time.local(2005,3,6,3,15,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.5) - assert_equal Time.local(2005,3,6,8,3,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.7) + assert_in_delta Time.local(2005,3,6,8,3,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.7), 1 assert_equal Time.local(2012,9,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 7) assert_equal Time.local(2013,10,3,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5) assert_equal Time.local(2013,10,17,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5) @@ -446,10 +446,10 @@ class TimeExtCalculationsTest < Test::Unit::TestCase assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:months => 4) assert_equal Time.utc(2005,3,21,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3) assert_equal Time.utc(2005,3,25,3,15,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.5) - assert_equal Time.utc(2005,3,26,12,51,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.7) + assert_in_delta Time.utc(2005,3,26,12,51,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.7), 1 assert_equal Time.utc(2005,3,5,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5) assert_equal Time.utc(2005,3,6,3,15,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.5) - assert_equal Time.utc(2005,3,6,8,3,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.7) + assert_in_delta Time.utc(2005,3,6,8,3,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.7), 1 assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 7, :months => 7) assert_equal Time.utc(2013,10,3,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 7, :months => 19, :days => 11) assert_equal Time.utc(2013,10,17,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5) diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 0380c28c17..03ae70d420 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -92,7 +92,7 @@ class TimeWithZoneTest < Test::Unit::TestCase end def test_xmlschema_with_fractional_seconds - @twz += 0.123456 # advance the time by a fraction of a second + @twz += 0.1234560001 # advance the time by a fraction of a second assert_equal "1999-12-31T19:00:00.123-05:00", @twz.xmlschema(3) assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(6) assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(12) -- cgit v1.2.3 From 34509777fd375e5bc529f21ca66cf63263c2cf64 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Mon, 27 Apr 2009 18:16:55 -0700 Subject: Makes new callbacks support keys with special characters --- activesupport/lib/active_support/new_callbacks.rb | 1 + activesupport/test/new_callbacks_test.rb | 28 +++++++++++++++++++++++ 2 files changed, 29 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 7a48dbac04..8a91e1c674 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -356,6 +356,7 @@ module ActiveSupport str = <<-RUBY_EVAL def _run_#{symbol}_callbacks(key = nil) if key + key = key.hash.to_s.gsub(/-/, '_') name = "_run__\#{self.class.name.split("::").last}__#{symbol}__\#{key}__callbacks" if respond_to?(name) diff --git a/activesupport/test/new_callbacks_test.rb b/activesupport/test/new_callbacks_test.rb index abe7790ebf..8c887e1bf1 100644 --- a/activesupport/test/new_callbacks_test.rb +++ b/activesupport/test/new_callbacks_test.rb @@ -255,6 +255,26 @@ module NewCallbacksTest end end + class HyphenatedCallbacks + include ActiveSupport::NewCallbacks + define_callbacks :save + attr_reader :stuff + + save_callback :before, :omg, :per_key => {:if => :yes} + + def yes() true end + + def omg + @stuff = "OMG" + end + + def save + _run_save_callbacks("hyphen-ated") do + @stuff + end + end + end + class AroundCallbacksTest < Test::Unit::TestCase def test_save_around around = AroundPerson.new @@ -381,4 +401,12 @@ module NewCallbacksTest assert_equal ["first", "second", "third", "second", "first"], terminator.history end end + + class HyphenatedKeyTest < Test::Unit::TestCase + def test_save + obj = HyphenatedCallbacks.new + obj.save + assert_equal obj.stuff, "OMG" + end + end end -- cgit v1.2.3 From 059afb3a3a48106f430a8478072e34a59b4b72d6 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Wed, 29 Apr 2009 11:26:01 -0700 Subject: Removed a stray method_missing in the new callbacks system --- activesupport/lib/active_support/new_callbacks.rb | 9 --------- 1 file changed, 9 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 8a91e1c674..2ae7b006c7 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -304,15 +304,6 @@ module ActiveSupport end end - # This method_missing is supplied to catch callbacks with keys and create - # the appropriate callback for future use. - def method_missing(meth, *args, &blk) - if meth.to_s =~ /_run__([\w:]+)__(\w+)__(\w+)__callbacks/ - return self.class._create_and_run_keyed_callback($1, $2.to_sym, $3.to_sym, self, &blk) - end - super - end - # An Array with a compile method class CallbackChain < Array def initialize(symbol) -- cgit v1.2.3 From eb201e64c0b68aee6d0715d44cf48178204c4133 Mon Sep 17 00:00:00 2001 From: codebrulee Date: Mon, 4 May 2009 12:36:22 -0400 Subject: Fixed Hash#from_xml with keys that are all caps. Signed-off-by: Michael Koziarski --- .../lib/active_support/core_ext/hash/conversions.rb | 2 +- activesupport/test/core_ext/hash_ext_test.rb | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) (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 f9dddec687..fe1f79050c 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -217,7 +217,7 @@ class Hash case params.class.to_s when "Hash" params.inject({}) do |h,(k,v)| - h[k.to_s.underscore.tr("-", "_")] = unrename_keys(v) + h[k.to_s.tr("-", "_")] = unrename_keys(v) h end when "Array" diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index d65a5323bf..ece5466abb 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -646,6 +646,22 @@ class HashToXmlTest < Test::Unit::TestCase assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["rsp"]["photos"]["photo"] end + def test_all_caps_key_from_xml + test_xml = <<-EOT + + Lorem Ipsum + + EOT + + expected_hash = { + "ABC3XYZ" => { + "TEST" => "Lorem Ipsum" + } + } + + assert_equal expected_hash, Hash.from_xml(test_xml) + end + def test_empty_array_from_xml blog_xml = <<-XML -- cgit v1.2.3 From 783deae99a4850f597135146b19e7ee4622da94e Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 7 May 2009 10:03:39 -0500 Subject: Add test coverage to module setup extensions --- activesupport/test/core_ext/module/setup_test.rb | 74 ++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 activesupport/test/core_ext/module/setup_test.rb (limited to 'activesupport') diff --git a/activesupport/test/core_ext/module/setup_test.rb b/activesupport/test/core_ext/module/setup_test.rb new file mode 100644 index 0000000000..132790f2ff --- /dev/null +++ b/activesupport/test/core_ext/module/setup_test.rb @@ -0,0 +1,74 @@ +require 'abstract_unit' +require 'active_support/core/time' +require 'active_support/core_ext/module/setup' + +class SetupTest < Test::Unit::TestCase + module Baz + module ClassMethods + def baz + "baz" + end + + def setup=(value) + @@setup = value + end + + def setup + @@setup + end + end + + setup do + self.setup = true + end + + def baz + "baz" + end + end + + module Bar + depends_on Baz + + def bar + "bar" + end + + def baz + "bar+" + super + end + end + + def setup + @klass = Class.new + end + + def test_module_is_included_normally + @klass.use(Baz) + assert_equal "baz", @klass.new.baz + assert_equal SetupTest::Baz, @klass.included_modules[0] + + @klass.use(Baz) + assert_equal "baz", @klass.new.baz + assert_equal SetupTest::Baz, @klass.included_modules[0] + end + + def test_class_methods_are_extended + @klass.use(Baz) + assert_equal "baz", @klass.baz + assert_equal SetupTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] + end + + def test_setup_block_is_ran + @klass.use(Baz) + assert_equal true, @klass.setup + end + + def test_modules_dependencies_are_met + @klass.use(Bar) + assert_equal "bar", @klass.new.bar + assert_equal "bar+baz", @klass.new.baz + assert_equal "baz", @klass.baz + assert_equal [SetupTest::Bar, SetupTest::Baz], @klass.included_modules[0..1] + end +end -- cgit v1.2.3 From 2854535b02bcee3668bda02c76c3105fc24730d3 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 7 May 2009 10:29:22 -0500 Subject: Make module dependency DSL opt in --- activesupport/lib/active_support.rb | 1 + .../lib/active_support/core_ext/module.rb | 1 - .../lib/active_support/core_ext/module/setup.rb | 26 -------- .../lib/active_support/dependency_module.rb | 24 +++++++ activesupport/test/core_ext/module/setup_test.rb | 74 --------------------- activesupport/test/dependency_module_test.rb | 77 ++++++++++++++++++++++ 6 files changed, 102 insertions(+), 101 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/module/setup.rb create mode 100644 activesupport/lib/active_support/dependency_module.rb delete mode 100644 activesupport/test/core_ext/module/setup_test.rb create mode 100644 activesupport/test/dependency_module_test.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 0879535487..dab017770d 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -34,6 +34,7 @@ module ActiveSupport autoload :Callbacks, 'active_support/callbacks' autoload :NewCallbacks, 'active_support/new_callbacks' autoload :ConcurrentHash, 'active_support/concurrent_hash' + autoload :DependencyModule, 'active_support/dependency_module' autoload :Deprecation, 'active_support/deprecation' autoload :Gzip, 'active_support/gzip' autoload :Inflector, 'active_support/inflector' diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb index fee91534e7..215c47b114 100644 --- a/activesupport/lib/active_support/core_ext/module.rb +++ b/activesupport/lib/active_support/core_ext/module.rb @@ -9,4 +9,3 @@ require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/module/loading' require 'active_support/core_ext/module/model_naming' require 'active_support/core_ext/module/synchronization' -require 'active_support/core_ext/module/setup' diff --git a/activesupport/lib/active_support/core_ext/module/setup.rb b/activesupport/lib/active_support/core_ext/module/setup.rb deleted file mode 100644 index e6dfd0cf56..0000000000 --- a/activesupport/lib/active_support/core_ext/module/setup.rb +++ /dev/null @@ -1,26 +0,0 @@ -class Module - attr_accessor :_setup_block - attr_accessor :_dependencies - - def setup(&blk) - @_setup_block = blk - end - - def use(mod) - return if self < mod - - (mod._dependencies || []).each do |dep| - use dep - end - # raise "Circular dependencies" if self < mod - include mod - extend mod.const_get("ClassMethods") if mod.const_defined?("ClassMethods") - class_eval(&mod._setup_block) if mod._setup_block - end - - def depends_on(mod) - return if self < mod - @_dependencies ||= [] - @_dependencies << mod - end -end \ No newline at end of file diff --git a/activesupport/lib/active_support/dependency_module.rb b/activesupport/lib/active_support/dependency_module.rb new file mode 100644 index 0000000000..0e1cc67b53 --- /dev/null +++ b/activesupport/lib/active_support/dependency_module.rb @@ -0,0 +1,24 @@ +module ActiveSupport + module DependencyModule + def setup(&blk) + @_setup_block = blk + end + + def append_features(base) + return if base < self + (@_dependencies ||= []).each { |dep| base.send(:include, dep) } + super + end + + def included(base) + base.extend const_get("ClassMethods") if const_defined?("ClassMethods") + base.class_eval(&@_setup_block) if instance_variable_defined?("@_setup_block") + end + + def depends_on(mod) + return if self < mod + @_dependencies ||= [] + @_dependencies << mod + end + end +end diff --git a/activesupport/test/core_ext/module/setup_test.rb b/activesupport/test/core_ext/module/setup_test.rb deleted file mode 100644 index 132790f2ff..0000000000 --- a/activesupport/test/core_ext/module/setup_test.rb +++ /dev/null @@ -1,74 +0,0 @@ -require 'abstract_unit' -require 'active_support/core/time' -require 'active_support/core_ext/module/setup' - -class SetupTest < Test::Unit::TestCase - module Baz - module ClassMethods - def baz - "baz" - end - - def setup=(value) - @@setup = value - end - - def setup - @@setup - end - end - - setup do - self.setup = true - end - - def baz - "baz" - end - end - - module Bar - depends_on Baz - - def bar - "bar" - end - - def baz - "bar+" + super - end - end - - def setup - @klass = Class.new - end - - def test_module_is_included_normally - @klass.use(Baz) - assert_equal "baz", @klass.new.baz - assert_equal SetupTest::Baz, @klass.included_modules[0] - - @klass.use(Baz) - assert_equal "baz", @klass.new.baz - assert_equal SetupTest::Baz, @klass.included_modules[0] - end - - def test_class_methods_are_extended - @klass.use(Baz) - assert_equal "baz", @klass.baz - assert_equal SetupTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] - end - - def test_setup_block_is_ran - @klass.use(Baz) - assert_equal true, @klass.setup - end - - def test_modules_dependencies_are_met - @klass.use(Bar) - assert_equal "bar", @klass.new.bar - assert_equal "bar+baz", @klass.new.baz - assert_equal "baz", @klass.baz - assert_equal [SetupTest::Bar, SetupTest::Baz], @klass.included_modules[0..1] - end -end diff --git a/activesupport/test/dependency_module_test.rb b/activesupport/test/dependency_module_test.rb new file mode 100644 index 0000000000..d611b4056c --- /dev/null +++ b/activesupport/test/dependency_module_test.rb @@ -0,0 +1,77 @@ +require 'abstract_unit' +require 'active_support/dependency_module' + +class DependencyModuleTest < Test::Unit::TestCase + module Baz + extend ActiveSupport::DependencyModule + + module ClassMethods + def baz + "baz" + end + + def setup=(value) + @@setup = value + end + + def setup + @@setup + end + end + + setup do + self.setup = true + end + + def baz + "baz" + end + end + + module Bar + extend ActiveSupport::DependencyModule + + depends_on Baz + + def bar + "bar" + end + + def baz + "bar+" + super + end + end + + def setup + @klass = Class.new + end + + def test_module_is_included_normally + @klass.send(:include, Baz) + assert_equal "baz", @klass.new.baz + assert_equal DependencyModuleTest::Baz, @klass.included_modules[0] + + @klass.send(:include, Baz) + assert_equal "baz", @klass.new.baz + assert_equal DependencyModuleTest::Baz, @klass.included_modules[0] + end + + def test_class_methods_are_extended + @klass.send(:include, Baz) + assert_equal "baz", @klass.baz + assert_equal DependencyModuleTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] + end + + def test_setup_block_is_ran + @klass.send(:include, Baz) + assert_equal true, @klass.setup + end + + def test_modules_dependencies_are_met + @klass.send(:include, Bar) + assert_equal "bar", @klass.new.bar + assert_equal "bar+baz", @klass.new.baz + assert_equal "baz", @klass.baz + assert_equal [DependencyModuleTest::Bar, DependencyModuleTest::Baz], @klass.included_modules[0..1] + end +end -- cgit v1.2.3 From af40fa6d036d86895e7be4ef46a615d44eb41ede Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 7 May 2009 10:38:57 -0500 Subject: Prefer "included" language over "setup" --- activesupport/lib/active_support/dependency_module.rb | 14 +++++++------- activesupport/test/dependency_module_test.rb | 16 ++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/dependency_module.rb b/activesupport/lib/active_support/dependency_module.rb index 0e1cc67b53..c690b49a2b 100644 --- a/activesupport/lib/active_support/dependency_module.rb +++ b/activesupport/lib/active_support/dependency_module.rb @@ -1,18 +1,18 @@ module ActiveSupport module DependencyModule - def setup(&blk) - @_setup_block = blk - end - def append_features(base) return if base < self (@_dependencies ||= []).each { |dep| base.send(:include, dep) } super end - def included(base) - base.extend const_get("ClassMethods") if const_defined?("ClassMethods") - base.class_eval(&@_setup_block) if instance_variable_defined?("@_setup_block") + def included(base = nil, &block) + if base.nil? && block_given? + @_included_block = block + else + base.extend const_get("ClassMethods") if const_defined?("ClassMethods") + base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block") + end end def depends_on(mod) diff --git a/activesupport/test/dependency_module_test.rb b/activesupport/test/dependency_module_test.rb index d611b4056c..07090d15a1 100644 --- a/activesupport/test/dependency_module_test.rb +++ b/activesupport/test/dependency_module_test.rb @@ -10,17 +10,17 @@ class DependencyModuleTest < Test::Unit::TestCase "baz" end - def setup=(value) - @@setup = value + def included_ran=(value) + @@included_ran = value end - def setup - @@setup + def included_ran + @@included_ran end end - setup do - self.setup = true + included do + self.included_ran = true end def baz @@ -62,9 +62,9 @@ class DependencyModuleTest < Test::Unit::TestCase assert_equal DependencyModuleTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] end - def test_setup_block_is_ran + def test_included_block_is_ran @klass.send(:include, Baz) - assert_equal true, @klass.setup + assert_equal true, @klass.included_ran end def test_modules_dependencies_are_met -- cgit v1.2.3 From 4817bf94d135c44ddfae1a30acb15de989e3c86c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 7 May 2009 18:39:03 -0700 Subject: Check for date/time methods that moved upstream in 1.9 --- activesupport/lib/active_support/core_ext/date/calculations.rb | 4 ++-- activesupport/lib/active_support/core_ext/date_time/conversions.rb | 6 +++--- activesupport/lib/active_support/core_ext/time/conversions.rb | 2 +- 3 files changed, 6 insertions(+), 6 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 04a32edefd..1fe4ffb8e1 100644 --- a/activesupport/lib/active_support/core_ext/date/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date/calculations.rb @@ -132,7 +132,7 @@ class Date # Short-hand for years_since(1) def next_year years_since(1) - end + end unless method_defined?(:next_year) # Short-hand for months_ago(1) def last_month @@ -142,7 +142,7 @@ class Date # Short-hand for months_since(1) def next_month months_since(1) - end + end unless method_defined?(:next_month) # Returns a new Date/DateTime representing the "start" of this week (i.e, Monday; DateTime objects will have time set to 0:00) def beginning_of_week 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 ddfa8d610d..5f01bc4fd6 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -58,7 +58,7 @@ class DateTime # Converts self to a Ruby Date object; time portion is discarded def to_date ::Date.new(year, month, day) - end + end unless method_defined?(:to_date) # 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 @@ -69,12 +69,12 @@ class DateTime # To be able to keep Times, Dates and DateTimes interchangeable on conversions def to_datetime self - end + end unless method_defined?(:to_datetime) # Converts datetime to an appropriate format for use in XML def xmlschema strftime("%Y-%m-%dT%H:%M:%S%Z") - end if RUBY_VERSION < '1.9' + end unless method_defined?(:xmlschema) # Converts self to a floating-point number of seconds since the Unix epoch def to_f diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb index 94e01597a9..6d9c080442 100644 --- a/activesupport/lib/active_support/core_ext/time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/time/conversions.rb @@ -69,7 +69,7 @@ class Time # In this case, it simply returns +self+. def to_time self - end + end unless method_defined?(:to_time) # Converts a Time instance to a Ruby DateTime instance, preserving UTC offset. # -- cgit v1.2.3 From 9e0cfdb7f951c0446cdfd3b2cc26443712fe657a Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Sat, 9 May 2009 18:35:31 -0400 Subject: ActiveSupport::OrderedHash#to_a method returns an ordered set of arrays. Matches ruby1.9's Hash#to_a. Signed-off-by: Michael Koziarski [#2629 state:committed] --- activesupport/lib/active_support/ordered_hash.rb | 4 ++++ activesupport/test/ordered_hash_test.rb | 4 ++++ 2 files changed, 8 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index fed8094a24..33fd2a29b9 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -57,6 +57,10 @@ module ActiveSupport self end + def to_a + @keys.map { |key| [ key, self[key] ] } + end + def each_key @keys.each { |key| yield key } end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 7cd8c8a8f4..6fccbbdc41 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -51,6 +51,10 @@ class OrderedHashTest < Test::Unit::TestCase assert_same @ordered_hash, @ordered_hash.to_hash end + def test_to_a + assert_equal @keys.zip(@values), @ordered_hash.to_a + end + def test_has_key assert_equal true, @ordered_hash.has_key?('blue') assert_equal true, @ordered_hash.key?('blue') -- cgit v1.2.3 From 2e7409f035236c719c5b1567c4bb3e65a5e543bc Mon Sep 17 00:00:00 2001 From: Alexander Dymo Date: Thu, 7 May 2009 03:19:17 +0300 Subject: Change spelling of Kyev timezone to Kyiv [#2613 state:resolved] --- activesupport/CHANGELOG | 2 ++ activesupport/lib/active_support/values/time_zone.rb | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index ca5ab13a46..032f0fb9c1 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *Edge* +* Change spelling of Kyev timezone to Kyiv #2613 [Alexander Dymo] + * Add ActiveSupport.parse_json_times to disable time parsing in JSON backends that don't support it or don't need it. [rick] * Add pluggable JSON backends with support for the JSON gem. [rick] diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index e2d759aa50..b37dae1c2a 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -92,7 +92,7 @@ module ActiveSupport "Bucharest" => "Europe/Bucharest", "Cairo" => "Africa/Cairo", "Helsinki" => "Europe/Helsinki", - "Kyev" => "Europe/Kiev", + "Kyiv" => "Europe/Kiev", "Riga" => "Europe/Riga", "Sofia" => "Europe/Sofia", "Tallinn" => "Europe/Tallinn", @@ -336,7 +336,7 @@ module ActiveSupport "Copenhagen", "Madrid", "Paris", "Amsterdam", "Berlin", "Bern", "Rome", "Stockholm", "Vienna", "West Central Africa" ], - [ 7_200, "Bucharest", "Cairo", "Helsinki", "Kyev", "Riga", "Sofia", + [ 7_200, "Bucharest", "Cairo", "Helsinki", "Kyiv", "Riga", "Sofia", "Tallinn", "Vilnius", "Athens", "Istanbul", "Minsk", "Jerusalem", "Harare", "Pretoria" ], [ 10_800, "Moscow", "St. Petersburg", "Volgograd", "Kuwait", "Riyadh", -- cgit v1.2.3 From e1854e0b199fba352ddcaa58a3af168e8cc70e3a Mon Sep 17 00:00:00 2001 From: Douglas F Shearer Date: Thu, 7 May 2009 23:58:07 +0100 Subject: ActiveSupport::OrderedHash[1,2,3,4] creates an OrderedHash instead of a Hash. [#2615 state:committed] Signed-off-by: Jeremy Kemper --- activesupport/lib/active_support/ordered_hash.rb | 10 ++++++++++ activesupport/test/ordered_hash_test.rb | 6 ++++++ 2 files changed, 16 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 33fd2a29b9..8d1c0f5160 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -10,6 +10,16 @@ module ActiveSupport @keys = [] end + def self.[](*args) + ordered_hash = new + args.each_with_index { |val,ind| + # Only every second value is a key. + next if ind % 2 != 0 + ordered_hash[val] = args[ind + 1] + } + ordered_hash + end + def initialize_copy(other) super # make a deep copy of keys diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 6fccbbdc41..647938dd87 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -162,4 +162,10 @@ class OrderedHashTest < Test::Unit::TestCase def test_inspect assert @ordered_hash.inspect.include?(@hash.inspect) end + + def test_alternate_initialization + alternate = ActiveSupport::OrderedHash[1,2,3,4] + assert_kind_of ActiveSupport::OrderedHash, alternate + assert_equal [1, 3], alternate.keys + end end -- cgit v1.2.3 From c1d120a71e74aa3ccab6dc28a5406b87a51a69c1 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Mon, 11 May 2009 11:48:38 -0700 Subject: Don't run the action if callbacks are halted. In AbstractController, this means that response_body is not empty --- activesupport/lib/active_support/new_callbacks.rb | 2 +- activesupport/test/new_callbacks_test.rb | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 2ae7b006c7..9316d6d2b6 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -316,7 +316,7 @@ module ActiveSupport each do |callback| method << callback.start(key, options) end - method << "yield self if block_given?" + method << "yield self if block_given? && !halted" reverse_each do |callback| method << callback.end(key, options) end diff --git a/activesupport/test/new_callbacks_test.rb b/activesupport/test/new_callbacks_test.rb index 8c887e1bf1..dec6106ac1 100644 --- a/activesupport/test/new_callbacks_test.rb +++ b/activesupport/test/new_callbacks_test.rb @@ -365,7 +365,7 @@ module NewCallbacksTest save_callback :after, :third - attr_reader :history + attr_reader :history, :saved def initialize @history = [] end @@ -390,7 +390,9 @@ module NewCallbacksTest end def save - _run_save_callbacks + _run_save_callbacks do + @saved = true + end end end @@ -400,6 +402,12 @@ module NewCallbacksTest terminator.save assert_equal ["first", "second", "third", "second", "first"], terminator.history end + + def test_block_never_called_if_terminated + obj = CallbackTerminator.new + obj.save + assert !obj.saved + end end class HyphenatedKeyTest < Test::Unit::TestCase @@ -407,6 +415,6 @@ module NewCallbacksTest obj = HyphenatedCallbacks.new obj.save assert_equal obj.stuff, "OMG" - end + end end end -- cgit v1.2.3 From e8550ee0329586b32de425e905c7af7e65bc78a8 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 13 May 2009 01:10:37 -0700 Subject: Cherry-pick core extensions --- activesupport/Rakefile | 2 +- activesupport/lib/active_support/core_ext/object/conversions.rb | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/Rakefile b/activesupport/Rakefile index a4e8200a43..c3ea09d424 100644 --- a/activesupport/Rakefile +++ b/activesupport/Rakefile @@ -22,8 +22,8 @@ Rake::TestTask.new { |t| t.warning = true } task :isolated_test do + ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) Dir['test/**/*_test.rb'].all? do |file| - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) system(ruby, '-Ilib:test', file) end or raise "Failures" end diff --git a/activesupport/lib/active_support/core_ext/object/conversions.rb b/activesupport/lib/active_support/core_ext/object/conversions.rb index 278b856c45..638f0decc1 100644 --- a/activesupport/lib/active_support/core_ext/object/conversions.rb +++ b/activesupport/lib/active_support/core_ext/object/conversions.rb @@ -1,3 +1,6 @@ +require 'active_support/core_ext/array/conversions' +require 'active_support/core_ext/hash/conversions' + class Object # Alias of to_s. def to_param -- cgit v1.2.3 From 5dd29c466c38a1bc395da579fd4b22c5e5a8e9fd Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 13 May 2009 16:15:37 -0700 Subject: Cherry-picking Active Support extensions --- activesupport/lib/active_support/memoizable.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb index edf626802a..fa6db683d4 100644 --- a/activesupport/lib/active_support/memoizable.rb +++ b/activesupport/lib/active_support/memoizable.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/module/aliasing' module ActiveSupport module SafelyMemoizable -- cgit v1.2.3 From 53dda29f8b34073a4b135ee224c1d09c1f10de02 Mon Sep 17 00:00:00 2001 From: Brian Lopez Date: Sun, 17 May 2009 10:37:30 -0500 Subject: Add support for parsing XML and JSON from an IO as well as a string [#2659 state:resolved] Signed-off-by: Joshua Peek --- .../lib/active_support/json/backends/jsongem.rb | 5 ++++- activesupport/lib/active_support/json/backends/yaml.rb | 5 ++++- activesupport/lib/active_support/xml_mini/jdom.rb | 16 ++++++++++------ activesupport/lib/active_support/xml_mini/libxml.rb | 16 ++++++++++------ activesupport/lib/active_support/xml_mini/nokogiri.rb | 16 ++++++++++------ activesupport/lib/active_support/xml_mini/rexml.rb | 14 +++++++++----- activesupport/test/xml_mini/nokogiri_engine_test.rb | 13 +++++++++++++ activesupport/test/xml_mini/rexml_engine_test.rb | 14 ++++++++++++++ 8 files changed, 74 insertions(+), 25 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 de847e30a3..d1a1cdd7d7 100644 --- a/activesupport/lib/active_support/json/backends/jsongem.rb +++ b/activesupport/lib/active_support/json/backends/jsongem.rb @@ -6,8 +6,11 @@ module ActiveSupport module JSONGem extend self - # Converts a JSON string into a Ruby object. + # Parses a JSON string or IO and convert it into an object def decode(json) + if json.respond_to?(:read) + json = json.read + end data = ::JSON.parse(json) if ActiveSupport.parse_json_times convert_dates_from(data) diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index c7db508c23..1c18fc4801 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -9,8 +9,11 @@ module ActiveSupport module Yaml extend self - # Converts a JSON string into a Ruby object. + # 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 => e raise ParseError, "Invalid JSON string" diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb index d795d55690..1cd714d864 100644 --- a/activesupport/lib/active_support/xml_mini/jdom.rb +++ b/activesupport/lib/active_support/xml_mini/jdom.rb @@ -24,15 +24,19 @@ module ActiveSupport node_type_map = {} NODE_TYPE_NAMES.each { |type| node_type_map[Node.send(type)] = type } - # Parse an XML Document string into a simple hash using Java's jdom. - # string:: - # XML Document string to parse - def parse(string) - if string.blank? + # Parse an XML Document string or IO into a simple hash using Java's jdom. + # data:: + # XML Document string or IO to parse + def parse(data) + if data.respond_to?(:read) + data = data.read + end + + if data.blank? {} else @dbf = DocumentBuilderFactory.new_instance - xml_string_reader = StringReader.new(string) + xml_string_reader = StringReader.new(data) xml_input_source = InputSource.new(xml_string_reader) doc = @dbf.new_document_builder.parse(xml_input_source) merge_element!({}, doc.document_element) diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb index 370205409a..d4c4dc7be5 100644 --- a/activesupport/lib/active_support/xml_mini/libxml.rb +++ b/activesupport/lib/active_support/xml_mini/libxml.rb @@ -5,16 +5,20 @@ module ActiveSupport module XmlMini_LibXML #:nodoc: extend self - # Parse an XML Document string into a simple hash using libxml. - # string:: - # XML Document string to parse - def parse(string) + # Parse an XML Document string or IO into a simple hash using libxml. + # data:: + # XML Document string or IO to parse + def parse(data) + if data.respond_to?(:read) + data = data.read + end + LibXML::XML.default_keep_blanks = false - if string.blank? + if data.blank? {} else - LibXML::XML::Parser.string(string.strip).parse.to_hash + LibXML::XML::Parser.string(data.strip).parse.to_hash end end diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb index 8f9676e4f6..7337c143c9 100644 --- a/activesupport/lib/active_support/xml_mini/nokogiri.rb +++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb @@ -5,14 +5,18 @@ module ActiveSupport module XmlMini_Nokogiri #:nodoc: extend self - # Parse an XML Document string into a simple hash using libxml / nokogiri. - # string:: - # XML Document string to parse - def parse(string) - if string.blank? + # Parse an XML Document string or IO into a simple hash using libxml / nokogiri. + # data:: + # XML Document string or IO to parse + def parse(data) + if data.respond_to?(:read) + data = data.read + end + + if data.blank? {} else - doc = Nokogiri::XML(string) + doc = Nokogiri::XML(data) raise doc.errors.first if doc.errors.length > 0 doc.to_hash end diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb index 5033210aae..1184d2d6c9 100644 --- a/activesupport/lib/active_support/xml_mini/rexml.rb +++ b/activesupport/lib/active_support/xml_mini/rexml.rb @@ -7,16 +7,20 @@ module ActiveSupport CONTENT_KEY = '__content__'.freeze - # Parse an XML Document string into a simple hash + # Parse an XML Document string or IO into a simple hash # # Same as XmlSimple::xml_in but doesn't shoot itself in the foot, # and uses the defaults from ActiveSupport # - # string:: - # XML Document string to parse - def parse(string) + # data:: + # XML Document string or IO to parse + def parse(data) + if data.respond_to?(:read) + data = data.read + end + require 'rexml/document' unless defined?(REXML::Document) - doc = REXML::Document.new(string) + doc = REXML::Document.new(data) merge_element!({}, doc.root) end diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb index 886a9d1aba..7c3a591e63 100644 --- a/activesupport/test/xml_mini/nokogiri_engine_test.rb +++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb @@ -148,6 +148,19 @@ class NokogiriEngineTest < Test::Unit::TestCase eoxml end + def test_parse_from_io + io = StringIO.new(<<-eoxml) + + good + + hello everyone + + morning + + eoxml + XmlMini.parse(io) + end + private def assert_equal_rexml(xml) hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb index a412d8ca05..57bb35254a 100644 --- a/activesupport/test/xml_mini/rexml_engine_test.rb +++ b/activesupport/test/xml_mini/rexml_engine_test.rb @@ -12,4 +12,18 @@ class REXMLEngineTest < Test::Unit::TestCase XmlMini.backend = 'REXML' assert_equal XmlMini_REXML, XmlMini.backend end + + def test_parse_from_io + XmlMini.backend = 'REXML' + io = StringIO.new(<<-eoxml) + + good + + hello everyone + + morning + + eoxml + XmlMini.parse(io) + end end -- cgit v1.2.3 From e89241c92fbcf68b59d9efb50c21c5040e9f3156 Mon Sep 17 00:00:00 2001 From: rick Date: Sun, 17 May 2009 19:16:11 -0700 Subject: load the JSON Backend lazily. If the JSON gem is already loaded, use the JSONGem backend by default. --- activesupport/lib/active_support/json.rb | 11 ++++++++--- activesupport/lib/active_support/json/backends/jsongem.rb | 4 +++- activesupport/lib/active_support/json/backends/yaml.rb | 4 +++- activesupport/test/json/decoding_test.rb | 3 +++ 4 files changed, 17 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index 5072992cdf..1e8ded12da 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -40,9 +40,15 @@ module ActiveSupport end class << self - attr_reader :backend delegate :decode, :to => :backend - + + def backend + @backend || begin + self.backend = defined?(::JSON) ? "JSONGem" : "Yaml" + @backend + end + end + def backend=(name) if name.is_a?(Module) @backend = name @@ -77,6 +83,5 @@ module ActiveSupport end ActiveSupport.escape_html_entities_in_json = true -ActiveSupport::JSON.backend = 'Yaml' require 'active_support/json/encoding' diff --git a/activesupport/lib/active_support/json/backends/jsongem.rb b/activesupport/lib/active_support/json/backends/jsongem.rb index d1a1cdd7d7..649e6301d1 100644 --- a/activesupport/lib/active_support/json/backends/jsongem.rb +++ b/activesupport/lib/active_support/json/backends/jsongem.rb @@ -1,6 +1,8 @@ +require 'json' unless defined?(JSON) + module ActiveSupport module JSON - ParseError = ::JSON::ParserError + ParseError = ::JSON::ParserError unless const_defined?(:ParseError) module Backends module JSONGem diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index 1c18fc4801..667016f45d 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -2,7 +2,9 @@ require 'active_support/core_ext/string/starts_ends_with' module ActiveSupport module JSON - class ParseError < StandardError + unless const_defined?(:ParseError) + class ParseError < StandardError + end end module Backends diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 7e1bfcca84..09fd0d09ba 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -36,6 +36,9 @@ class TestJSONDecoding < ActiveSupport::TestCase %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => {'b' => ["","",""]} } + # load the default JSON backend + ActiveSupport::JSON.backend + backends = %w(Yaml) begin gem 'json', '>= 1.1' -- cgit v1.2.3 From 29550cc91f8dcbfe3e4020986d719c77ddd2f14d Mon Sep 17 00:00:00 2001 From: Joe Van Dyk Date: Mon, 2 Feb 2009 16:43:14 -0800 Subject: Add ability to get multiple memcached keys at the same time (via MemCacheStore#read_multi). Signed-off-by: Jeremy Kemper --- activesupport/lib/active_support/cache/mem_cache_store.rb | 5 +++++ activesupport/memcached_get_multi.diff | 0 activesupport/test/caching_test.rb | 9 +++++++++ 3 files changed, 14 insertions(+) create mode 100644 activesupport/memcached_get_multi.diff (limited to 'activesupport') diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index 4d8e1fdd67..90b7526fe1 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -43,6 +43,11 @@ module ActiveSupport extend Strategy::LocalCache end + # Reads multiple keys from the cache. + def read_multi(*keys) + @data.get_multi keys + end + def read(key, options = nil) # :nodoc: super @data.get(key, raw?(options)) diff --git a/activesupport/memcached_get_multi.diff b/activesupport/memcached_get_multi.diff new file mode 100644 index 0000000000..e69de29bb2 diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index 8bb0c155cf..b845796fe5 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -251,6 +251,15 @@ uses_memcached 'memcached backed store' do end end + def test_multi_get + @cache.with_local_cache do + @cache.write('foo', 1) + @cache.write('goo', 2) + result = @cache.read_multi('foo', 'goo') + assert_equal({'foo' => 1, 'goo' => 2}, result) + end + end + def test_middleware app = lambda { |env| result = @cache.write('foo', 'bar') -- cgit v1.2.3 From 41e9414b60e8d042bacf2f8d61d7efc07111417a Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 18 May 2009 15:01:13 -0700 Subject: Include acts_as_string? --- activesupport/lib/active_support/multibyte/chars.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index 60f082bcc1..96ed35f0e0 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -1,4 +1,5 @@ # encoding: utf-8 +require 'active_support/core_ext/string/behavior' module ActiveSupport #:nodoc: module Multibyte #:nodoc: -- cgit v1.2.3 From e2ed1a1ca4f2dbfb9eb2c31fd1ddd45562afef25 Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Tue, 19 May 2009 10:24:26 -0400 Subject: Allow MemCacheStore to be initialized with a MemCache object instead of addresses and options --- activesupport/CHANGELOG | 2 ++ .../lib/active_support/cache/mem_cache_store.rb | 17 +++++++++++------ activesupport/test/caching_test.rb | 14 ++++++++++---- 3 files changed, 23 insertions(+), 10 deletions(-) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 032f0fb9c1..6551be01f9 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *Edge* +* Allow MemCacheStore to be initialized with a MemCache object instead of addresses and options [Bryan Helmkamp] + * Change spelling of Kyev timezone to Kyiv #2613 [Alexander Dymo] * Add ActiveSupport.parse_json_times to disable time parsing in JSON backends that don't support it or don't need it. [rick] diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index 90b7526fe1..ab8eb72096 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -23,7 +23,12 @@ module ActiveSupport DELETED = "DELETED\r\n" end - attr_reader :addresses + def self.build_mem_cache(*addresses) + addresses = addresses.flatten + options = addresses.extract_options! + addresses = ["localhost"] if addresses.empty? + MemCache.new(addresses, options) + end # Creates a new MemCacheStore object, with the given memcached server # addresses. Each address is either a host name, or a host-with-port string @@ -34,11 +39,11 @@ module ActiveSupport # If no addresses are specified, then MemCacheStore will connect to # localhost port 11211 (the default memcached port). def initialize(*addresses) - addresses = addresses.flatten - options = addresses.extract_options! - addresses = ["localhost"] if addresses.empty? - @addresses = addresses - @data = MemCache.new(addresses, options) + if addresses.first.is_a?(MemCache) + @data = addresses.first + else + @data = self.class.build_mem_cache(*addresses) + end extend Strategy::LocalCache end diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index b845796fe5..ad19dcfd09 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -15,22 +15,28 @@ class CacheStoreSettingTest < ActiveSupport::TestCase end def test_mem_cache_fragment_cache_store + MemCache.expects(:new).with(%w[localhost], {}) store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost" assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) - assert_equal %w(localhost), store.addresses + end + + def test_mem_cache_fragment_cache_store_with_given_mem_cache + mem_cache = MemCache.new + MemCache.expects(:new).never + store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache + assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) end def test_mem_cache_fragment_cache_store_with_multiple_servers + MemCache.expects(:new).with(%w[localhost 192.168.1.1], {}) store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1' assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) - assert_equal %w(localhost 192.168.1.1), store.addresses end def test_mem_cache_fragment_cache_store_with_options + MemCache.expects(:new).with(%w[localhost 192.168.1.1], { :namespace => "foo" }) store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1', :namespace => 'foo' assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) - assert_equal %w(localhost 192.168.1.1), store.addresses - assert_equal 'foo', store.instance_variable_get('@data').instance_variable_get('@namespace') end def test_object_assigned_fragment_cache_store -- cgit v1.2.3 From 36058f45040b5559fd8f6a44a17ead27a6b3d2f7 Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Tue, 19 May 2009 19:51:38 -0400 Subject: Use duck typing to also allow MemCache-like object when initializing a MemCacheStore Signed-off-by: Jeremy Kemper --- activesupport/CHANGELOG | 2 +- activesupport/lib/active_support/cache/mem_cache_store.rb | 2 +- activesupport/test/caching_test.rb | 6 ++++++ 3 files changed, 8 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 6551be01f9..27d26b2ba5 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,6 +1,6 @@ *Edge* -* Allow MemCacheStore to be initialized with a MemCache object instead of addresses and options [Bryan Helmkamp] +* Allow MemCacheStore to be initialized with a MemCache-like object instead of addresses and options [Bryan Helmkamp] * Change spelling of Kyev timezone to Kyiv #2613 [Alexander Dymo] diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index ab8eb72096..38b3409ca6 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -39,7 +39,7 @@ module ActiveSupport # If no addresses are specified, then MemCacheStore will connect to # localhost port 11211 (the default memcached port). def initialize(*addresses) - if addresses.first.is_a?(MemCache) + if addresses.first.respond_to?(:get) @data = addresses.first else @data = self.class.build_mem_cache(*addresses) diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index ad19dcfd09..bd237a5c8e 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -27,6 +27,12 @@ class CacheStoreSettingTest < ActiveSupport::TestCase assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) end + def test_mem_cache_fragment_cache_store_with_given_mem_cache_like_object + MemCache.expects(:new).never + store = ActiveSupport::Cache.lookup_store :mem_cache_store, stub("memcache", :get => true) + assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) + end + def test_mem_cache_fragment_cache_store_with_multiple_servers MemCache.expects(:new).with(%w[localhost 192.168.1.1], {}) store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1' -- cgit v1.2.3 From 67247ca8ee850223193a5fe77f5460aefc0336c0 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Tue, 19 May 2009 17:41:17 -0700 Subject: Corrected new callbacks semantics with regards to using objects for around filters. --- activesupport/lib/active_support/new_callbacks.rb | 10 ++-- activesupport/test/new_callbacks_test.rb | 62 +++++++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 9316d6d2b6..f8108780f1 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -296,9 +296,13 @@ module ActiveSupport method_name else kind, name = @kind, @name - @klass.send(:define_method, method_name) do - filter.send("#{kind}_#{name}", self) - end + @klass.send(:define_method, "#{method_name}_object") { filter } + + @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def #{method_name}(&blk) + #{method_name}_object.send("#{kind}_#{name}", self, &blk) + end + RUBY_EVAL method_name end end diff --git a/activesupport/test/new_callbacks_test.rb b/activesupport/test/new_callbacks_test.rb index dec6106ac1..7bec47224d 100644 --- a/activesupport/test/new_callbacks_test.rb +++ b/activesupport/test/new_callbacks_test.rb @@ -396,6 +396,68 @@ module NewCallbacksTest end end + class CallbackObject + def before_save(caller) + caller.record << "before" + end + + def around_save(caller) + caller.record << "around before" + yield + caller.record << "around after" + end + end + + class UsingObjectBefore + include ActiveSupport::NewCallbacks + + define_callbacks :save + save_callback :before, CallbackObject.new + + attr_accessor :record + def initialize + @record = [] + end + + def save + _run_save_callbacks do + @record << "yielded" + end + end + end + + class UsingObjectAround + include ActiveSupport::NewCallbacks + + define_callbacks :save + save_callback :around, CallbackObject.new + + attr_accessor :record + def initialize + @record = [] + end + + def save + _run_save_callbacks do + @record << "yielded" + end + end + end + + class UsingObjectTest < Test::Unit::TestCase + def test_before_object + u = UsingObjectBefore.new + u.save + assert_equal ["before", "yielded"], u.record + end + + def test_around_object + u = UsingObjectAround.new + u.save + assert_equal ["around before", "yielded", "around after"], u.record + end + end + class CallbackTerminatorTest < Test::Unit::TestCase def test_termination terminator = CallbackTerminator.new -- cgit v1.2.3 From c4a6109286909c394e8c5bfc471a1eb9de245d2b Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Wed, 20 May 2009 16:52:56 -0700 Subject: Got controller/mime_responds_test.rb running on the new base --- activesupport/lib/active_support/test_case.rb | 5 +++++ activesupport/lib/active_support/testing/pending.rb | 5 +++++ 2 files changed, 10 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index 50e25ef740..bab2a401eb 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -32,6 +32,11 @@ module ActiveSupport include ActiveSupport::Testing::Default end + $tags = {} + def self.for_tag(tag) + yield if $tags[tag] + end + include ActiveSupport::Testing::SetupAndTeardown include ActiveSupport::Testing::Assertions include ActiveSupport::Testing::Deprecation diff --git a/activesupport/lib/active_support/testing/pending.rb b/activesupport/lib/active_support/testing/pending.rb index d945c7e476..21134ff9e2 100644 --- a/activesupport/lib/active_support/testing/pending.rb +++ b/activesupport/lib/active_support/testing/pending.rb @@ -11,6 +11,11 @@ module ActiveSupport @@at_exit = false def pending(description = "", &block) + if description.is_a?(Symbol) + is_pending = $tags[description] + return block.call unless is_pending + end + if block_given? failed = false -- cgit v1.2.3 From 5a036457620b7fb22027dc4f0c399871db6ed0c3 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Thu, 21 May 2009 03:04:17 +0200 Subject: Allow Module#depends_on to accept multiple modules --- activesupport/lib/active_support/dependency_module.rb | 10 ++++++---- activesupport/test/dependency_module_test.rb | 11 +++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/dependency_module.rb b/activesupport/lib/active_support/dependency_module.rb index 8c202acc8f..9872b9654b 100644 --- a/activesupport/lib/active_support/dependency_module.rb +++ b/activesupport/lib/active_support/dependency_module.rb @@ -16,10 +16,12 @@ module ActiveSupport end end - def depends_on(mod) - return if self < mod - @_dependencies ||= [] - @_dependencies << mod + def depends_on(*mods) + mods.each do |mod| + next if self < mod + @_dependencies ||= [] + @_dependencies << mod + end end end end diff --git a/activesupport/test/dependency_module_test.rb b/activesupport/test/dependency_module_test.rb index 07090d15a1..be7db0fa7b 100644 --- a/activesupport/test/dependency_module_test.rb +++ b/activesupport/test/dependency_module_test.rb @@ -42,6 +42,12 @@ class DependencyModuleTest < Test::Unit::TestCase end end + module Foo + extend ActiveSupport::DependencyModule + + depends_on Bar, Baz + end + def setup @klass = Class.new end @@ -74,4 +80,9 @@ class DependencyModuleTest < Test::Unit::TestCase assert_equal "baz", @klass.baz assert_equal [DependencyModuleTest::Bar, DependencyModuleTest::Baz], @klass.included_modules[0..1] end + + def test_depends_on_with_multiple_modules + @klass.send(:include, Foo) + assert_equal [DependencyModuleTest::Foo, DependencyModuleTest::Bar, DependencyModuleTest::Baz], @klass.included_modules[0..2] + end end -- cgit v1.2.3 From 429a00f225b24b938575ed40d11fa07987e12a6f Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 16:41:20 -0700 Subject: Remove bad add --- activesupport/memcached_get_multi.diff | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 activesupport/memcached_get_multi.diff (limited to 'activesupport') diff --git a/activesupport/memcached_get_multi.diff b/activesupport/memcached_get_multi.diff deleted file mode 100644 index e69de29bb2..0000000000 -- cgit v1.2.3 From 68398838544a778244e6028f2c30deb7313ea0b2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 16:49:21 -0700 Subject: Break up misc Object extensions --- .../lib/active_support/core_ext/object/misc.rb | 83 +--------------------- .../active_support/core_ext/object/returning.rb | 42 +++++++++++ .../lib/active_support/core_ext/object/tap.rb | 16 +++++ .../active_support/core_ext/object/with_options.rb | 24 +++++++ 4 files changed, 85 insertions(+), 80 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/object/returning.rb create mode 100644 activesupport/lib/active_support/core_ext/object/tap.rb create mode 100644 activesupport/lib/active_support/core_ext/object/with_options.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index fb1bcdb98f..80011dfbed 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -1,80 +1,3 @@ -class Object - # Returns +value+ after yielding +value+ to the block. This simplifies the - # process of constructing an object, performing work on the object, and then - # returning the object from a method. It is a Ruby-ized realization of the K - # combinator, courtesy of Mikael Brockman. - # - # ==== Examples - # - # # Without returning - # def foo - # values = [] - # values << "bar" - # values << "baz" - # return values - # end - # - # foo # => ['bar', 'baz'] - # - # # returning with a local variable - # def foo - # returning values = [] do - # values << 'bar' - # values << 'baz' - # end - # end - # - # foo # => ['bar', 'baz'] - # - # # returning with a block argument - # def foo - # returning [] do |values| - # values << 'bar' - # values << 'baz' - # end - # end - # - # foo # => ['bar', 'baz'] - def returning(value) - yield(value) - value - end - - # Yields x to the block, and then returns x. - # The primary purpose of this method is to "tap into" a method chain, - # in order to perform operations on intermediate results within the chain. - # - # (1..10).tap { |x| puts "original: #{x.inspect}" }.to_a. - # tap { |x| puts "array: #{x.inspect}" }. - # select { |x| x%2 == 0 }. - # tap { |x| puts "evens: #{x.inspect}" }. - # map { |x| x*x }. - # tap { |x| puts "squares: #{x.inspect}" } - def tap - yield self - self - end unless Object.respond_to?(:tap) - - # An elegant way to factor duplication out of options passed to a series of - # method calls. Each method called in the block, with the block variable as - # the receiver, will have its options merged with the default +options+ hash - # 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 - # end - # - # Can also be used with an explicit receiver: - # - # map.with_options :controller => "people" do |people| - # people.connect "/people", :action => "index" - # people.connect "/people/:id", :action => "show" - # end - # - def with_options(options) - yield ActiveSupport::OptionMerger.new(self, options) - end -end +require 'active_support/core_ext/object/returning' +require 'active_support/core_ext/object/tap' +require 'active_support/core_ext/object/with_options' diff --git a/activesupport/lib/active_support/core_ext/object/returning.rb b/activesupport/lib/active_support/core_ext/object/returning.rb new file mode 100644 index 0000000000..0dc2e1266a --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/returning.rb @@ -0,0 +1,42 @@ +class Object + # Returns +value+ after yielding +value+ to the block. This simplifies the + # process of constructing an object, performing work on the object, and then + # returning the object from a method. It is a Ruby-ized realization of the K + # combinator, courtesy of Mikael Brockman. + # + # ==== Examples + # + # # Without returning + # def foo + # values = [] + # values << "bar" + # values << "baz" + # return values + # end + # + # foo # => ['bar', 'baz'] + # + # # returning with a local variable + # def foo + # returning values = [] do + # values << 'bar' + # values << 'baz' + # end + # end + # + # foo # => ['bar', 'baz'] + # + # # returning with a block argument + # def foo + # returning [] do |values| + # values << 'bar' + # values << 'baz' + # end + # end + # + # foo # => ['bar', 'baz'] + def returning(value) + yield(value) + value + end +end diff --git a/activesupport/lib/active_support/core_ext/object/tap.rb b/activesupport/lib/active_support/core_ext/object/tap.rb new file mode 100644 index 0000000000..db7e715e2d --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/tap.rb @@ -0,0 +1,16 @@ +class Object + # Yields x to the block, and then returns x. + # The primary purpose of this method is to "tap into" a method chain, + # in order to perform operations on intermediate results within the chain. + # + # (1..10).tap { |x| puts "original: #{x.inspect}" }.to_a. + # tap { |x| puts "array: #{x.inspect}" }. + # select { |x| x%2 == 0 }. + # tap { |x| puts "evens: #{x.inspect}" }. + # map { |x| x*x }. + # tap { |x| puts "squares: #{x.inspect}" } + def tap + yield self + self + end unless Object.respond_to?(:tap) +end diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb new file mode 100644 index 0000000000..dd38b7d261 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/with_options.rb @@ -0,0 +1,24 @@ +class Object + # An elegant way to factor duplication out of options passed to a series of + # method calls. Each method called in the block, with the block variable as + # the receiver, will have its options merged with the default +options+ hash + # 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 + # end + # + # Can also be used with an explicit receiver: + # + # map.with_options :controller => "people" do |people| + # people.connect "/people", :action => "index" + # people.connect "/people/:id", :action => "show" + # end + # + def with_options(options) + yield ActiveSupport::OptionMerger.new(self, options) + end +end -- cgit v1.2.3 From 3694227f24d0f220c0ce7ef6c7f51598e2715d2d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 17:10:10 -0700 Subject: Break out Symbol#to_proc as a future-ruby extension --- activesupport/lib/active_support/core_ext/symbol.rb | 15 +-------------- .../lib/active_support/core_ext/symbol/to_proc.rb | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 14 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/symbol/to_proc.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/symbol.rb b/activesupport/lib/active_support/core_ext/symbol.rb index 520369452b..c103cd9dcf 100644 --- a/activesupport/lib/active_support/core_ext/symbol.rb +++ b/activesupport/lib/active_support/core_ext/symbol.rb @@ -1,14 +1 @@ -class Symbol - # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples: - # - # # The same as people.collect { |p| p.name } - # people.collect(&:name) - # - # # The same as people.select { |p| p.manager? }.collect { |p| p.salary } - # people.select(&:manager?).collect(&:salary) - # - # This is a builtin method in Ruby 1.8.7 and later. - def to_proc - Proc.new { |*args| args.shift.__send__(self, *args) } - end unless :to_proc.respond_to?(:to_proc) -end +require 'active_support/core_ext/symbol/to_proc' diff --git a/activesupport/lib/active_support/core_ext/symbol/to_proc.rb b/activesupport/lib/active_support/core_ext/symbol/to_proc.rb new file mode 100644 index 0000000000..520369452b --- /dev/null +++ b/activesupport/lib/active_support/core_ext/symbol/to_proc.rb @@ -0,0 +1,14 @@ +class Symbol + # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples: + # + # # The same as people.collect { |p| p.name } + # people.collect(&:name) + # + # # The same as people.select { |p| p.manager? }.collect { |p| p.salary } + # people.select(&:manager?).collect(&:salary) + # + # This is a builtin method in Ruby 1.8.7 and later. + def to_proc + Proc.new { |*args| args.shift.__send__(self, *args) } + end unless :to_proc.respond_to?(:to_proc) +end -- cgit v1.2.3 From 5f222c524ed00b2ac805e267f70a916cf8f9bc77 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 17:11:41 -0700 Subject: Remove 'core' fluff. Hookable ActiveSupport.load_all! --- activesupport/lib/active_support.rb | 11 +++++++++-- activesupport/lib/active_support/all.rb | 3 +++ activesupport/lib/active_support/core.rb | 7 ------- activesupport/lib/active_support/core/all.rb | 5 ----- activesupport/lib/active_support/core/time.rb | 4 ---- activesupport/lib/active_support/core/time/autoload.rb | 5 ----- .../lib/active_support/core_ext/hash/conversions.rb | 3 +-- activesupport/lib/active_support/time.rb | 14 ++++++++++++++ activesupport/lib/active_support/time/autoload.rb | 5 +++++ activesupport/test/core_ext/duration_test.rb | 2 +- activesupport/test/core_ext/numeric_ext_test.rb | 2 +- activesupport/test/core_ext/object_and_class_ext_test.rb | 2 +- activesupport/test/core_ext/time_ext_test.rb | 2 +- activesupport/test/i18n_test.rb | 2 +- activesupport/test/time_zone_test.rb | 2 +- 15 files changed, 38 insertions(+), 31 deletions(-) create mode 100644 activesupport/lib/active_support/all.rb delete mode 100644 activesupport/lib/active_support/core.rb delete mode 100644 activesupport/lib/active_support/core/all.rb delete mode 100644 activesupport/lib/active_support/core/time.rb delete mode 100644 activesupport/lib/active_support/core/time/autoload.rb create mode 100644 activesupport/lib/active_support/time.rb create mode 100644 activesupport/lib/active_support/time/autoload.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index dab017770d..a1a140bc33 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -22,8 +22,15 @@ #++ module ActiveSupport - def self.load_all! - [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom] + Core.load_all! + class << self + attr_accessor :load_all_hooks + def on_load_all(&hook) load_all_hooks << hook end + def load_all!; load_all_hooks.each { |hook| hook.call } end + end + self.load_all_hooks = [] + + on_load_all do + [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom] end autoload :BacktraceCleaner, 'active_support/backtrace_cleaner' diff --git a/activesupport/lib/active_support/all.rb b/activesupport/lib/active_support/all.rb new file mode 100644 index 0000000000..f537818300 --- /dev/null +++ b/activesupport/lib/active_support/all.rb @@ -0,0 +1,3 @@ +require 'active_support' +require 'active_support/time' +require 'active_support/core_ext' diff --git a/activesupport/lib/active_support/core.rb b/activesupport/lib/active_support/core.rb deleted file mode 100644 index ad8db94941..0000000000 --- a/activesupport/lib/active_support/core.rb +++ /dev/null @@ -1,7 +0,0 @@ -module ActiveSupport - module Core - def self.load_all! - [TimeWithZone] - end - end -end diff --git a/activesupport/lib/active_support/core/all.rb b/activesupport/lib/active_support/core/all.rb deleted file mode 100644 index 55e8b4cfac..0000000000 --- a/activesupport/lib/active_support/core/all.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'active_support/core_ext' -require 'active_support/core' -Dir["#{File.dirname(__FILE__)}/*.rb"].sort.each do |path| - require "active_support/core/#{File.basename(path, '.rb')}" -end diff --git a/activesupport/lib/active_support/core/time.rb b/activesupport/lib/active_support/core/time.rb deleted file mode 100644 index 43e13b5e58..0000000000 --- a/activesupport/lib/active_support/core/time.rb +++ /dev/null @@ -1,4 +0,0 @@ -require 'active_support/core/time/autoload' -require 'active_support/core_ext/time' -require 'active_support/core_ext/date' -require 'active_support/core_ext/date_time' diff --git a/activesupport/lib/active_support/core/time/autoload.rb b/activesupport/lib/active_support/core/time/autoload.rb deleted file mode 100644 index c9a7731b39..0000000000 --- a/activesupport/lib/active_support/core/time/autoload.rb +++ /dev/null @@ -1,5 +0,0 @@ -module ActiveSupport - autoload :Duration, 'active_support/duration' - autoload :TimeWithZone, 'active_support/time_with_zone' - autoload :TimeZone, 'active_support/values/time_zone' -end diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index fe1f79050c..2a34874d08 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -1,8 +1,7 @@ -require 'date' +require 'active_support/time' require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/array/conversions' require 'active_support/core_ext/hash/reverse_merge' -require 'active_support/core/time' class Hash # This module exists to decorate files deserialized using Hash.from_xml with diff --git a/activesupport/lib/active_support/time.rb b/activesupport/lib/active_support/time.rb new file mode 100644 index 0000000000..d36a683601 --- /dev/null +++ b/activesupport/lib/active_support/time.rb @@ -0,0 +1,14 @@ +require 'active_support' +require 'active_support/core_ext/time' +require 'active_support/core_ext/date' +require 'active_support/core_ext/date_time' + +module ActiveSupport + autoload :Duration, 'active_support/duration' + autoload :TimeWithZone, 'active_support/time_with_zone' + autoload :TimeZone, 'active_support/values/time_zone' + + on_load_all do + [Duration, TimeWithZone, TimeZone] + end +end diff --git a/activesupport/lib/active_support/time/autoload.rb b/activesupport/lib/active_support/time/autoload.rb new file mode 100644 index 0000000000..c9a7731b39 --- /dev/null +++ b/activesupport/lib/active_support/time/autoload.rb @@ -0,0 +1,5 @@ +module ActiveSupport + autoload :Duration, 'active_support/duration' + autoload :TimeWithZone, 'active_support/time_with_zone' + autoload :TimeZone, 'active_support/values/time_zone' +end diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index 30d4152729..6f16621ae5 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require 'active_support/core/time' +require 'active_support/time' class DurationTest < ActiveSupport::TestCase def test_inspect diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb index 74b086fa9c..992ec60302 100644 --- a/activesupport/test/core_ext/numeric_ext_test.rb +++ b/activesupport/test/core_ext/numeric_ext_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' +require 'active_support/time' require 'active_support/core_ext/numeric' require 'active_support/core_ext/integer' -require 'active_support/core/time' class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase def setup 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 8869b053e6..f0121b862d 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' +require 'active_support/time' require 'active_support/core_ext/object' require 'active_support/core_ext/class/removal' -require 'active_support/core/time' class ClassA; end class ClassB < ClassA; end diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index e265423f06..1c2d0fbce4 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require 'active_support/core/time' +require 'active_support/time' class TimeExtCalculationsTest < Test::Unit::TestCase def test_seconds_since_midnight diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb index 2a08abfb3e..9868f1e87d 100644 --- a/activesupport/test/i18n_test.rb +++ b/activesupport/test/i18n_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require 'active_support/core/time' +require 'active_support/time' require 'active_support/core_ext/array/conversions' class I18nTest < Test::Unit::TestCase diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb index 87d6ccc30d..99c4310854 100644 --- a/activesupport/test/time_zone_test.rb +++ b/activesupport/test/time_zone_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require 'active_support/core/time' +require 'active_support/time' class TimeZoneTest < Test::Unit::TestCase def test_utc_to_local -- cgit v1.2.3 From 886aa2f0e1a1a95a5b518d918fefaa526755ad34 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 17:58:35 -0700 Subject: Extract autoloads --- activesupport/lib/active_support.rb | 25 +------------------------ activesupport/lib/active_support/autoload.rb | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 24 deletions(-) create mode 100644 activesupport/lib/active_support/autoload.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index a1a140bc33..a20635ba62 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -32,32 +32,9 @@ module ActiveSupport on_load_all do [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom] end - - autoload :BacktraceCleaner, 'active_support/backtrace_cleaner' - autoload :Base64, 'active_support/base64' - autoload :BasicObject, 'active_support/basic_object' - autoload :BufferedLogger, 'active_support/buffered_logger' - autoload :Cache, 'active_support/cache' - autoload :Callbacks, 'active_support/callbacks' - autoload :NewCallbacks, 'active_support/new_callbacks' - autoload :ConcurrentHash, 'active_support/concurrent_hash' - autoload :DependencyModule, 'active_support/dependency_module' - autoload :Deprecation, 'active_support/deprecation' - autoload :Gzip, 'active_support/gzip' - autoload :Inflector, 'active_support/inflector' - autoload :Memoizable, 'active_support/memoizable' - autoload :MessageEncryptor, 'active_support/message_encryptor' - autoload :MessageVerifier, 'active_support/message_verifier' - autoload :Multibyte, 'active_support/multibyte' - autoload :OptionMerger, 'active_support/option_merger' - autoload :OrderedHash, 'active_support/ordered_hash' - autoload :OrderedOptions, 'active_support/ordered_options' - autoload :Rescuable, 'active_support/rescuable' - autoload :SecureRandom, 'active_support/secure_random' - autoload :StringInquirer, 'active_support/string_inquirer' - autoload :XmlMini, 'active_support/xml_mini' end +require 'active_support/autoload' require 'active_support/vendor' I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml" diff --git a/activesupport/lib/active_support/autoload.rb b/activesupport/lib/active_support/autoload.rb new file mode 100644 index 0000000000..ed229d1c5f --- /dev/null +++ b/activesupport/lib/active_support/autoload.rb @@ -0,0 +1,25 @@ +module ActiveSupport + autoload :BacktraceCleaner, 'active_support/backtrace_cleaner' + autoload :Base64, 'active_support/base64' + autoload :BasicObject, 'active_support/basic_object' + autoload :BufferedLogger, 'active_support/buffered_logger' + autoload :Cache, 'active_support/cache' + autoload :Callbacks, 'active_support/callbacks' + autoload :NewCallbacks, 'active_support/new_callbacks' + autoload :ConcurrentHash, 'active_support/concurrent_hash' + autoload :DependencyModule, 'active_support/dependency_module' + autoload :Deprecation, 'active_support/deprecation' + autoload :Gzip, 'active_support/gzip' + autoload :Inflector, 'active_support/inflector' + autoload :Memoizable, 'active_support/memoizable' + autoload :MessageEncryptor, 'active_support/message_encryptor' + autoload :MessageVerifier, 'active_support/message_verifier' + autoload :Multibyte, 'active_support/multibyte' + autoload :OptionMerger, 'active_support/option_merger' + autoload :OrderedHash, 'active_support/ordered_hash' + autoload :OrderedOptions, 'active_support/ordered_options' + autoload :Rescuable, 'active_support/rescuable' + autoload :SecureRandom, 'active_support/secure_random' + autoload :StringInquirer, 'active_support/string_inquirer' + autoload :XmlMini, 'active_support/xml_mini' +end -- cgit v1.2.3 From 428829fc38d06be63082e261d59f478a4b7dd354 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 17:59:34 -0700 Subject: Single-require forward compatibility with new Ruby features like Object#tap, Enumerable#group_by, and Process.daemon. Code with the latest but run anywhere. --- activesupport/lib/active_support/ruby/shim.rb | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 activesupport/lib/active_support/ruby/shim.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb new file mode 100644 index 0000000000..37c57c485a --- /dev/null +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -0,0 +1,24 @@ +# Backported Ruby builtins so you can code with the latest & greatest +# but still run on any Ruby 1.8.x. +# +# Date next_year, next_month +# DateTime to_date, to_datetime, xmlschema +# Enumerable group_by, each_with_object, none? +# Integer even?, odd? +# Object tap +# Process Process.daemon +# REXML security fix +# String ord +# Symbol to_proc +# Time to_date, to_time, to_datetime +require 'active_support' +require 'active_support/core_ext/date/calculations' +require 'active_support/core_ext/date_time/conversions' +require 'active_support/core_ext/enumerable' +require 'active_support/core_ext/integer/even_odd' +require 'active_support/core_ext/object/tap' +require 'active_support/core_ext/process/daemon' +require 'active_support/core_ext/string/conversions' +require 'active_support/core_ext/rexml' +require 'active_support/core_ext/symbol/to_proc' +require 'active_support/core_ext/time/conversions' -- cgit v1.2.3 From e9a75451236119e1db3e5d7cc7703637d048c7f8 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 20 May 2009 18:11:06 -0700 Subject: Avoid uninitialized instance variable warning --- activesupport/lib/active_support/json.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index 1e8ded12da..6d845182fb 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -43,10 +43,10 @@ module ActiveSupport delegate :decode, :to => :backend def backend - @backend || begin + unless defined? @backend self.backend = defined?(::JSON) ? "JSONGem" : "Yaml" - @backend end + @backend end def backend=(name) -- cgit v1.2.3 From 10085114ce7ec6bc967fa701c49ef218f666efb5 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 25 May 2009 18:05:58 +0200 Subject: Make Filter#filter work with around filters --- activesupport/lib/active_support/new_callbacks.rb | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index f8108780f1..039d0fa658 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -298,11 +298,23 @@ module ActiveSupport kind, name = @kind, @name @klass.send(:define_method, "#{method_name}_object") { filter } - @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 - def #{method_name}(&blk) - #{method_name}_object.send("#{kind}_#{name}", self, &blk) - end - RUBY_EVAL + if kind == :around + @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def #{method_name}(&blk) + if :#{kind} == :around && #{method_name}_object.respond_to?(:filter) + #{method_name}_object.send("filter", self, &blk) + else + #{method_name}_object.send("#{kind}_#{name}", self, &blk) + end + end + RUBY_EVAL + else + @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def #{method_name}(&blk) + #{method_name}_object.send("#{kind}_#{name}", self, &blk) + end + RUBY_EVAL + end method_name end end -- cgit v1.2.3 From 2f59066470193c6219dfd958fc5d8096a2ddee68 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 26 May 2009 13:09:33 +0200 Subject: Support Method callbacks --- activesupport/lib/active_support/new_callbacks.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 039d0fa658..b6cbdbb6b0 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -287,6 +287,14 @@ module ActiveSupport when Proc @klass.send(:define_method, method_name, &filter) method_name << (filter.arity == 1 ? "(self)" : "") + when Method + @klass.send(:define_method, "#{method_name}_method") { filter } + @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def #{method_name}(&blk) + #{method_name}_method.call(self, &blk) + end + RUBY_EVAL + method_name when String @klass.class_eval <<-RUBY_EVAL def #{method_name} -- cgit v1.2.3 From 6ef329d3250cfc3a21184cc2a8248aa18a1f6815 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Wed, 27 May 2009 14:54:58 -0500 Subject: Ensure Memcache local cache returns duplicated values [#2302 state:resolved] --- activesupport/lib/active_support/cache/strategy/local_cache.rb | 2 +- activesupport/test/caching_test.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb index 4bbcd8e4c4..3b5fccc737 100644 --- a/activesupport/lib/active_support/cache/strategy/local_cache.rb +++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb @@ -45,7 +45,7 @@ module ActiveSupport elsif value.nil? value = super local_cache.write(key, value || NULL) if local_cache - value + value.duplicable? ? value.dup : value else # forcing the value to be immutable value.duplicable? ? value.dup : value diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index bd237a5c8e..51d04d9388 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -180,6 +180,15 @@ uses_memcached 'memcached backed store' do end end + def test_stored_objects_should_not_be_frozen + @cache.with_local_cache do + @cache.write('foo', 'bar') + end + @cache.with_local_cache do + assert !@cache.read('foo').frozen? + end + end + def test_write_should_return_true_on_success @cache.with_local_cache do result = @cache.write('foo', 'bar') -- cgit v1.2.3 From a5688fa9073dc8824d98071346e6cd9ae417eb72 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Wed, 27 May 2009 11:02:13 -0700 Subject: Add the ability to prepend filters to new callbacks --- activesupport/lib/active_support/new_callbacks.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index b6cbdbb6b0..e9a30b9c35 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -464,7 +464,9 @@ module ActiveSupport self._#{symbol}_callbacks.delete_if {|c| c.matches?(type, :#{symbol}, filter)} Callback.new(filter, type, options.dup, self, :#{symbol}) end - self._#{symbol}_callbacks.push(*filters) + options[:prepend] ? + self._#{symbol}_callbacks.unshift(*filters) : + self._#{symbol}_callbacks.push(*filters) _define_runner(:#{symbol}, self._#{symbol}_callbacks.compile(nil, :terminator => _#{symbol}_terminator), options) -- cgit v1.2.3 From 2b166d306c7829c8be531cb030515166367cbb20 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Wed, 27 May 2009 16:49:23 -0700 Subject: Added support to new callbacks for around filter object that respond to :before & :after --- activesupport/lib/active_support/new_callbacks.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index e9a30b9c35..5ca6b90b01 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -311,6 +311,11 @@ module ActiveSupport def #{method_name}(&blk) if :#{kind} == :around && #{method_name}_object.respond_to?(:filter) #{method_name}_object.send("filter", self, &blk) + # TODO: Deprecate this + elsif #{method_name}_object.respond_to?(:before) && #{method_name}_object.respond_to?(:after) + #{method_name}_object.before(self) + yield + #{method_name}_object.after(self) else #{method_name}_object.send("#{kind}_#{name}", self, &blk) end -- cgit v1.2.3 From 1e2628431a742e4f67af1d5dc1db8ad6393e8832 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Wed, 27 May 2009 16:50:40 -0700 Subject: Added support to new callbacks for around filter object that respond to :before & :after used in before|after callbacks --- activesupport/lib/active_support/new_callbacks.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 5ca6b90b01..185fb6a6af 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -324,7 +324,11 @@ module ActiveSupport else @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 def #{method_name}(&blk) - #{method_name}_object.send("#{kind}_#{name}", self, &blk) + if #{method_name}_object.respond_to?(:#{kind}) + #{method_name}_object.#{kind}(self, &blk) + else + #{method_name}_object.send("#{kind}_#{name}", self, &blk) + end end RUBY_EVAL end -- cgit v1.2.3 From f2f58f535520bfa77ab2d0ad1fb598f18349dd2e Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Wed, 27 May 2009 17:31:48 -0700 Subject: Fix failing ActionCacheFilter tests due to around filter changes. --- activesupport/lib/active_support/new_callbacks.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/new_callbacks.rb b/activesupport/lib/active_support/new_callbacks.rb index 185fb6a6af..f1d2ea7bb1 100644 --- a/activesupport/lib/active_support/new_callbacks.rb +++ b/activesupport/lib/active_support/new_callbacks.rb @@ -313,8 +313,8 @@ module ActiveSupport #{method_name}_object.send("filter", self, &blk) # TODO: Deprecate this elsif #{method_name}_object.respond_to?(:before) && #{method_name}_object.respond_to?(:after) - #{method_name}_object.before(self) - yield + should_continue = #{method_name}_object.before(self) + yield if should_continue #{method_name}_object.after(self) else #{method_name}_object.send("#{kind}_#{name}", self, &blk) -- cgit v1.2.3 From 4e50a35fa243f6cf7ad567774a9f7c1cb87a1653 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 28 May 2009 11:35:36 -0500 Subject: Break up DependencyModule's dual function of providing a "depend_on" DSL and "included" block DSL into separate modules. But, unify both approaches under AS::Concern. --- activesupport/lib/active_support/autoload.rb | 3 +- activesupport/lib/active_support/concern.rb | 22 ++++++ .../lib/active_support/dependency_module.rb | 12 +-- activesupport/test/concern_test.rb | 88 ++++++++++++++++++++++ activesupport/test/dependency_module_test.rb | 88 ---------------------- 5 files changed, 113 insertions(+), 100 deletions(-) create mode 100644 activesupport/lib/active_support/concern.rb create mode 100644 activesupport/test/concern_test.rb delete mode 100644 activesupport/test/dependency_module_test.rb (limited to 'activesupport') diff --git a/activesupport/lib/active_support/autoload.rb b/activesupport/lib/active_support/autoload.rb index ed229d1c5f..75706855d6 100644 --- a/activesupport/lib/active_support/autoload.rb +++ b/activesupport/lib/active_support/autoload.rb @@ -5,7 +5,7 @@ module ActiveSupport autoload :BufferedLogger, 'active_support/buffered_logger' autoload :Cache, 'active_support/cache' autoload :Callbacks, 'active_support/callbacks' - autoload :NewCallbacks, 'active_support/new_callbacks' + autoload :Concern, 'active_support/concern' autoload :ConcurrentHash, 'active_support/concurrent_hash' autoload :DependencyModule, 'active_support/dependency_module' autoload :Deprecation, 'active_support/deprecation' @@ -15,6 +15,7 @@ module ActiveSupport autoload :MessageEncryptor, 'active_support/message_encryptor' autoload :MessageVerifier, 'active_support/message_verifier' autoload :Multibyte, 'active_support/multibyte' + autoload :NewCallbacks, 'active_support/new_callbacks' autoload :OptionMerger, 'active_support/option_merger' autoload :OrderedHash, 'active_support/ordered_hash' autoload :OrderedOptions, 'active_support/ordered_options' diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb new file mode 100644 index 0000000000..154f8807f7 --- /dev/null +++ b/activesupport/lib/active_support/concern.rb @@ -0,0 +1,22 @@ +require 'active_support/dependency_module' + +module ActiveSupport + module Concern + include DependencyModule + + def append_features(base) + if super + base.extend const_get("ClassMethods") if const_defined?("ClassMethods") + base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block") + end + end + + def included(base = nil, &block) + if base.nil? + @_included_block = block + else + super + end + end + end +end diff --git a/activesupport/lib/active_support/dependency_module.rb b/activesupport/lib/active_support/dependency_module.rb index 9872b9654b..6847c0f86a 100644 --- a/activesupport/lib/active_support/dependency_module.rb +++ b/activesupport/lib/active_support/dependency_module.rb @@ -1,19 +1,9 @@ module ActiveSupport module DependencyModule def append_features(base) - return if base < self + return false if base < self (@_dependencies ||= []).each { |dep| base.send(:include, dep) } super - base.extend const_get("ClassMethods") if const_defined?("ClassMethods") - base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block") - end - - def included(base = nil, &block) - if base.nil? - @_included_block = block - else - super - end end def depends_on(*mods) diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb new file mode 100644 index 0000000000..22f7ec2064 --- /dev/null +++ b/activesupport/test/concern_test.rb @@ -0,0 +1,88 @@ +require 'abstract_unit' +require 'active_support/concern' + +class ConcernTest < Test::Unit::TestCase + module Baz + extend ActiveSupport::Concern + + module ClassMethods + def baz + "baz" + end + + def included_ran=(value) + @@included_ran = value + end + + def included_ran + @@included_ran + end + end + + included do + self.included_ran = true + end + + def baz + "baz" + end + end + + module Bar + extend ActiveSupport::Concern + + depends_on Baz + + def bar + "bar" + end + + def baz + "bar+" + super + end + end + + module Foo + extend ActiveSupport::Concern + + depends_on Bar, Baz + end + + def setup + @klass = Class.new + end + + def test_module_is_included_normally + @klass.send(:include, Baz) + assert_equal "baz", @klass.new.baz + assert_equal ConcernTest::Baz, @klass.included_modules[0] + + @klass.send(:include, Baz) + assert_equal "baz", @klass.new.baz + assert_equal ConcernTest::Baz, @klass.included_modules[0] + end + + def test_class_methods_are_extended + @klass.send(:include, Baz) + assert_equal "baz", @klass.baz + assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] + end + + def test_included_block_is_ran + @klass.send(:include, Baz) + assert_equal true, @klass.included_ran + end + + def test_modules_dependencies_are_met + @klass.send(:include, Bar) + assert_equal "bar", @klass.new.bar + assert_equal "bar+baz", @klass.new.baz + assert_equal "baz", @klass.baz + assert_equal [ConcernTest::Bar, ConcernTest::Baz], @klass.included_modules[0..1] + end + + def test_depends_on_with_multiple_modules + @klass.send(:include, Foo) + assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz], @klass.included_modules[0..2] + end +end diff --git a/activesupport/test/dependency_module_test.rb b/activesupport/test/dependency_module_test.rb deleted file mode 100644 index be7db0fa7b..0000000000 --- a/activesupport/test/dependency_module_test.rb +++ /dev/null @@ -1,88 +0,0 @@ -require 'abstract_unit' -require 'active_support/dependency_module' - -class DependencyModuleTest < Test::Unit::TestCase - module Baz - extend ActiveSupport::DependencyModule - - module ClassMethods - def baz - "baz" - end - - def included_ran=(value) - @@included_ran = value - end - - def included_ran - @@included_ran - end - end - - included do - self.included_ran = true - end - - def baz - "baz" - end - end - - module Bar - extend ActiveSupport::DependencyModule - - depends_on Baz - - def bar - "bar" - end - - def baz - "bar+" + super - end - end - - module Foo - extend ActiveSupport::DependencyModule - - depends_on Bar, Baz - end - - def setup - @klass = Class.new - end - - def test_module_is_included_normally - @klass.send(:include, Baz) - assert_equal "baz", @klass.new.baz - assert_equal DependencyModuleTest::Baz, @klass.included_modules[0] - - @klass.send(:include, Baz) - assert_equal "baz", @klass.new.baz - assert_equal DependencyModuleTest::Baz, @klass.included_modules[0] - end - - def test_class_methods_are_extended - @klass.send(:include, Baz) - assert_equal "baz", @klass.baz - assert_equal DependencyModuleTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] - end - - def test_included_block_is_ran - @klass.send(:include, Baz) - assert_equal true, @klass.included_ran - end - - def test_modules_dependencies_are_met - @klass.send(:include, Bar) - assert_equal "bar", @klass.new.bar - assert_equal "bar+baz", @klass.new.baz - assert_equal "baz", @klass.baz - assert_equal [DependencyModuleTest::Bar, DependencyModuleTest::Baz], @klass.included_modules[0..1] - end - - def test_depends_on_with_multiple_modules - @klass.send(:include, Foo) - assert_equal [DependencyModuleTest::Foo, DependencyModuleTest::Bar, DependencyModuleTest::Baz], @klass.included_modules[0..2] - end -end -- cgit v1.2.3