From 13004c37e658dac960ba3a75cdf90206fc58118e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 1 Nov 2009 13:44:24 +0100 Subject: Give useful test:isolated failures --- activesupport/test/ts_isolated.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activesupport/test/ts_isolated.rb b/activesupport/test/ts_isolated.rb index 9378a13766..cbab61a523 100644 --- a/activesupport/test/ts_isolated.rb +++ b/activesupport/test/ts_isolated.rb @@ -8,8 +8,8 @@ class TestIsolated < Test::Unit::TestCase Dir["#{File.dirname(__FILE__)}/**/*_test.rb"].each do |file| define_method("test #{file}") do command = "#{ruby} -Ilib:test #{file}" - silence_stderr { `#{command}` } - assert_equal 0, $?.to_i, command + result = silence_stderr { `#{command}` } + assert_block("#{command}\n#{result}") { $?.to_i.zero? } end end end -- cgit v1.2.3 From 36121d29a53c71cbdf4f0280718d572f16360f8c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 1 Nov 2009 10:34:16 +0100 Subject: Ruby 1.9 doesn't recognize EM SPACE as whitespace, breaking String#strip --- activesupport/test/multibyte_chars_test.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 680936ded5..0d3c3c7716 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -102,7 +102,13 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase # NEWLINE, SPACE, EM SPACE @whitespace = "\n#{[32, 8195].pack('U*')}" - @whitespace.force_encoding(Encoding::UTF_8) if @whitespace.respond_to?(:force_encoding) + + # Ruby 1.9 doesn't recognize EM SPACE as whitespace! + if @whitespace.respond_to?(:force_encoding) + @whitespace.slice!(2) + @whitespace.force_encoding(Encoding::UTF_8) + end + @byte_order_mark = [65279].pack('U') end -- cgit v1.2.3 From a2de13e1e0de5bba3cbd6050fe4884595704e1e2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 1 Nov 2009 10:38:02 +0100 Subject: Ruby 1.9.2: URI.escape is obsolete --- activesupport/lib/active_support/core_ext/uri.rb | 3 ++- activesupport/test/core_ext/uri_ext_test.rb | 8 ++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/uri.rb b/activesupport/lib/active_support/core_ext/uri.rb index 9a1c61d99b..ca1be8b7e9 100644 --- a/activesupport/lib/active_support/core_ext/uri.rb +++ b/activesupport/lib/active_support/core_ext/uri.rb @@ -4,7 +4,8 @@ if RUBY_VERSION >= '1.9' str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese. str.force_encoding(Encoding::UTF_8) if str.respond_to?(:force_encoding) - unless str == URI.unescape(URI.escape(str)) + parser = URI::Parser.new + unless str == parser.unescape(parser.escape(str)) URI::Parser.class_eval do remove_method :unescape def unescape(str, escaped = @regexp[:ESCAPED]) diff --git a/activesupport/test/core_ext/uri_ext_test.rb b/activesupport/test/core_ext/uri_ext_test.rb index 2d4f38d095..e4a242abc4 100644 --- a/activesupport/test/core_ext/uri_ext_test.rb +++ b/activesupport/test/core_ext/uri_ext_test.rb @@ -7,7 +7,11 @@ class URIExtTest < Test::Unit::TestCase str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese. str.force_encoding(Encoding::UTF_8) if str.respond_to?(:force_encoding) - assert_equal str, URI.unescape(URI.escape(str)) - assert_equal str, URI.decode(URI.escape(str)) + if URI.const_defined?(:Parser) + parser = URI::Parser.new + assert_equal str, parser.unescape(parser.escape(str)) + else + assert_equal str, URI.unescape(URI.escape(str)) + end end end -- cgit v1.2.3 From 8935854375a6c08acd617beaec30f6fd09a29ea0 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 1 Nov 2009 10:49:28 +0100 Subject: Ruby 1.9.2: rational.rb is deprecated --- activesupport/lib/active_support/core_ext/date_time/calculations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb index 41cf020f94..e93abfa4a3 100644 --- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb @@ -1,4 +1,4 @@ -require 'rational' +require 'rational' unless RUBY_VERSION >= '1.9.2' class DateTime class << self -- cgit v1.2.3 From b540eca5889d7a28fac39c9ec0df715aa89487ce Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 1 Nov 2009 11:06:47 +0100 Subject: Consolidate Object#to_param and #to_query core extensions --- actionpack/lib/action_dispatch/routing.rb | 4 +- activeresource/lib/active_resource/base.rb | 1 + activesupport/lib/active_support/cache.rb | 7 +--- .../active_support/core_ext/array/conversions.rb | 16 -------- .../lib/active_support/core_ext/boolean.rb | 1 - .../active_support/core_ext/boolean/conversions.rb | 11 ----- .../active_support/core_ext/hash/conversions.rb | 17 -------- activesupport/lib/active_support/core_ext/nil.rb | 1 - .../lib/active_support/core_ext/nil/conversions.rb | 5 --- .../active_support/core_ext/object/conversions.rb | 18 +-------- .../lib/active_support/core_ext/object/to_param.rb | 47 ++++++++++++++++++++++ .../lib/active_support/core_ext/object/to_query.rb | 27 +++++++++++++ activesupport/test/core_ext/boolean_ext_test.rb | 12 ------ activesupport/test/core_ext/hash_ext_test.rb | 41 ------------------- activesupport/test/core_ext/nil_ext_test.rb | 8 ---- .../test/core_ext/object/to_param_test.rb | 19 +++++++++ .../test/core_ext/object/to_query_test.rb | 43 ++++++++++++++++++++ activesupport/test/core_ext/object_ext_test.rb | 7 ---- 18 files changed, 141 insertions(+), 144 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/boolean.rb delete mode 100644 activesupport/lib/active_support/core_ext/boolean/conversions.rb delete mode 100644 activesupport/lib/active_support/core_ext/nil.rb delete mode 100644 activesupport/lib/active_support/core_ext/nil/conversions.rb create mode 100644 activesupport/lib/active_support/core_ext/object/to_param.rb create mode 100644 activesupport/lib/active_support/core_ext/object/to_query.rb delete mode 100644 activesupport/test/core_ext/boolean_ext_test.rb delete mode 100644 activesupport/test/core_ext/nil_ext_test.rb create mode 100644 activesupport/test/core_ext/object/to_param_test.rb create mode 100644 activesupport/test/core_ext/object/to_query_test.rb diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index b9c377db2c..68ed1e3340 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -1,6 +1,4 @@ -require 'active_support/core_ext/object/conversions' -require 'active_support/core_ext/boolean/conversions' -require 'active_support/core_ext/nil/conversions' +require 'active_support/core_ext/object/to_param' require 'active_support/core_ext/regexp' module ActionDispatch diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index ae627c365d..bd2abdd38e 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -8,6 +8,7 @@ require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/module/aliasing' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/misc' +require 'active_support/core_ext/object/to_query' require 'set' require 'uri' diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 818983fdd6..b91ae65e9f 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -2,12 +2,7 @@ require 'benchmark' require 'active_support/core_ext/benchmark' require 'active_support/core_ext/exception' require 'active_support/core_ext/class/attribute_accessors' - -%w(hash nil string time date date_time array big_decimal range object boolean).each do |library| - require "active_support/core_ext/#{library}/conversions" -end - -# require 'active_support/core_ext' # FIXME: pulling in all to_param extensions +require 'active_support/core_ext/object/to_param' module ActiveSupport # See ActiveSupport::Cache::Store for documentation. diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb index c53cf3f530..db140225e8 100644 --- a/activesupport/lib/active_support/core_ext/array/conversions.rb +++ b/activesupport/lib/active_support/core_ext/array/conversions.rb @@ -40,22 +40,6 @@ class Array end end - - # Calls to_param on all its elements and joins the result with - # slashes. This is used by url_for in Action Pack. - def to_param - collect { |e| e.to_param }.join '/' - end - - # Converts an array into a string suitable for use as a URL query string, - # using the given +key+ as the param name. - # - # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" - def to_query(key) - prefix = "#{key}[]" - collect { |value| value.to_query(prefix) }.join '&' - end - # Converts a collection of elements into a formatted string by calling # to_s on all elements and joining them: # diff --git a/activesupport/lib/active_support/core_ext/boolean.rb b/activesupport/lib/active_support/core_ext/boolean.rb deleted file mode 100644 index be834288f2..0000000000 --- a/activesupport/lib/active_support/core_ext/boolean.rb +++ /dev/null @@ -1 +0,0 @@ -require 'active_support/core_ext/boolean/conversions' \ No newline at end of file diff --git a/activesupport/lib/active_support/core_ext/boolean/conversions.rb b/activesupport/lib/active_support/core_ext/boolean/conversions.rb deleted file mode 100644 index 534ebb7118..0000000000 --- a/activesupport/lib/active_support/core_ext/boolean/conversions.rb +++ /dev/null @@ -1,11 +0,0 @@ -class TrueClass - def to_param - self - end -end - -class FalseClass - def to_param - self - end -end diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index bd9419e1a2..190173f8a0 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -1,6 +1,4 @@ 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' class Hash @@ -68,21 +66,6 @@ class Hash ) end - # Converts a hash into a string suitable for use as a URL query string. An optional namespace can be - # passed to enclose the param names (see example below). - # - # ==== Examples - # { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish" - # - # { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" - def to_query(namespace = nil) - collect do |key, value| - value.to_query(namespace ? "#{namespace}[#{key}]" : key) - end.sort * '&' - end - - alias_method :to_param, :to_query - def to_xml(options = {}) require 'builder' unless defined?(Builder) diff --git a/activesupport/lib/active_support/core_ext/nil.rb b/activesupport/lib/active_support/core_ext/nil.rb deleted file mode 100644 index e9f63c4802..0000000000 --- a/activesupport/lib/active_support/core_ext/nil.rb +++ /dev/null @@ -1 +0,0 @@ -require 'active_support/core_ext/nil/conversions' \ No newline at end of file diff --git a/activesupport/lib/active_support/core_ext/nil/conversions.rb b/activesupport/lib/active_support/core_ext/nil/conversions.rb deleted file mode 100644 index 6ceb500a2a..0000000000 --- a/activesupport/lib/active_support/core_ext/nil/conversions.rb +++ /dev/null @@ -1,5 +0,0 @@ -class NilClass - def to_param - self - end -end diff --git a/activesupport/lib/active_support/core_ext/object/conversions.rb b/activesupport/lib/active_support/core_ext/object/conversions.rb index 638f0decc1..540f7aadb0 100644 --- a/activesupport/lib/active_support/core_ext/object/conversions.rb +++ b/activesupport/lib/active_support/core_ext/object/conversions.rb @@ -1,18 +1,4 @@ +require 'active_support/core_ext/object/to_param' +require 'active_support/core_ext/object/to_query' require 'active_support/core_ext/array/conversions' require 'active_support/core_ext/hash/conversions' - -class Object - # Alias of to_s. - def to_param - to_s - end - - # Converts an object into a string suitable for use as a URL query string, using the given key as the - # param name. - # - # Note: This method is defined as a default implementation for all Objects for Hash#to_query to work. - def to_query(key) - require 'cgi' unless defined?(CGI) && defined?(CGI::escape) - "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" - end -end diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb new file mode 100644 index 0000000000..a5e2260791 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/to_param.rb @@ -0,0 +1,47 @@ +class Object + # Alias of to_s. + def to_param + to_s + end +end + +class NilClass + def to_param + self + end +end + +class TrueClass + def to_param + self + end +end + +class FalseClass + def to_param + self + end +end + +class Array + # Calls to_param on all its elements and joins the result with + # slashes. This is used by url_for in Action Pack. + def to_param + collect { |e| e.to_param }.join '/' + end +end + +class Hash + # Converts a hash into a string suitable for use as a URL query string. An optional namespace can be + # passed to enclose the param names (see example below). + # + # ==== Examples + # { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish" + # + # { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" + def to_param(namespace = nil) + collect do |key, value| + value.to_query(namespace ? "#{namespace}[#{key}]" : key) + end.sort * '&' + end +end diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb new file mode 100644 index 0000000000..3f1540f685 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/to_query.rb @@ -0,0 +1,27 @@ +require 'active_support/core_ext/object/to_param' + +class Object + # Converts an object into a string suitable for use as a URL query string, using the given key as the + # param name. + # + # Note: This method is defined as a default implementation for all Objects for Hash#to_query to work. + def to_query(key) + require 'cgi' unless defined?(CGI) && defined?(CGI::escape) + "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" + end +end + +class Array + # Converts an array into a string suitable for use as a URL query string, + # using the given +key+ as the param name. + # + # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" + def to_query(key) + prefix = "#{key}[]" + collect { |value| value.to_query(prefix) }.join '&' + end +end + +class Hash + alias_method :to_query, :to_param +end diff --git a/activesupport/test/core_ext/boolean_ext_test.rb b/activesupport/test/core_ext/boolean_ext_test.rb deleted file mode 100644 index 9439716efb..0000000000 --- a/activesupport/test/core_ext/boolean_ext_test.rb +++ /dev/null @@ -1,12 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/boolean/conversions' - -class BooleanExtAccessTests < Test::Unit::TestCase - def test_to_param_on_true - assert_equal true, true.to_param - end - - def test_to_param_on_false - assert_equal false, false.to_param - end -end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index eb4c37aaf0..4642bb1330 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -899,42 +899,6 @@ class HashToXmlTest < Test::Unit::TestCase # :builder, etc, shouldn't be added to options assert_equal({:skip_instruct => true}, options) end -end - -class QueryTest < Test::Unit::TestCase - def test_simple_conversion - assert_query_equal 'a=10', :a => 10 - end - - def test_cgi_escaping - assert_query_equal 'a%3Ab=c+d', 'a:b' => 'c d' - end - - def test_nil_parameter_value - empty = Object.new - def empty.to_param; nil end - assert_query_equal 'a=', 'a' => empty - end - - def test_nested_conversion - assert_query_equal 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas', - :person => {:name => 'Nicholas', :login => 'seckar'} - end - - def test_multiple_nested - assert_query_equal 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10', - :person => {:id => 10}, :account => {:person => {:id => 20}} - end - - def test_array_values - assert_query_equal 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20', - :person => {:id => [10, 20]} - end - - def test_array_values_are_not_sorted - assert_query_equal 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10', - :person => {:id => [20, 10]} - end def test_expansion_count_is_limited expected = { @@ -962,9 +926,4 @@ class QueryTest < Test::Unit::TestCase Hash.from_xml(attack_xml) end end - - private - def assert_query_equal(expected, actual, message = nil) - assert_equal expected.split('&'), actual.to_query.split('&') - end end diff --git a/activesupport/test/core_ext/nil_ext_test.rb b/activesupport/test/core_ext/nil_ext_test.rb deleted file mode 100644 index 1062676d65..0000000000 --- a/activesupport/test/core_ext/nil_ext_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/nil/conversions' - -class NilExtAccessTests < Test::Unit::TestCase - def test_to_param - assert_nil nil.to_param - end -end diff --git a/activesupport/test/core_ext/object/to_param_test.rb b/activesupport/test/core_ext/object/to_param_test.rb new file mode 100644 index 0000000000..c3efefddb5 --- /dev/null +++ b/activesupport/test/core_ext/object/to_param_test.rb @@ -0,0 +1,19 @@ +require 'abstract_unit' +require 'active_support/core_ext/object/to_param' + +class ToParamTest < Test::Unit::TestCase + def test_object + foo = Object.new + def foo.to_s; 'foo' end + assert_equal 'foo', foo.to_param + end + + def test_nil + assert_nil nil.to_param + end + + def test_boolean + assert_equal true, true.to_param + assert_equal false, false.to_param + end +end diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb new file mode 100644 index 0000000000..0fb15be654 --- /dev/null +++ b/activesupport/test/core_ext/object/to_query_test.rb @@ -0,0 +1,43 @@ +require 'abstract_unit' +require 'active_support/core_ext/object/to_query' + +class ToQueryTest < Test::Unit::TestCase + def test_simple_conversion + assert_query_equal 'a=10', :a => 10 + end + + def test_cgi_escaping + assert_query_equal 'a%3Ab=c+d', 'a:b' => 'c d' + end + + def test_nil_parameter_value + empty = Object.new + def empty.to_param; nil end + assert_query_equal 'a=', 'a' => empty + end + + def test_nested_conversion + assert_query_equal 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas', + :person => {:name => 'Nicholas', :login => 'seckar'} + end + + def test_multiple_nested + assert_query_equal 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10', + :person => {:id => 10}, :account => {:person => {:id => 20}} + end + + def test_array_values + assert_query_equal 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20', + :person => {:id => [10, 20]} + end + + def test_array_values_are_not_sorted + assert_query_equal 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10', + :person => {:id => [20, 10]} + end + + private + def assert_query_equal(expected, actual, message = nil) + assert_equal expected.split('&'), actual.to_query.split('&') + end +end diff --git a/activesupport/test/core_ext/object_ext_test.rb b/activesupport/test/core_ext/object_ext_test.rb index 484eecaab6..04c19ed2aa 100644 --- a/activesupport/test/core_ext/object_ext_test.rb +++ b/activesupport/test/core_ext/object_ext_test.rb @@ -1,16 +1,9 @@ require 'abstract_unit' require 'active_support/core_ext/object/metaclass' -require 'active_support/core_ext/object/conversions' class ObjectExtTest < Test::Unit::TestCase def test_tap_yields_and_returns_self foo = Object.new assert_equal foo, foo.tap { |x| assert_equal foo, x; :bar } end - - def test_to_param - foo = Object.new - foo.class_eval("def to_s; 'foo'; end") - assert_equal 'foo', foo.to_param - end end -- cgit v1.2.3 From 36a9644b86c53e322a891669cbdd2cf62cd648ac Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 1 Nov 2009 13:43:53 +0100 Subject: Clarify date/time dependencies --- activesupport/lib/active_support/core_ext/date/calculations.rb | 1 + activesupport/lib/active_support/core_ext/date/conversions.rb | 1 + activesupport/lib/active_support/json/encoding.rb | 3 --- activesupport/lib/active_support/time_with_zone.rb | 1 + activesupport/test/caching_test.rb | 6 +++--- railties/lib/rails/application.rb | 1 + 6 files changed, 7 insertions(+), 6 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb index ce3bebc25a..3dd61334d0 100644 --- a/activesupport/lib/active_support/core_ext/date/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date/calculations.rb @@ -1,4 +1,5 @@ require 'active_support/duration' +require 'active_support/core_ext/time/zones' class Date class << self diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb index 54facf4430..b41ad5b686 100644 --- a/activesupport/lib/active_support/core_ext/date/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date/conversions.rb @@ -1,6 +1,7 @@ require 'active_support/inflector' require 'active_support/core_ext/time/conversions' require 'active_support/core_ext/date_time/conversions' +require 'active_support/values/time_zone' class Date DATE_FORMATS = { diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index f440d6ce58..8e8f9022c1 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -6,10 +6,7 @@ require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/object/instance_variables' require 'active_support/deprecation' -require 'active_support/core_ext/date_time/conversions' -require 'active_support/core_ext/time/conversions' require 'active_support/time_with_zone' -require 'active_support/values/time_zone' # Hack to load json gem first so we can overwrite its to_json. begin diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 4907fae9d6..a64128e49e 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -1,4 +1,5 @@ require 'active_support/duration' +require 'active_support/values/time_zone' require 'active_support/core_ext/numeric/time' require 'active_support/core_ext/integer/time' require 'active_support/core_ext/time/conversions' diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index 892aa97ad7..6a51ce9402 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -154,13 +154,13 @@ class FileStoreTest < ActiveSupport::TestCase File.stubs(:mtime).returns(time) @cache.write('foo', 'bar') - cache_read = lambda { @cache.read('foo', :expires_in => 1.minute) } + cache_read = lambda { @cache.read('foo', :expires_in => 60) } assert_equal 'bar', cache_read.call - Time.stubs(:now).returns(time + 30.seconds) + Time.stubs(:now).returns(time + 30) assert_equal 'bar', cache_read.call - Time.stubs(:now).returns(time + 2.minutes) + Time.stubs(:now).returns(time + 120) assert_nil cache_read.call end end diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 26a55a73e1..af73b08547 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -242,6 +242,7 @@ module Rails # If assigned value cannot be matched to a TimeZone, an exception will be raised. initializer :initialize_time_zone do if config.time_zone + require 'active_support/core_ext/time/zones' zone_default = Time.__send__(:get_zone, config.time_zone) unless zone_default -- cgit v1.2.3 From e93c2da14108c324ddf5f08f0165b342e028896f Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 2 Nov 2009 17:49:37 -0800 Subject: Arel::In -> Arel::Predicates::In --- activerecord/lib/active_record/associations.rb | 2 +- .../active_record/associations/has_and_belongs_to_many_association.rb | 2 +- activerecord/lib/active_record/associations/has_many_association.rb | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 0888c41396..03c8d4b3ed 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1724,7 +1724,7 @@ module ActiveRecord if (ids_array = select_limited_ids_array(options, join_dependency)).empty? throw :invalid_query else - Arel::In.new( + Arel::Predicates::In.new( Arel::SqlLiteral.new("#{connection.quote_table_name table_name}.#{primary_key}"), ids_array ) diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index 4672b0723e..c646fe488b 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -84,7 +84,7 @@ module ActiveRecord else relation = arel_table(@reflection.options[:join_table]) relation.conditions(relation[@reflection.primary_key_name].eq(@owner.id). - and(Arel::In.new(relation[@reflection.association_foreign_key], records.map(&:id))) + and(Arel::Predicates::In.new(relation[@reflection.association_foreign_key], records.map(&:id))) ).delete end end diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 29ba84ee37..cd31b0e211 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -71,7 +71,7 @@ module ActiveRecord else relation = arel_table(@reflection.table_name) relation.conditions(relation[@reflection.primary_key_name].eq(@owner.id). - and(Arel::In.new(relation[@reflection.klass.primary_key], records.map(&:id))) + and(Arel::Predicates::In.new(relation[@reflection.klass.primary_key], records.map(&:id))) ).update(relation[@reflection.primary_key_name] => nil) @owner.class.update_counters(@owner.id, cached_counter_attribute_name => -records.size) if has_cached_counter? -- cgit v1.2.3 From 23780850237876cf81038534d8f59fa307af0b31 Mon Sep 17 00:00:00 2001 From: Matias Flores Date: Sat, 26 Sep 2009 21:32:21 -0300 Subject: Fix chars.reverse for multibyte decomposed strings [#597 state:committed] Signed-off-by: Jeremy Kemper --- activesupport/lib/active_support/multibyte/chars.rb | 2 +- activesupport/test/multibyte_chars_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index 579ccc124d..c9bcfbd313 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -321,7 +321,7 @@ module ActiveSupport #:nodoc: # Example: # 'Café'.mb_chars.reverse.to_s #=> 'éfaC' def reverse - chars(self.class.u_unpack(@wrapped_string).reverse.pack('U*')) + chars(self.class.g_unpack(@wrapped_string).reverse.flatten.pack('U*')) end # Implements Unicode-aware slice with codepoints. Slicing on one point returns the codepoints for that diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 0d3c3c7716..a1ea8c8f4c 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -384,6 +384,17 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase assert_equal 'わちにこ', @chars.reverse end + def test_reverse_should_work_with_normalized_strings + str = 'bös' + reversed_str = 'söb' + assert_equal chars(reversed_str).normalize(:kc), chars(str).normalize(:kc).reverse + assert_equal chars(reversed_str).normalize(:c), chars(str).normalize(:c).reverse + assert_equal chars(reversed_str).normalize(:d), chars(str).normalize(:d).reverse + assert_equal chars(reversed_str).normalize(:kd), chars(str).normalize(:kd).reverse + assert_equal chars(reversed_str).decompose, chars(str).decompose.reverse + assert_equal chars(reversed_str).compose, chars(str).compose.reverse + end + def test_slice_should_take_character_offsets assert_equal nil, ''.mb_chars.slice(0) assert_equal 'こ', @chars.slice(0) -- cgit v1.2.3 From d226f17507805c145cc7a1727d46714b88910094 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 3 Nov 2009 00:08:33 -0200 Subject: Ensure that generators can be invoked from any directory. Signed-off-by: Engine Yard --- railties/lib/rails/generators/base.rb | 17 +++++++++++++++++ railties/test/generators/generators_test_helper.rb | 15 ++++++++++----- railties/test/generators_test.rb | 2 +- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index 7af99797ea..e6baf2fc79 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -12,6 +12,16 @@ module Rails add_runtime_options! + # Always move to rails source root. + # + def initialize(*args) #:nodoc: + if !invoked?(args) && defined?(Rails.root) && Rails.root + self.destination_root = Rails.root + FileUtils.cd(destination_root) + end + super + end + # Automatically sets the source root based on the class name. # def self.source_root @@ -247,6 +257,13 @@ module Rails end end + # Check if this generator was invoked from another one by inspecting + # parameters. + # + def invoked?(args) + args.last.is_a?(Hash) && args.last.key?(:invocations) + end + # Use Rails default banner. # def self.banner diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index ccf08c347c..fdf6b4041f 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -1,8 +1,14 @@ # TODO: Fix this RAILS_ENV stuff -RAILS_ENV = 'test' - +RAILS_ENV = 'test' unless defined?(RAILS_ENV) require 'abstract_unit' -Rails.application.config.root = File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures')) + +module Rails + def self.root + @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures')) + end +end +Rails.application.config.root = Rails.root + require 'rails/generators' require 'rubygems' require 'active_record' @@ -15,8 +21,7 @@ class GeneratorsTestCase < Test::Unit::TestCase include FileUtils def destination_root - @destination_root ||= File.expand_path(File.join(File.dirname(__FILE__), - '..', 'fixtures', 'tmp')) + File.join(Rails.root, "tmp") end def setup diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 178b5ef6de..8f1984c7d2 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -105,7 +105,7 @@ class GeneratorsTest < GeneratorsTestCase end def test_warning_is_shown_if_generator_cant_be_loaded - Rails::Generators.load_paths << File.expand_path("../fixtures/vendor/gems/gems/wrong", __FILE__) + Rails::Generators.load_paths << File.join(Rails.root, "vendor", "gems", "gems", "wrong") output = capture(:stderr){ Rails::Generators.find_by_namespace(:wrong) } assert_match /\[WARNING\] Could not load generator at/, output assert_match /Error: uninitialized constant Rails::Generator/, output -- cgit v1.2.3 From ca990b03cc24a132211d0de8fb9dc2f975d904ca Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 2 Nov 2009 20:08:32 -0800 Subject: Work around rebundling issue --- ci/ci_build.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index b2f9f59bec..a6f8871f27 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -16,13 +16,11 @@ root_dir = File.expand_path(File.dirname(__FILE__) + "/..") # A security hole, but there is nothing valuable on rails CI box anyway. build_results[:geminstaller] = system "sudo geminstaller --config=#{root_dir}/ci/geminstaller.yml --exceptions" -rm_f "#{root_dir}/vendor" -system "rm -rf #{root_dir}/*/vendor" cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" puts - build_results[:bundle] = system 'gem bundle' + build_results[:bundle] = system 'rm -rf vendor && gem bundle' end cd "#{root_dir}/activesupport" do -- cgit v1.2.3 From 8ed82dfeb964345db9d092507a24b253de1d2ced Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 2 Nov 2009 20:25:02 -0800 Subject: Force gemcutter source to ensure a consistent arel version --- Gemfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index e99e7c7591..eb84edd147 100644 --- a/Gemfile +++ b/Gemfile @@ -1,4 +1,5 @@ -Gem.sources.each { |uri| source uri } +clear_sources +source 'http://gemcutter.org' gem "rails", "3.0.pre", :vendored_at => "railties" %w( @@ -15,7 +16,6 @@ gem "rack", "1.0.1" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", "~> 0.5.0" gem "erubis", "~> 2.6.0" -gem "arel", :git => "git://github.com/rails/arel.git" gem "mocha" gem "sqlite3-ruby" gem "RedCloth" -- cgit v1.2.3 From aaa5a692a3e471f7f8f50957aac1c06fd30ec166 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 3 Nov 2009 00:25:15 -0800 Subject: Use spoofed version bump to ensure git is preferred --- Gemfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Gemfile b/Gemfile index eb84edd147..a60c1010d9 100644 --- a/Gemfile +++ b/Gemfile @@ -16,6 +16,7 @@ gem "rack", "1.0.1" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", "~> 0.5.0" gem "erubis", "~> 2.6.0" +gem "arel", "0.1.3", :git => "git://github.com/rails/arel.git" gem "mocha" gem "sqlite3-ruby" gem "RedCloth" -- cgit v1.2.3 From f950d0b4af54c3d387024dce2c5e2bc56aef0fc3 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Tue, 3 Nov 2009 11:23:22 -0600 Subject: Fix simple resource named routes for new routing dsl --- actionpack/lib/action_dispatch/routing/mapper.rb | 28 +++++++++++++++++------- actionpack/test/dispatch/routing_test.rb | 25 ++++++++++++++++----- 2 files changed, 39 insertions(+), 14 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index d6d822842b..ebfb4c9be2 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -20,15 +20,20 @@ module ActionDispatch return self end - controller(resource) do + singular = resource.to_s + plural = singular.pluralize + + controller(plural) do namespace(resource) do with_scope_level(:resource) do yield if block_given? - get "", :to => :show + get "", :to => :show, :as => "#{singular}" post "", :to => :create put "", :to => :update - delete "", :to => :destory + delete "", :to => :destroy + get "new", :to => :new, :as => "new_#{singular}" + get "edit", :to => :edit, :as => "edit_#{singular}" end end end @@ -54,22 +59,25 @@ module ActionDispatch return self end + plural = resource.to_s + singular = plural.singularize + controller(resource) do namespace(resource) do with_scope_level(:resources) do yield if block_given? member do - get "", :to => :show + get "", :to => :show, :as => "#{singular}" put "", :to => :update - delete "", :to => :destory - get "edit", :to => :edit + delete "", :to => :destroy + get "edit", :to => :edit, :as => "edit_#{singular}" end collection do - get "", :to => :index + get "", :to => :index, :as => "#{plural}" post "", :to => :create - get "new", :to => :new + get "new", :to => :new, :as => "new_#{singular}" end end end @@ -221,6 +229,10 @@ module ActionDispatch map_method(:delete, *args, &block) end + def root(options = {}) + match '/', options.merge(:as => :root) + end + def match(*args) options = args.last.is_a?(Hash) ? args.pop : {} diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 74e6c8e72d..7917c1974b 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -190,8 +190,21 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest def test_projects with_test_routes do + get '/projects' + assert_equal 'projects#index', @response.body + assert_equal '/projects', projects_path + + get '/projects/new' + assert_equal 'projects#new', @response.body + assert_equal '/projects/new', new_project_path + get '/projects/1' assert_equal 'projects#show', @response.body + assert_equal '/projects/1', project_path(:id => '1') + + get '/projects/1/edit' + assert_equal 'projects#edit', @response.body + assert_equal '/projects/1/edit', edit_project_path(:id => '1') end end @@ -231,7 +244,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal 'people#index', @response.body get '/projects/1/companies/1/avatar' - assert_equal 'avatar#show', @response.body + assert_equal 'avatars#show', @response.body end end @@ -254,7 +267,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal 'people#show', @response.body get '/projects/1/people/1/7a2dec8/avatar' - assert_equal 'avatar#show', @response.body + assert_equal 'avatars#show', @response.body put '/projects/1/people/1/accessible_projects' assert_equal 'people#accessible_projects', @response.body @@ -282,7 +295,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal 'posts#preview', @response.body get '/projects/1/posts/1/subscription' - assert_equal 'subscription#show', @response.body + assert_equal 'subscriptions#show', @response.body get '/projects/1/posts/1/comments' assert_equal 'comments#index', @response.body @@ -329,13 +342,13 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest def test_account_namespace with_test_routes do get '/account/subscription' - assert_equal 'subscription#show', @response.body + assert_equal 'subscriptions#show', @response.body get '/account/credit' - assert_equal 'credit#show', @response.body + assert_equal 'credits#show', @response.body get '/account/credit_card' - assert_equal 'credit_card#show', @response.body + assert_equal 'credit_cards#show', @response.body end end -- cgit v1.2.3 From e15b5eda2b4888764cd0c63a297136babac026d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 3 Nov 2009 20:50:39 -0200 Subject: Avoid duplicated names on help description and show proper error message if trying to load a Rails 2.x generator. Signed-off-by: Jeremy Kemper --- railties/lib/rails/generators.rb | 50 ++++++++++++++++------ .../lib/generators/foobar/foobar_generator.rb | 4 ++ railties/test/generators_test.rb | 11 ++++- 3 files changed, 49 insertions(+), 16 deletions(-) create mode 100644 railties/test/fixtures/lib/generators/foobar/foobar_generator.rb diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 49f32aa0db..a6a59f039f 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -152,7 +152,18 @@ module Rails end load_paths # Cache load paths. Needed to avoid __FILE__ pointing to wrong paths. - # Receives a namespace and tries different combinations to find a generator. + # Rails finds namespaces exactly as thor, with three conveniences: + # + # 1) If your generator name ends with generator, as WebratGenerator, it sets + # its namespace to "webrat", so it can be invoked as "webrat" and not + # "webrat_generator"; + # + # 2) If your generator has a generators namespace, as Rails::Generators::WebratGenerator, + # the namespace is set to "rails:generators:webrat", but Rails allows it + # to be invoked simply as "rails:webrat". The "generators" is added + # automatically when doing the lookup; + # + # 3) Rails looks in load paths and loads the generator just before it's going to be used. # # ==== Examples # @@ -162,30 +173,29 @@ module Rails # # "rails:generators:webrat", "webrat:generators:integration", "webrat" # - # If the namespace has ":" included we consider that a absolute namespace - # was given and the lookup above does not happen. Just the name is searched. - # - # Finally, it deals with one kind of shortcut: + # On the other hand, if "rails:webrat" is given, it will search for: # - # find_by_namespace "test_unit:model" + # "rails:generators:webrat", "rails:webrat" # - # It will search for generators at: - # - # "test_unit:generators:model", "test_unit:model" + # Notice that the "generators" namespace is handled automatically by Rails, + # so you don't need to type it when you want to invoke a generator in specific. # def self.find_by_namespace(name, base=nil, context=nil) #:nodoc: - name, attempts = name.to_s, [] + name, attempts = name.to_s, [ ] case name.count(':') when 1 base, name = name.split(':') return find_by_namespace(name, base) when 0 - attempts << "#{base}:generators:#{name}" if base - attempts << "#{name}:generators:#{context}" if context + attempts += generator_names(base, name) if base + attempts += generator_names(name, context) if context end attempts << name + attempts += generator_names(name, name) unless name.include?(?:) + attempts.uniq! + unloaded = attempts - namespaces lookup(unloaded) @@ -231,7 +241,10 @@ module Rails until tail.empty? others += Dir[File.join(path, *tail)].collect do |file| - file.split('/')[-tail.size, 2].join(':').sub(/_generator\.rb$/, '') + name = file.split('/')[-tail.size, 2] + name.last.sub!(/_generator\.rb$/, '') + name.uniq! + name.join(':') end tail.shift end @@ -246,7 +259,7 @@ module Rails # Return all defined namespaces. # def self.namespaces #:nodoc: - Thor::Base.subclasses.map{ |klass| klass.namespace } + Thor::Base.subclasses.map { |klass| klass.namespace } end # Keep builtin generators in an Array[Array[group, name]]. @@ -257,6 +270,12 @@ module Rails end end + # By default, Rails strips the generator namespace to make invocations + # easier. This method generaters the both possibilities names. + def self.generator_names(first, second) + [ "#{first}:generators:#{second}", "#{first}:#{second}" ] + end + # Try callbacks for the given base. # def self.invoke_fallbacks_for(name, base) @@ -285,6 +304,9 @@ module Rails Dir[File.join(path, '**', attempts)].each do |file| begin require file + rescue NameError => e + raise unless e.message =~ /Rails::Generator/ + warn "[WARNING] Could not load generator at #{file.inspect} because it's a Rails 2.x generator, which is not supported anymore" rescue Exception => e warn "[WARNING] Could not load generator at #{file.inspect}. Error: #{e.message}" end diff --git a/railties/test/fixtures/lib/generators/foobar/foobar_generator.rb b/railties/test/fixtures/lib/generators/foobar/foobar_generator.rb new file mode 100644 index 0000000000..d1de8c56fa --- /dev/null +++ b/railties/test/fixtures/lib/generators/foobar/foobar_generator.rb @@ -0,0 +1,4 @@ +module Foobar + class FoobarGenerator < Rails::Generators::Base + end +end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 8f1984c7d2..07f51eca01 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -45,6 +45,12 @@ class GeneratorsTest < GeneratorsTestCase assert_equal "test_unit:generators:model", klass.namespace end + def test_find_by_namespace_with_duplicated_name + klass = Rails::Generators.find_by_namespace(:foobar) + assert klass + assert_equal "foobar:foobar", klass.namespace + end + def test_find_by_namespace_add_generators_to_raw_lookups klass = Rails::Generators.find_by_namespace("test_unit:model") assert klass @@ -101,14 +107,15 @@ class GeneratorsTest < GeneratorsTestCase def test_rails_generators_with_others_information output = capture(:stdout){ Rails::Generators.help }.split("\n").last - assert_equal "Others: active_record:fixjour, fixjour, mspec, rails:javascripts.", output + assert_equal "Others: active_record:fixjour, fixjour, foobar, mspec, rails:javascripts.", output end def test_warning_is_shown_if_generator_cant_be_loaded Rails::Generators.load_paths << File.join(Rails.root, "vendor", "gems", "gems", "wrong") output = capture(:stderr){ Rails::Generators.find_by_namespace(:wrong) } + assert_match /\[WARNING\] Could not load generator at/, output - assert_match /Error: uninitialized constant Rails::Generator/, output + assert_match /Rails 2\.x generator/, output end def test_no_color_sets_proper_shell -- cgit v1.2.3 From 3fb548cac319207f369f348c5f27d165b65c2f85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 3 Nov 2009 20:51:44 -0200 Subject: Ensure ActiveRecord is loaded on revoke/destroy. Signed-off-by: Jeremy Kemper --- railties/lib/rails/generators/active_record.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/railties/lib/rails/generators/active_record.rb b/railties/lib/rails/generators/active_record.rb index babad33db3..c62f75c384 100644 --- a/railties/lib/rails/generators/active_record.rb +++ b/railties/lib/rails/generators/active_record.rb @@ -1,6 +1,7 @@ require 'rails/generators/named_base' require 'rails/generators/migration' require 'rails/generators/active_model' +require 'active_record' module ActiveRecord module Generators -- cgit v1.2.3 From 3b8e29fe5697d4aec99229abcbd04141d3e53b71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 3 Nov 2009 22:02:24 -0200 Subject: Remove --freeze (since Rails will come bundled in all new apps) and update gem action to change Gemfile instead of config.environment. Signed-off-by: Jeremy Kemper --- railties/lib/rails/generators/actions.rb | 60 ++++++++++++++++++---- .../rails/generators/rails/app/app_generator.rb | 7 --- .../rails/generators/rails/app/templates/Gemfile | 4 +- railties/test/generators/actions_test.rb | 47 ++++++++--------- railties/test/generators/app_generator_test.rb | 14 ----- railties/test/generators/generators_test_helper.rb | 2 +- 6 files changed, 76 insertions(+), 58 deletions(-) diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index 9254f8d918..c601c6fb39 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -1,4 +1,5 @@ require 'open-uri' +require 'active_support/deprecation' module Rails module Generators @@ -45,19 +46,56 @@ module Rails # # gem "rspec", :env => :test # gem "technoweenie-restful-authentication", :lib => "restful-authentication", :source => "http://gems.github.com/" + # gem "rails", "3.0", :git => "git://github.com/rails/rails" # - def gem(name, options={}) - log :gem, name - env = options.delete(:env) + def gem(*args) + options = args.extract_options! + name, version = args - gems_code = "config.gem '#{name}'" + # Deal with deprecated options + { :env => :only, :lib => :require_as }.each do |old, new| + next unless options[old] + options[new] = options.delete(old) + ActiveSupport::Deprecation.warn "#{old.inspect} option in gem is deprecated, use #{new.inspect} instead" + end + + # Deal with deprecated source + if source = options.delete(:source) + ActiveSupport::Deprecation.warn ":source option in gem is deprecated, use add_source method instead" + add_source(source) + end + + # Set the message to be shown in logs. Uses the git repo if one is given, + # otherwise use name (version). + parts, message = [ name.inspect ], name + if version ||= options.delete(:version) + parts << version + message << " (#{version})" + end + message = options[:git] if options[:git] + + log :gemfile, message + + options.each do |option, value| + parts << ":#{option} => #{value.inspect}" + end - if options.any? - opts = options.inject([]) {|result, h| result << [":#{h[0]} => #{h[1].inspect.gsub('"',"'")}"] }.sort.join(", ") - gems_code << ", #{opts}" + in_root do + append_file "Gemfile", "gem #{parts.join(", ")}", :verbose => false end + end + + # Add the given source to Gemfile + # + # ==== Example + # + # source "http://gems.github.com/" + def add_source(source, options={}) + log :source, source - environment gems_code, :env => env + in_root do + prepend_file "Gemfile", "source #{source.inspect}", :verbose => false + end end # Adds a line inside the Initializer block for config/environment.rb. @@ -79,6 +117,7 @@ module Rails end end end + alias :application :environment # Run a command in git. # @@ -222,9 +261,8 @@ module Rails # # freeze! # - def freeze!(args = {}) - log :vendor, "rails" - in_root { run("#{extify(:rake)} rails:freeze:edge", :verbose => false) } + def freeze!(args={}) + ActiveSupport::Deprecation.warn "freeze! is deprecated since your rails app now comes bundled with Rails by default, please check your Gemfile" end # Make an entry in Rails routing file conifg/routes.rb diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 93d9ac553d..e552cc4520 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -12,9 +12,6 @@ module Rails::Generators class_option :database, :type => :string, :aliases => "-d", :default => "sqlite3", :desc => "Preconfigure for selected database (options: #{DATABASES.join('/')})" - class_option :freeze, :type => :boolean, :aliases => "-F", :default => false, - :desc => "Freeze Rails in vendor/rails from the gems" - class_option :template, :type => :string, :aliases => "-m", :desc => "Path to an application template (can be a filesystem path or URL)." @@ -155,10 +152,6 @@ module Rails::Generators raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" end - def freeze? - freeze! if options[:freeze] - end - protected attr_accessor :rails_template diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 3966c0f70d..a41ce2f484 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -1,9 +1,9 @@ # Gemfile is where you list all of your application's dependencies # -<%= "# " if options.freeze? %>gem "rails", "<%= Rails::VERSION::STRING %>" +gem "rails", "<%= Rails::VERSION::STRING %>" # # Bundling edge rails: -<%= "# " unless options.freeze? %>gem "rails", "<%= Rails::VERSION::STRING %>", :git => "git://github.com/rails/rails.git" +# gem "rails", "<%= Rails::VERSION::STRING %>", :git => "git://github.com/rails/rails.git" # Specify gemcutter as a gem source # source "http://gemcutter.org" diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index 199b5fa8b4..7d03a37f2a 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -54,37 +54,37 @@ class ActionsTest < GeneratorsTestCase action :plugin, 'rest_auth', {} end - def test_gem_should_put_gem_dependency_in_enviroment + def test_add_source_adds_source_to_gemfile run_generator - action :gem, 'will-paginate' - assert_file 'config/application.rb', /config\.gem 'will\-paginate'/ + action :add_source, 'http://gems.github.com' + assert_file 'Gemfile', /source "http:\/\/gems\.github\.com"/ end - def test_gem_with_options_should_include_options_in_gem_dependency_in_environment + def test_gem_should_put_gem_dependency_in_gemfile run_generator - action :gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com' - - regexp = /#{Regexp.escape("config.gem 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com'")}/ - assert_file 'config/application.rb', regexp + action :gem, 'will-paginate' + assert_file 'Gemfile', /gem "will\-paginate"/ end - def test_gem_with_env_string_should_put_gem_dependency_in_specified_environment + def test_gem_with_options_should_include_all_options_in_gemfile run_generator - action :gem, 'rspec', :env => 'test' - assert_file 'config/environments/test.rb', /config\.gem 'rspec'/ - end - def test_gem_with_env_array_should_put_gem_dependency_in_specified_environments - run_generator - action :gem, 'quietbacktrace', :env => %w[ development test ] - assert_file 'config/environments/development.rb', /config\.gem 'quietbacktrace'/ - assert_file 'config/environments/test.rb', /config\.gem 'quietbacktrace'/ + assert_deprecated do + action :gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com' + end + + assert_file 'Gemfile', /gem "mislav\-will\-paginate", :require_as => "will\-paginate"/ + assert_file 'Gemfile', /source "http:\/\/gems\.github\.com"/ end - def test_gem_with_lib_option_set_to_false_should_put_gem_dependency_in_enviroment_correctly + def test_gem_with_env_should_include_all_dependencies_in_gemfile run_generator - action :gem, 'mislav-will-paginate', :lib => false - assert_file 'config/application.rb', /config\.gem 'mislav\-will\-paginate'\, :lib => false/ + + assert_deprecated do + action :gem, 'rspec', :env => %w(development test) + end + + assert_file 'Gemfile', /gem "rspec", :only => \["development", "test"\]/ end def test_environment_should_include_data_in_environment_initializer_block @@ -163,9 +163,10 @@ class ActionsTest < GeneratorsTestCase action :capify! end - def test_freeze_should_freeze_rails_edge - generator.expects(:run).once.with('rake rails:freeze:edge', :verbose => false) - action :freeze! + def test_freeze_is_deprecated + assert_deprecated do + action :freeze! + end end def test_route_should_add_data_to_the_routes_block_in_config_routes diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 20f2a24e6d..10d0bc6bc2 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -110,20 +110,6 @@ class AppGeneratorTest < GeneratorsTestCase ).each { |path| assert_file "script/#{path}", /#!\/usr\/bin\/env/ } end - def test_rails_is_frozen - generator(:freeze => true, :database => "sqlite3").expects(:run). - with("rake rails:freeze:edge", :verbose => false) - silence(:stdout){ generator.invoke } - - assert_file 'Gemfile' do |content| - flag = %(gem "rails", "#{Rails::VERSION::STRING}", :git => "git://github.com/rails/rails.git") - assert_match /^#{Regexp.escape(flag)}$/, content - - flag = %(# gem "rails", "#{Rails::VERSION::STRING}") - assert_match /^#{Regexp.escape(flag)}$/, content - end - end - def test_template_from_dir_pwd FileUtils.cd(Rails.root) assert_match /It works from file!/, run_generator(["-m", "lib/template.rb"]) diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index fdf6b4041f..4ce48a453b 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -17,7 +17,7 @@ require 'action_dispatch' CURRENT_PATH = File.expand_path(Dir.pwd) Rails::Generators.no_color! -class GeneratorsTestCase < Test::Unit::TestCase +class GeneratorsTestCase < ActiveSupport::TestCase include FileUtils def destination_root -- cgit v1.2.3 From e5211e3bd052ebc24905c65172d449f7b3bcc73f Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 3 Nov 2009 16:36:19 -0800 Subject: Improve Gemfile commentary --- railties/lib/rails/generators/rails/app/templates/Gemfile | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index a41ce2f484..8e851a64e7 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -1,20 +1,17 @@ -# Gemfile is where you list all of your application's dependencies -# +# Edit this Gemfile to bundle your application's dependencies. + gem "rails", "<%= Rails::VERSION::STRING %>" -# -# Bundling edge rails: -# gem "rails", "<%= Rails::VERSION::STRING %>", :git => "git://github.com/rails/rails.git" -# Specify gemcutter as a gem source -# source "http://gemcutter.org" +## Bundle edge rails: +# gem "rails", :git => "git://github.com/rails/rails.git" -# Specify gems that this application depends on and have them installed with rake gems:install +## Bundle the gems you use: # gem "bj" # gem "hpricot", "0.6" # gem "sqlite3-ruby", :require_as => "sqlite3" # gem "aws-s3", :require_as => "aws/s3" -# Specify gems that should only be required in certain environments +## Bundle gems used only in certain environments: # gem "rspec", :only => :test # only :test do # gem "webrat" -- cgit v1.2.3 From d627c932bdc5c0e2911e39cfb38952c29dab7afc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 4 Nov 2009 00:14:44 -0200 Subject: Pass config.generators options along when RAILS_GENERATORS is set and show --force-plural message just once. Signed-off-by: Jeremy Kemper --- railties/lib/rails/application.rb | 3 ++- railties/lib/rails/commands/destroy.rb | 2 -- railties/lib/rails/commands/generate.rb | 2 -- railties/lib/rails/configuration.rb | 14 +++++++++----- railties/lib/rails/generators/actions.rb | 1 + railties/lib/rails/generators/named_base.rb | 5 ++++- .../rails/generators/rails/app/templates/script/destroy.tt | 3 ++- .../generators/rails/app/templates/script/generate.tt | 1 + railties/lib/rails/generators/resource_helpers.rb | 8 +++++++- railties/test/application/generators_test.rb | 6 ++++-- railties/test/generators/resource_generator_test.rb | 2 +- 11 files changed, 31 insertions(+), 16 deletions(-) diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index af73b08547..ce3ab9147c 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -416,7 +416,8 @@ module Rails # === # TODO: Does this need to be an initializer here? initializer :initialize_generators do - if defined?(Rails::Generators) + if defined?(RAILS_GENERATORS) && RAILS_GENERATORS + require 'rails/generators' Rails::Generators.no_color! unless config.generators.colorize_logging Rails::Generators.aliases.deep_merge! config.generators.aliases Rails::Generators.options.deep_merge! config.generators.options diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb index 1270fdd033..15ff90f78a 100644 --- a/railties/lib/rails/commands/destroy.rb +++ b/railties/lib/rails/commands/destroy.rb @@ -1,5 +1,3 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'generators')) - if ARGV.size == 0 Rails::Generators.help exit diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb index d91dcf9788..82a658e2ed 100755 --- a/railties/lib/rails/commands/generate.rb +++ b/railties/lib/rails/commands/generate.rb @@ -1,5 +1,3 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'generators')) - if ARGV.size == 0 Rails::Generators.help exit diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index 0a545f23de..2b847ba711 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -278,12 +278,16 @@ module Rails end def method_missing(method, *args) - method = method.to_s.sub(/=$/, '').to_sym - namespace = args.first.is_a?(Symbol) ? args.shift : nil - configuration = args.first.is_a?(Hash) ? args.shift : nil + method = method.to_s.sub(/=$/, '').to_sym - @options[:rails][method] = namespace if namespace - namespace ||= method + if method == :rails + namespace, configuration = :rails, args.shift + elsif args.first.is_a?(Hash) + namespace, configuration = method, args.shift + else + namespace, configuration = args.shift, args.shift + @options[:rails][method] = namespace + end if configuration aliases = configuration.delete(:aliases) diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index c601c6fb39..8677bf283b 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -289,6 +289,7 @@ module Rails if args.size == 1 say args.first.to_s else + args << (self.behavior == :invoke ? :green : :red) say_status *args end end diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index 0e5976f915..1d4f52286e 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -11,7 +11,10 @@ module Rails alias :file_name :singular_name - def initialize(*args) #:nodoc: + def initialize(args, *options) #:nodoc: + # Unfreeze name in case it's given as a frozen string + args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? + super assign_names!(self.name) parse_attributes! if respond_to?(:attributes) diff --git a/railties/lib/rails/generators/rails/app/templates/script/destroy.tt b/railties/lib/rails/generators/rails/app/templates/script/destroy.tt index c97090cdee..62a856d338 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/destroy.tt +++ b/railties/lib/rails/generators/rails/app/templates/script/destroy.tt @@ -1,3 +1,4 @@ <%= shebang %> -require File.expand_path('../../config/application', __FILE__) +RAILS_GENERATORS = true +require File.expand_path('../../config/environment', __FILE__) require 'rails/commands/destroy' diff --git a/railties/lib/rails/generators/rails/app/templates/script/generate.tt b/railties/lib/rails/generators/rails/app/templates/script/generate.tt index 26f029c6a6..a005e77104 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/generate.tt +++ b/railties/lib/rails/generators/rails/app/templates/script/generate.tt @@ -1,3 +1,4 @@ <%= shebang %> +RAILS_GENERATORS = true require File.expand_path('../../config/environment', __FILE__) require 'rails/commands/generate' diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb index 0385581083..99954e2292 100644 --- a/railties/lib/rails/generators/resource_helpers.rb +++ b/railties/lib/rails/generators/resource_helpers.rb @@ -6,6 +6,8 @@ module Rails # ActiveModel. # module ResourceHelpers + mattr_accessor :skip_warn + def self.included(base) #:nodoc: base.send :attr_reader, :controller_name, :controller_class_name, :controller_file_name, :controller_class_path, :controller_file_path @@ -19,7 +21,11 @@ module Rails super if name == name.pluralize && !options[:force_plural] - say "Plural version of the model detected, using singularized version. Override with --force-plural." + unless ResourceHelpers.skip_warn + say "Plural version of the model detected, using singularized version. Override with --force-plural." + ResourceHelpers.skip_warn = true + end + name.replace name.singularize assign_names!(self.name) end diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 445a867c85..bfbf1ffd16 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -1,4 +1,5 @@ require "isolation/abstract_unit" +RAILS_GENERATORS = true module ApplicationTests class GeneratorsTest < Test::Unit::TestCase @@ -23,7 +24,8 @@ module ApplicationTests Rails::Initializer.run do |c| c.generators.orm = :datamapper c.generators.test_framework = :rspec - expected = { :rails => { :orm => :datamapper, :test_framework => :rspec } } + c.generators.helper = false + expected = { :rails => { :orm => :datamapper, :test_framework => :rspec, :helper => false } } assert_equal(expected, c.generators.options) end end @@ -93,4 +95,4 @@ module ApplicationTests assert Rails::Generators.options.size >= 1 end end -end \ No newline at end of file +end diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb index dcae81c204..886af01b22 100644 --- a/railties/test/generators/resource_generator_test.rb +++ b/railties/test/generators/resource_generator_test.rb @@ -75,7 +75,7 @@ class ResourceGeneratorTest < GeneratorsTestCase end def test_plural_names_are_singularized - content = run_generator ["accounts"] + content = run_generator ["accounts".freeze] assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ assert_file "test/unit/account_test.rb", /class AccountTest/ assert_match /Plural version of the model detected, using singularized version. Override with --force-plural./, content -- cgit v1.2.3 From a3d5274e67c841a6fdc9f9acb9e1b6bbc351dd28 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 3 Nov 2009 18:58:40 -0800 Subject: Configure generator when needed rather than during initialization --- railties/lib/rails/application.rb | 12 ------------ railties/lib/rails/generators.rb | 6 ++++++ .../rails/generators/rails/app/templates/script/destroy.tt | 3 ++- .../rails/generators/rails/app/templates/script/generate.tt | 3 ++- railties/test/application/generators_test.rb | 3 ++- 5 files changed, 12 insertions(+), 15 deletions(-) diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index ce3ab9147c..242aea1842 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -412,18 +412,6 @@ module Rails end end - # Configure generators if they were already loaded - # === - # TODO: Does this need to be an initializer here? - initializer :initialize_generators do - if defined?(RAILS_GENERATORS) && RAILS_GENERATORS - require 'rails/generators' - Rails::Generators.no_color! unless config.generators.colorize_logging - Rails::Generators.aliases.deep_merge! config.generators.aliases - Rails::Generators.options.deep_merge! config.generators.options - end - end - # For each framework, search for instrument file with Notifications hooks. # initializer :load_notifications_hooks do diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index a6a59f039f..fa2c11795b 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -72,6 +72,12 @@ module Rails } } + def self.configure!(config = Rails.application.config.generators) #:nodoc: + no_color! unless config.colorize_logging + aliases.deep_merge! config.aliases + options.deep_merge! config.options + end + def self.aliases #:nodoc: @aliases ||= DEFAULT_ALIASES.dup end diff --git a/railties/lib/rails/generators/rails/app/templates/script/destroy.tt b/railties/lib/rails/generators/rails/app/templates/script/destroy.tt index 62a856d338..6adc90b2c3 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/destroy.tt +++ b/railties/lib/rails/generators/rails/app/templates/script/destroy.tt @@ -1,4 +1,5 @@ <%= shebang %> -RAILS_GENERATORS = true require File.expand_path('../../config/environment', __FILE__) +require 'rails/generators' +Rails::Generators.configure! require 'rails/commands/destroy' diff --git a/railties/lib/rails/generators/rails/app/templates/script/generate.tt b/railties/lib/rails/generators/rails/app/templates/script/generate.tt index a005e77104..71d47dec92 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/generate.tt +++ b/railties/lib/rails/generators/rails/app/templates/script/generate.tt @@ -1,4 +1,5 @@ <%= shebang %> -RAILS_GENERATORS = true require File.expand_path('../../config/environment', __FILE__) +require 'rails/generators' +Rails::Generators.configure! require 'rails/commands/generate' diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index bfbf1ffd16..ccbcd84176 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -1,5 +1,4 @@ require "isolation/abstract_unit" -RAILS_GENERATORS = true module ApplicationTests class GeneratorsTest < Test::Unit::TestCase @@ -47,6 +46,7 @@ module ApplicationTests end # Initialize the application Rails.initialize! + Rails::Generators.configure! assert_equal :rspec, Rails::Generators.options[:rails][:test_framework] assert_equal "-w", Rails::Generators.aliases[:rails][:test_framework] @@ -59,6 +59,7 @@ module ApplicationTests end # Initialize the application Rails.initialize! + Rails::Generators.configure! assert_equal Thor::Base.shell, Thor::Shell::Basic end -- cgit v1.2.3 From 935bd0fef8e26f4ec65fe411a1d29942493f8d46 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Sun, 1 Nov 2009 17:18:27 +0100 Subject: Add ActiveSupport::Multibyte::Chars#limit. The limit method limits the number of bytes in a string. Useful when the storage space of the string is limited, for instance in a database column definition. Sharpen up the implementation of translate offset. [#3192 state:committed] --- .../lib/active_support/multibyte/chars.rb | 29 ++++++----- activesupport/test/multibyte_chars_test.rb | 59 ++++++++++++++++++++++ 2 files changed, 74 insertions(+), 14 deletions(-) diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index c9bcfbd313..51b870de8c 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -363,6 +363,16 @@ module ActiveSupport #:nodoc: slice end + # Limit the byte size of the string to a number of bytes without breaking characters. Usable + # when the storage for a string is limited for some reason. + # + # Example: + # s = 'こんにちは' + # s.mb_chars.limit(7) #=> "こに" + def limit(limit) + slice(0...translate_offset(limit)) + end + # Returns the codepoint of the first character in the string. # # Example: @@ -651,24 +661,15 @@ module ActiveSupport #:nodoc: end protected - + def translate_offset(byte_offset) #:nodoc: return nil if byte_offset.nil? return 0 if @wrapped_string == '' - chunk = @wrapped_string[0..byte_offset] begin - begin - chunk.unpack('U*').length - 1 - rescue ArgumentError => e - chunk = @wrapped_string[0..(byte_offset+=1)] - # Stop retrying at the end of the string - raise e unless byte_offset < chunk.length - # We damaged a character, retry - retry - end - # Catch the ArgumentError so we can throw our own - rescue ArgumentError - raise EncodingError, 'malformed UTF-8 character' + @wrapped_string[0...byte_offset].unpack('U*').length + rescue ArgumentError => e + byte_offset -= 1 + retry end end diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index a1ea8c8f4c..fc7b5e5081 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -169,6 +169,7 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase assert chars('').strip.kind_of?(ActiveSupport::Multibyte.proxy_class) assert chars('').reverse.kind_of?(ActiveSupport::Multibyte.proxy_class) assert chars(' ').slice(0).kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').limit(0).kind_of?(ActiveSupport::Multibyte.proxy_class) assert chars('').upcase.kind_of?(ActiveSupport::Multibyte.proxy_class) assert chars('').downcase.kind_of?(ActiveSupport::Multibyte.proxy_class) assert chars('').capitalize.kind_of?(ActiveSupport::Multibyte.proxy_class) @@ -196,7 +197,9 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase def test_should_return_character_offset_for_regexp_matches assert_nil(@chars =~ /wrong/u) assert_equal 0, (@chars =~ /こ/u) + assert_equal 0, (@chars =~ /こに/u) assert_equal 1, (@chars =~ /に/u) + assert_equal 2, (@chars =~ /ち/u) assert_equal 3, (@chars =~ /わ/u) end @@ -493,6 +496,44 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase end end + def test_limit_should_not_break_on_blank_strings + chars = ''.mb_chars + + assert_equal '', chars.limit(0) + assert_equal '', chars.limit(1) + end + + def test_limit_should_work_on_a_multibyte_string + chars = UNICODE_STRING.mb_chars + + assert_equal UNICODE_STRING, chars.limit(UNICODE_STRING.length) + assert_equal '', chars.limit(0) + assert_equal '', chars.limit(1) + assert_equal 'こ', chars.limit(3) + assert_equal 'こに', chars.limit(6) + assert_equal 'こに', chars.limit(8) + assert_equal 'こにち', chars.limit(9) + assert_equal 'こにちわ', chars.limit(50) + end + + def test_limit_should_work_on_an_ascii_string + ascii = ASCII_STRING.mb_chars + + assert_equal ASCII_STRING, ascii.limit(ASCII_STRING.length) + assert_equal '', ascii.limit(0) + assert_equal 'o', ascii.limit(1) + assert_equal 'oh', ascii.limit(2) + assert_equal 'ohay', ascii.limit(4) + assert_equal 'ohayo', ascii.limit(50) + end + + def test_limit_should_keep_under_the_specified_byte_limit + chars = UNICODE_STRING.mb_chars + (1..UNICODE_STRING.length).each do |limit| + assert chars.limit(limit).to_s.length <= limit + end + end + def test_composition_exclusion_is_set_up_properly # Normalization of DEVANAGARI LETTER QA breaks when composition exclusion isn't used correctly qa = [0x915, 0x93c].pack('U*') @@ -603,3 +644,21 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase end.pack('U*') end end + +class MultibyteInternalsTest < ActiveSupport::TestCase + include MultibyteTestHelpers + + test "Chars translates a character offset to a byte offset" do + chars = "Puisque c'était son erreur, il m'a aidé".mb_chars + [ + [0, 0], + [3, 3], + [12, 11], + [14, 13], + [41, 39] + ].each do |byte_offset, character_offset| + assert_equal character_offset, chars.send(:translate_offset, byte_offset), + "Expected byte offset #{byte_offset} to translate to #{character_offset}" + end + end +end \ No newline at end of file -- cgit v1.2.3 From 62a022891b5f12284205920a03a3cbbe5b8ecd27 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Mon, 2 Nov 2009 21:06:12 +0100 Subject: Improve performance of Multibyte::Utils. Replace explicit for-loops by faster enumeration methods. [#3158 state:committed] --- activesupport/lib/active_support/multibyte/utils.rb | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/activesupport/lib/active_support/multibyte/utils.rb b/activesupport/lib/active_support/multibyte/utils.rb index 8e47763d39..b243df46d8 100644 --- a/activesupport/lib/active_support/multibyte/utils.rb +++ b/activesupport/lib/active_support/multibyte/utils.rb @@ -26,11 +26,11 @@ module ActiveSupport #:nodoc: else def self.verify(string) if expression = valid_character - for c in string.split(//) - return false unless expression.match(c) - end + # Splits the string on character boundaries, which are determined based on $KCODE. + string.split(//).all? { |c| expression.match(c) } + else + true end - true end end @@ -49,9 +49,8 @@ module ActiveSupport #:nodoc: else def self.clean(string) if expression = valid_character - stripped = []; for c in string.split(//) - stripped << c if expression.match(c) - end; stripped.join + # Splits the string on character boundaries, which are determined based on $KCODE. + string.split(//).grep(expression).join else string end -- cgit v1.2.3 From da3a228a93e1858a46f9a0cefcb9c72285479a56 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Mon, 2 Nov 2009 21:34:07 +0100 Subject: Make ActiveSupport::Chars#limit run on Ruby 1.9. --- .../lib/active_support/multibyte/chars.rb | 5 ++ activesupport/test/multibyte_chars_test.rb | 56 +++++++++++----------- 2 files changed, 32 insertions(+), 29 deletions(-) diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index 51b870de8c..d372b0ab1f 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -665,6 +665,11 @@ module ActiveSupport #:nodoc: def translate_offset(byte_offset) #:nodoc: return nil if byte_offset.nil? return 0 if @wrapped_string == '' + + if @wrapped_string.respond_to?(:force_encoding) + @wrapped_string = @wrapped_string.dup.force_encoding(Encoding::ASCII_8BIT) + end + begin @wrapped_string[0...byte_offset].unpack('U*').length rescue ArgumentError => e diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index fc7b5e5081..4ff74abf61 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -100,15 +100,14 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase def setup @chars = UNICODE_STRING.dup.mb_chars - # NEWLINE, SPACE, EM SPACE - @whitespace = "\n#{[32, 8195].pack('U*')}" - - # Ruby 1.9 doesn't recognize EM SPACE as whitespace! - if @whitespace.respond_to?(:force_encoding) - @whitespace.slice!(2) - @whitespace.force_encoding(Encoding::UTF_8) + if RUBY_VERSION < '1.9' + # Multibyte support all kinds of whitespace (ie. NEWLINE, SPACE, EM SPACE) + @whitespace = "\n\t#{[32, 8195].pack('U*')}" + else + # Ruby 1.9 only supports basic whitespace + @whitespace = "\n\t ".force_encoding(Encoding::UTF_8) end - + @byte_order_mark = [65279].pack('U') end @@ -497,28 +496,27 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase end def test_limit_should_not_break_on_blank_strings - chars = ''.mb_chars - - assert_equal '', chars.limit(0) - assert_equal '', chars.limit(1) + example = chars('') + assert_equal example, example.limit(0) + assert_equal example, example.limit(1) end def test_limit_should_work_on_a_multibyte_string - chars = UNICODE_STRING.mb_chars + example = chars(UNICODE_STRING) + bytesize = UNICODE_STRING.respond_to?(:bytesize) ? UNICODE_STRING.bytesize : UNICODE_STRING.size - assert_equal UNICODE_STRING, chars.limit(UNICODE_STRING.length) - assert_equal '', chars.limit(0) - assert_equal '', chars.limit(1) - assert_equal 'こ', chars.limit(3) - assert_equal 'こに', chars.limit(6) - assert_equal 'こに', chars.limit(8) - assert_equal 'こにち', chars.limit(9) - assert_equal 'こにちわ', chars.limit(50) + assert_equal UNICODE_STRING, example.limit(bytesize) + assert_equal '', example.limit(0) + assert_equal '', example.limit(1) + assert_equal 'こ', example.limit(3) + assert_equal 'こに', example.limit(6) + assert_equal 'こに', example.limit(8) + assert_equal 'こにち', example.limit(9) + assert_equal 'こにちわ', example.limit(50) end def test_limit_should_work_on_an_ascii_string - ascii = ASCII_STRING.mb_chars - + ascii = chars(ASCII_STRING) assert_equal ASCII_STRING, ascii.limit(ASCII_STRING.length) assert_equal '', ascii.limit(0) assert_equal 'o', ascii.limit(1) @@ -528,12 +526,12 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase end def test_limit_should_keep_under_the_specified_byte_limit - chars = UNICODE_STRING.mb_chars + example = chars(UNICODE_STRING) (1..UNICODE_STRING.length).each do |limit| - assert chars.limit(limit).to_s.length <= limit + assert example.limit(limit).to_s.length <= limit end end - + def test_composition_exclusion_is_set_up_properly # Normalization of DEVANAGARI LETTER QA breaks when composition exclusion isn't used correctly qa = [0x915, 0x93c].pack('U*') @@ -647,9 +645,9 @@ end class MultibyteInternalsTest < ActiveSupport::TestCase include MultibyteTestHelpers - + test "Chars translates a character offset to a byte offset" do - chars = "Puisque c'était son erreur, il m'a aidé".mb_chars + example = chars("Puisque c'était son erreur, il m'a aidé") [ [0, 0], [3, 3], @@ -657,7 +655,7 @@ class MultibyteInternalsTest < ActiveSupport::TestCase [14, 13], [41, 39] ].each do |byte_offset, character_offset| - assert_equal character_offset, chars.send(:translate_offset, byte_offset), + assert_equal character_offset, example.send(:translate_offset, byte_offset), "Expected byte offset #{byte_offset} to translate to #{character_offset}" end end -- cgit v1.2.3 From 0e64eab6a27bebdaaffa1ec10bbbd80bd8d73cb9 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Mon, 2 Nov 2009 22:10:02 +0100 Subject: Autoload Multibyte features. --- activesupport/lib/active_support/multibyte.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb index 6f2016a409..7e6f7d754b 100644 --- a/activesupport/lib/active_support/multibyte.rb +++ b/activesupport/lib/active_support/multibyte.rb @@ -4,6 +4,12 @@ require 'active_support/core_ext/module/attribute_accessors' module ActiveSupport #:nodoc: module Multibyte + autoload :EncodingError, 'active_support/multibyte/exceptions' + autoload :Chars, 'active_support/multibyte/chars' + autoload :UnicodeDatabase, 'active_support/multibyte/unicode_database' + autoload :Codepoint, 'active_support/multibyte/unicode_database' + autoload :UCD, 'active_support/multibyte/unicode_database' + # A list of all available normalization forms. See http://www.unicode.org/reports/tr15/tr15-29.html for more # information about normalization. NORMALIZATION_FORMS = [:c, :kc, :d, :kd] @@ -53,7 +59,4 @@ module ActiveSupport #:nodoc: end end -require 'active_support/multibyte/chars' -require 'active_support/multibyte/exceptions' -require 'active_support/multibyte/unicode_database' -require 'active_support/multibyte/utils' +require 'active_support/multibyte/utils' \ No newline at end of file -- cgit v1.2.3 From d64e87edd6d6362a18837f438123f9cd56b91f43 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 11:50:41 -0800 Subject: Try to remotely troubleshoot bundler issue in CI --- ci/ci_build.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index a6f8871f27..e5c632bd01 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -6,7 +6,7 @@ include FileUtils puts "[CruiseControl] Rails build" build_results = {} -root_dir = File.expand_path(File.dirname(__FILE__) + "/..") +root_dir = File.expand_path('../..', __FILE__) # Requires gem home and path to be writeable and/or overridden to be ~/.gem, # Will enable when RubyGems supports this properly (in a coming release) @@ -20,7 +20,7 @@ cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" puts - build_results[:bundle] = system 'rm -rf vendor && gem bundle' + build_results[:bundle] = system 'rm -rf vendor && gem --debug bundle' end cd "#{root_dir}/activesupport" do -- cgit v1.2.3 From 03dc66444e7c99701c0814f20ebcea64b1cc43ae Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 11:57:21 -0800 Subject: Add bundler 0.6.0 to CI geminstaller --- ci/geminstaller.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ci/geminstaller.yml b/ci/geminstaller.yml index 70729ea34a..a38221884b 100644 --- a/ci/geminstaller.yml +++ b/ci/geminstaller.yml @@ -27,3 +27,5 @@ gems: version: >= 1.2.2 - name: rubygems-update version: >= 1.3.3 +- name: bundler + version: >= 0.6.0 -- cgit v1.2.3 From 726a2fc8d26da0ab95d50ee57679d73bc762ba4d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 12:44:06 -0800 Subject: Give useful test:isolated failures --- actionpack/test/ts_isolated.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/test/ts_isolated.rb b/actionpack/test/ts_isolated.rb index 21d62f6aa7..5670d93613 100644 --- a/actionpack/test/ts_isolated.rb +++ b/actionpack/test/ts_isolated.rb @@ -10,8 +10,8 @@ class TestIsolated < Test::Unit::TestCase Dir["#{File.dirname(__FILE__)}/{abstract,controller,dispatch,template}/**/*_test.rb"].each do |file| define_method("test #{file}") do command = "#{ruby} -Ilib:test #{file}" - silence_stderr { `#{command}` } - assert_equal 0, $?.to_i, command + result = silence_stderr { `#{command}` } + assert_block("#{command}\n#{result}") { $?.to_i.zero? } end end end -- cgit v1.2.3 From d2d3464fcc8c230cc206cdb4d47f24c47ae6699d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 14:49:15 -0800 Subject: Turn off --debug for gem bundle. Force gem update. --- ci/ci_build.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index e5c632bd01..0ee952c00b 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -20,7 +20,7 @@ cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" puts - build_results[:bundle] = system 'rm -rf vendor && gem --debug bundle' + build_results[:bundle] = system 'rm -rf vendor && gem bundle --update' end cd "#{root_dir}/activesupport" do -- cgit v1.2.3 From 52e2bbd5c004f22b2affeec0fc03f1f9ca8c2a24 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 14:49:29 -0800 Subject: Ruby 1.9: work around constant resolution behavior change :( --- actionpack/test/abstract/helper_test.rb | 2 +- actionpack/test/dispatch/routing_test.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/actionpack/test/abstract/helper_test.rb b/actionpack/test/abstract/helper_test.rb index 6c28f01fa4..efcd68e5c8 100644 --- a/actionpack/test/abstract/helper_test.rb +++ b/actionpack/test/abstract/helper_test.rb @@ -40,7 +40,7 @@ module AbstractController class AbstractHelpersBlock < ControllerWithHelpers helper do - include HelperyTest + include ::AbstractController::Testing::HelperyTest end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 7917c1974b..ca07bc7a28 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -37,7 +37,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest get 'admin', :to => "queenbee#index" end - constraints IpRestrictor do + constraints ::TestRoutingMapper::IpRestrictor do get 'admin/accounts', :to => "queenbee#accounts" end @@ -80,7 +80,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end - match 'sprockets.js', :to => SprocketsApp + match 'sprockets.js', :to => ::TestRoutingMapper::SprocketsApp match 'people/:id/update', :to => 'people#update', :as => :update_person match '/projects/:project_id/people/:id/update', :to => 'people#update', :as => :update_project_person -- cgit v1.2.3 From 0ff8f81adcf1e025a34d4a50ea1db39384a00e0b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 15:00:19 -0800 Subject: Ruby 1.9: more constant lookup badness :( --- actionpack/test/controller/integration_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index d6e2a5a974..624b14e69b 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -390,7 +390,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest def with_test_route_set with_routing do |set| set.draw do |map| - match ':action', :to => IntegrationController + match ':action', :to => ::IntegrationProcessTest::IntegrationController end yield end -- cgit v1.2.3 From 425a02cecea188f502ad8f137271d1b90b9c7558 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 15:25:15 -0800 Subject: Ruby 1.9: resolve constant lookup issues --- actionpack/test/controller/helper_test.rb | 12 ++++++------ actionpack/test/controller/render_test.rb | 2 +- actionpack/test/controller/rescue_test.rb | 6 +++--- actionpack/test/controller/verification_test.rb | 2 +- actionpack/test/dispatch/request/json_params_parsing_test.rb | 2 +- .../test/dispatch/request/query_string_parsing_test.rb | 4 ++-- .../test/dispatch/request/url_encoded_params_parsing_test.rb | 2 +- actionpack/test/dispatch/request/xml_params_parsing_test.rb | 4 ++-- actionpack/test/dispatch/session/cookie_store_test.rb | 2 +- actionpack/test/dispatch/session/mem_cache_store_test.rb | 2 +- 10 files changed, 19 insertions(+), 19 deletions(-) diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 12539739aa..b9be163904 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -3,12 +3,6 @@ require 'active_support/core_ext/kernel/reporting' ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers' -class TestController < ActionController::Base - attr_accessor :delegate_attr - def delegate_method() end - def rescue_action(e) raise end -end - module Fun class GamesController < ActionController::Base def render_hello_world @@ -38,6 +32,12 @@ module LocalAbcHelper end class HelperTest < Test::Unit::TestCase + class TestController < ActionController::Base + attr_accessor :delegate_attr + def delegate_method() end + def rescue_action(e) raise end + end + def setup # Increment symbol counter. @symbol = (@@counter ||= 'A0').succ!.dup diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index ac8dad7c42..b32325fa20 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -860,7 +860,7 @@ class RenderTest < ActionController::TestCase # :ported: def test_access_to_controller_name_in_view get :accessing_controller_name_in_template - assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller. + assert_equal "test", @response.body # name is explicitly set in the controller. end # :ported: diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 2b1f532b8d..37367eaafc 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -343,9 +343,9 @@ class RescueTest < ActionController::IntegrationTest def with_test_routing with_routing do |set| set.draw do |map| - match 'foo', :to => TestController.action(:foo) - match 'invalid', :to => TestController.action(:invalid) - match 'b00m', :to => TestController.action(:b00m) + match 'foo', :to => ::RescueTest::TestController.action(:foo) + match 'invalid', :to => ::RescueTest::TestController.action(:invalid) + match 'b00m', :to => ::RescueTest::TestController.action(:b00m) end yield end diff --git a/actionpack/test/controller/verification_test.rb b/actionpack/test/controller/verification_test.rb index 63e8cf3e61..11d0d10897 100644 --- a/actionpack/test/controller/verification_test.rb +++ b/actionpack/test/controller/verification_test.rb @@ -126,7 +126,7 @@ class VerificationTest < ActionController::TestCase with_routing do |set| set.draw do |map| match 'foo', :to => 'test#foo', :as => :foo - match 'verification_test/:action', :to => TestController + match 'verification_test/:action', :to => ::VerificationTest::TestController end get :guarded_one_for_named_route_test, :two => "not one" assert_redirected_to '/foo' diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb index 3c2408de5f..d3308f73cc 100644 --- a/actionpack/test/dispatch/request/json_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb @@ -57,7 +57,7 @@ class JsonParamsParsingTest < ActionController::IntegrationTest def with_test_routing with_routing do |set| set.draw do |map| - match ':action', :to => TestController + match ':action', :to => ::JsonParamsParsingTest::TestController end yield end diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb index b764478d87..071d80c5b0 100644 --- a/actionpack/test/dispatch/request/query_string_parsing_test.rb +++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb @@ -109,12 +109,12 @@ class QueryStringParsingTest < ActionController::IntegrationTest def assert_parses(expected, actual) with_routing do |set| set.draw do |map| - match ':action', :to => TestController + match ':action', :to => ::QueryStringParsingTest::TestController end get "/parse", actual assert_response :ok - assert_equal(expected, TestController.last_query_parameters) + assert_equal(expected, ::QueryStringParsingTest::TestController.last_query_parameters) end end end diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb index e98a49980e..69dbd7f528 100644 --- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb @@ -130,7 +130,7 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest def with_test_routing with_routing do |set| set.draw do |map| - match ':action', :to => TestController + match ':action', :to => ::UrlEncodedParamsParsingTest::TestController end yield end diff --git a/actionpack/test/dispatch/request/xml_params_parsing_test.rb b/actionpack/test/dispatch/request/xml_params_parsing_test.rb index 0dc47ed9d5..96189e4ca2 100644 --- a/actionpack/test/dispatch/request/xml_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/xml_params_parsing_test.rb @@ -84,7 +84,7 @@ class XmlParamsParsingTest < ActionController::IntegrationTest def with_test_routing with_routing do |set| set.draw do |map| - match ':action', :to => TestController + match ':action', :to => ::XmlParamsParsingTest::TestController end yield end @@ -100,4 +100,4 @@ class LegacyXmlParamsParsingTest < XmlParamsParsingTest def default_headers {'HTTP_X_POST_DATA_FORMAT' => 'xml'} end -end \ No newline at end of file +end diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index edfc303d3d..ab7b9bc31b 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -219,7 +219,7 @@ class CookieStoreTest < ActionController::IntegrationTest def with_test_route_set(options = {}) with_routing do |set| set.draw do |map| - match ':action', :to => TestController + match ':action', :to => ::CookieStoreTest::TestController end options = {:key => SessionKey, :secret => SessionSecret}.merge(options) @app = ActionDispatch::Session::CookieStore.new(set, options) diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb index afc9d91d50..5a1dcb4dab 100644 --- a/actionpack/test/dispatch/session/mem_cache_store_test.rb +++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb @@ -112,7 +112,7 @@ class MemCacheStoreTest < ActionController::IntegrationTest def with_test_route_set with_routing do |set| set.draw do |map| - match ':action', :to => TestController + match ':action', :to => ::MemCacheStoreTest::TestController end @app = ActionDispatch::Session::MemCacheStore.new(set, :key => '_session_id') yield -- cgit v1.2.3 From dc1816da30eace9f292bfc57e21fe76a05ae8ea7 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 16:10:24 -0800 Subject: Ruby 1.9: fix number precision test --- actionpack/test/template/number_helper_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 85a97d570c..0a2b82bd89 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -88,7 +88,7 @@ class NumberHelperTest < ActionView::TestCase assert_equal("111.00", number_with_precision(111, :precision => 2)) assert_equal("111.235", number_with_precision("111.2346")) assert_equal("31.83", number_with_precision("31.825", :precision => 2)) - assert_equal("3268", number_with_precision((32.675 * 100.00), :precision => 0)) + assert_equal("3268", number_with_precision((32.6751 * 100.00), :precision => 0)) assert_equal("112", number_with_precision(111.50, :precision => 0)) assert_equal("1234567892", number_with_precision(1234567891.50, :precision => 0)) -- cgit v1.2.3 From a8ed10546d844fc15d87f5c8f168a18d0cdab5f0 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 4 Nov 2009 16:11:59 -0800 Subject: Ruby 1.9: don't assume params are US-ASCII. Hands off the encoding. --- actionpack/lib/action_dispatch/routing/route_set.rb | 7 ++++++- actionpack/test/controller/routing_test.rb | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 93617e826d..28e5b806da 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -20,7 +20,12 @@ module ActionDispatch params = env[PARAMETERS_KEY] merge_default_action!(params) split_glob_param!(params) if @glob_param - params.each { |key, value| params[key] = URI.unescape(value) if value.is_a?(String) } + params.each do |key, value| + if value.is_a?(String) + value = value.dup.force_encoding(Encoding::BINARY) if value.respond_to?(:force_encoding) + params[key] = URI.unescape(value) + end + end if env['action_controller.recognize'] [200, {}, params] diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 308e2a85b1..bb0b9247f3 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -450,6 +450,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo")) token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian + token.force_encoding(Encoding::BINARY) if token.respond_to?(:force_encoding) escaped_token = CGI::escape(token) assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token) -- cgit v1.2.3 From 6c59e5a558922b8f4084533071c3d93e151858ac Mon Sep 17 00:00:00 2001 From: Chris Hapgood Date: Wed, 4 Nov 2009 10:13:59 -0500 Subject: Fix OrderedHash#replace Signed-off-by: Michael Koziarski --- activesupport/lib/active_support/ordered_hash.rb | 7 +++++++ activesupport/test/ordered_hash_test.rb | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 4324e40cbb..b492648610 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -120,6 +120,13 @@ module ActiveSupport dup.merge!(other_hash) end + # When replacing with another hash, the initial order of our keys must come from the other hash -ordered or not. + def replace(other) + super + @keys = other.keys + self + end + def inspect "#" end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 15bd57181f..1521279437 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -191,4 +191,11 @@ class OrderedHashTest < Test::Unit::TestCase assert_equal "odd number of arguments for Hash", $!.message end end + + def test_replace_updates_keys + @other_ordered_hash = ActiveSupport::OrderedHash[:black, '000000', :white, '000000'] + original = @ordered_hash.replace(@other_ordered_hash) + assert_same original, @ordered_hash + assert_equal @other_ordered_hash.keys, @ordered_hash.keys + end end -- cgit v1.2.3 From 897164ddb70ed6f51b026e5c91f2bf3f7aa46ba6 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Mon, 2 Nov 2009 17:19:03 -0800 Subject: Conceptually unify instance & global initializers --- railties/lib/rails/application.rb | 45 ++++++++++----- railties/lib/rails/initializable.rb | 111 ++++++++++++++++-------------------- railties/lib/rails/plugin.rb | 99 ++++++++++++++++---------------- railties/test/initializable_test.rb | 72 +++++++++++++++++++---- 4 files changed, 192 insertions(+), 135 deletions(-) diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 242aea1842..b43dcb0041 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -1,6 +1,6 @@ module Rails class Application - extend Initializable + include Initializable class << self # Stub out App initialize @@ -8,6 +8,10 @@ module Rails new end + def new + @instance ||= super + end + def config @config ||= Configuration.new end @@ -27,23 +31,36 @@ module Rails config.root end - def routes - ActionController::Routing::Routes + def call(env) + new.call(env) end + end - def middleware - config.middleware - end + def initialize + run_initializers + end - def call(env) - @app ||= middleware.build(routes) - @app.call(env) - end + def config + self.class.config + end - def new - run_initializers - self - end + alias configuration config + + def plugin_loader + self.class.plugin_loader + end + + def middleware + config.middleware + end + + def routes + ActionController::Routing::Routes + end + + def call(env) + @app ||= middleware.build(routes) + @app.call(env) end initializer :initialize_rails do diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb index c491d5e012..93349454dd 100644 --- a/railties/lib/rails/initializable.rb +++ b/railties/lib/rails/initializable.rb @@ -1,93 +1,82 @@ module Rails module Initializable - def self.included(klass) - klass.instance_eval do - extend Rails::Initializable - extend Rails::Initializable::ClassMethodsWhenIncluded - include Rails::Initializable::InstanceMethodsWhenIncluded - end + def self.included(base) + base.extend ClassMethods end - def self.extended(klass) - klass.extend Initializer + Initializer = Struct.new(:name, :before, :after, :global, :block) do + alias global? global end class Collection < Array - def initialize(klasses) - klasses.each do |klass| - (klass.added_initializers || []).each do |initializer| - index = if initializer.before - index_for(initializer.before) - elsif initializer.after - index_for(initializer.after) + 1 - else - length - end - - insert(index, initializer) + def initialize(initializers = []) + super() + initializers.each do |initializer| + if initializer.before + index = index_for(initializer.before) + elsif initializer.after + index = index_for(initializer.after) + 1 + else + index = length end + insert(index || -1, initializer) end end - def index_for(name) - inst = find {|i| i.name == name } - inst && index(inst) + def +(other) + Collection.new(to_a + other.to_a) end + def index_for(name) + initializer = find { |i| i.name == name } + initializer && index(initializer) + end end - attr_reader :added_initializers - - # When you include Rails::Initializable, this method will be on instances - # of the class included into. When you extend it, it will be on the - # class or module itself. - # - # The #initializers method is set up to return the right list of - # initializers for the context in question. - def run_initializers - return if @_initialized - - initializers.each {|initializer| instance_eval(&initializer.block) } - - @_initialized = true + def run_initializers(*args) + return if @ran + self.class.initializers_for(:instance).each do |initializer| + instance_exec(*args, &initializer.block) + end + @ran = true end - module Initializer - Initializer = Struct.new(:name, :before, :after, :block, :global) - - def all_initializers - klasses = ancestors.select {|klass| klass.is_a?(Initializable) }.reverse - initializers = Collection.new(klasses) + module ClassMethods + def initializers + @initializers ||= [] end - alias initializers all_initializers - - def initializer(name, options = {}, &block) - @added_initializers ||= [] - @added_initializers << - Initializer.new(name, options[:before], options[:after], block, options[:global]) + def initializers_for(scope = :global) + initializers = Collection.new + ancestors.reverse_each do |klass| + next unless klass.respond_to?(:initializers) + initializers = initializers + klass.initializers.select { |i| + (scope == :global) == !!i.global? + } + end + initializers end - end - module ClassMethodsWhenIncluded - def initializers - all_initializers.select {|i| i.global == true } + def initializer(name, opts = {}, &blk) + @initializers ||= [] + @initializers << Initializer.new(name, opts[:before], opts[:after], opts[:global], blk) end - end - - module InstanceMethodsWhenIncluded - def initializers - self.class.all_initializers.reject {|i| i.global == true } + def run_initializers(*args) + return if @ran + initializers_for(:global).each do |initializer| + instance_exec(*args, &initializer.block) + end + @ran = true end end end - extend Initializable + include Initializable # Check for valid Ruby version (1.8.2 or 1.8.4 or higher). This is done in an # external file, so we can use it from the `rails` program as well without duplication. - initializer :check_ruby_version do + initializer :check_ruby_version, :global => true do require 'rails/ruby_version_check' end @@ -97,7 +86,7 @@ module Rails # on ActionController::Base. # # For Ruby 1.9, UTF-8 is the default internal and external encoding. - initializer :initialize_encoding do + initializer :initialize_encoding, :global => true do if RUBY_VERSION < '1.9' $KCODE='u' else diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 1c0af6411a..090ec6e4cb 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -18,6 +18,7 @@ module Rails # plugin.about["url"] # => "http://interblah.net" class Plugin include Comparable + include Initializable attr_reader :directory, :name @@ -99,67 +100,69 @@ module Rails def locale_files Dir[ File.join(locale_path, '*.{rb,yml}') ] end - - private - def load_about_information - about_yml_path = File.join(@directory, "about.yml") - parsed_yml = File.exist?(about_yml_path) ? YAML.load(File.read(about_yml_path)) : {} - parsed_yml || {} - rescue Exception - {} - end + private + def load_about_information + about_yml_path = File.join(@directory, "about.yml") + parsed_yml = File.exist?(about_yml_path) ? YAML.load(File.read(about_yml_path)) : {} + parsed_yml || {} + rescue Exception + {} + end - def report_nonexistant_or_empty_plugin! - raise LoadError, "Can not find the plugin named: #{name}" - end + def report_nonexistant_or_empty_plugin! + raise LoadError, "Can not find the plugin named: #{name}" + end - - def app_paths - [ File.join(directory, 'app', 'models'), File.join(directory, 'app', 'helpers'), controller_path, metal_path ] - end - - def lib_path - File.join(directory, 'lib') - end + def app_paths + [ File.join(directory, 'app', 'models'), File.join(directory, 'app', 'helpers'), controller_path, metal_path ] + end - def classic_init_path - File.join(directory, 'init.rb') - end + def lib_path + File.join(directory, 'lib') + end - def gem_init_path - File.join(directory, 'rails', 'init.rb') - end + def classic_init_path + File.join(directory, 'init.rb') + end - def init_path - File.file?(gem_init_path) ? gem_init_path : classic_init_path - end + def gem_init_path + File.join(directory, 'rails', 'init.rb') + end + def init_path + File.file?(gem_init_path) ? gem_init_path : classic_init_path + end - def has_app_directory? - File.directory?(File.join(directory, 'app')) - end + def has_app_directory? + File.directory?(File.join(directory, 'app')) + end - def has_lib_directory? - File.directory?(lib_path) - end + def has_lib_directory? + File.directory?(lib_path) + end - def has_init_file? - File.file?(init_path) - end + def has_init_file? + File.file?(init_path) + end + def evaluate_init_rb(initializer) + if has_init_file? + require 'active_support/core_ext/kernel/reporting' + silence_warnings do + # Allow plugins to reference the current configuration object + config = initializer.configuration - def evaluate_init_rb(initializer) - if has_init_file? - require 'active_support/core_ext/kernel/reporting' - silence_warnings do - # Allow plugins to reference the current configuration object - config = initializer.configuration - - eval(IO.read(init_path), binding, init_path) - end + eval(IO.read(init_path), binding, init_path) end - end + end + end + + class Vendored < Plugin + initializer :init_rb do |application| + evaluate_init_rb(application) + end + end end # This Plugin subclass represents a Gem plugin. Although RubyGems has already diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb index f7237e69cc..463fdc03c0 100644 --- a/railties/test/initializable_test.rb +++ b/railties/test/initializable_test.rb @@ -4,59 +4,59 @@ require 'rails/initializable' module InitializableTests class Foo - extend Rails::Initializable + include Rails::Initializable class << self attr_accessor :foo, :bar end - initializer :omg do + initializer :omg, :global => true do @foo ||= 0 @foo += 1 end end class Bar < Foo - initializer :bar do + initializer :bar, :global => true do @bar ||= 0 @bar += 1 end end module Word - extend Rails::Initializable + include Rails::Initializable - initializer :word do + initializer :word, :global => true do $word = "bird" end end class Parent - extend Rails::Initializable + include Rails::Initializable - initializer :one do + initializer :one, :global => true do $arr << 1 end - initializer :two do + initializer :two, :global => true do $arr << 2 end end class Child < Parent - extend Rails::Initializable + include Rails::Initializable - initializer :three, :before => :one do + initializer :three, :before => :one, :global => true do $arr << 3 end - initializer :four, :after => :one do + initializer :four, :after => :one, :global => true do $arr << 4 end end class Parent - initializer :five, :before => :one do + initializer :five, :before => :one, :global => true do $arr << 5 end end @@ -81,6 +81,38 @@ module InitializableTests end end + class WithArgs + include Rails::Initializable + + initializer :foo do |arg| + $with_arg = arg + end + end + + class OverriddenInitializer + class MoreInitializers + include Rails::Initializable + + initializer :startup, :before => :last do + $arr << 2 + end + end + + include Rails::Initializable + + initializer :first do + $arr << 1 + end + + initializer :last do + $arr << 3 + end + + def self.initializers + super + MoreInitializers.initializers + end + end + class Basic < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation @@ -140,4 +172,20 @@ module InitializableTests assert_equal [3, 4], $arr end end + + class WithArgsTest < ActiveSupport::TestCase + test "running initializers with args" do + $with_arg = nil + WithArgs.new.run_initializers('foo') + assert_equal 'foo', $with_arg + end + end + + class OverriddenInitializerTest < ActiveSupport::TestCase + test "merges in the initializers from the parent in the right order" do + $arr = [] + OverriddenInitializer.new.run_initializers + assert_equal [1, 2, 3], $arr + end + end end \ No newline at end of file -- cgit v1.2.3 From 43694269934540de2a73130d7ff47bd1a25ed3e4 Mon Sep 17 00:00:00 2001 From: Yehuda Katz + Carl Lerche Date: Thu, 5 Nov 2009 14:45:53 -0800 Subject: Add the ability to merge initializers from various objects in order. --- railties/lib/rails/initializable.rb | 42 +++++++++++++++++++++++++++++++++---- railties/test/initializable_test.rb | 8 +++++-- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb index 93349454dd..d78eab9a75 100644 --- a/railties/lib/rails/initializable.rb +++ b/railties/lib/rails/initializable.rb @@ -4,8 +4,35 @@ module Rails base.extend ClassMethods end - Initializer = Struct.new(:name, :before, :after, :global, :block) do + class Initializer + attr_reader :name, :before, :after, :global, :block + + def initialize(name, context, options, &block) + @name, @context, @options, @block = name, context, options, block + end + + def before + @options[:before] + end + + def after + @options[:after] + end + + def global + @options[:global] + end + alias global? global + + def run(*args) + @context.instance_exec(*args, &block) + end + + def bind(context) + return self if @context + Initializer.new(@name, context, @options, &block) + end end class Collection < Array @@ -35,12 +62,19 @@ module Rails def run_initializers(*args) return if @ran - self.class.initializers_for(:instance).each do |initializer| - instance_exec(*args, &initializer.block) + initializers.each do |initializer| + initializer.run(*args) end @ran = true end + def initializers + @initializers ||= begin + initializers = self.class.initializers_for(:instance) + Collection.new(initializers.map { |i| i.bind(self) }) + end + end + module ClassMethods def initializers @initializers ||= [] @@ -59,7 +93,7 @@ module Rails def initializer(name, opts = {}, &blk) @initializers ||= [] - @initializers << Initializer.new(name, opts[:before], opts[:after], opts[:global], blk) + @initializers << Initializer.new(name, nil, opts, &blk) end def run_initializers(*args) diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb index 463fdc03c0..2920883132 100644 --- a/railties/test/initializable_test.rb +++ b/railties/test/initializable_test.rb @@ -94,7 +94,11 @@ module InitializableTests include Rails::Initializable initializer :startup, :before => :last do - $arr << 2 + $arr << two + end + + def two + 2 end end @@ -109,7 +113,7 @@ module InitializableTests end def self.initializers - super + MoreInitializers.initializers + super + MoreInitializers.new.initializers end end -- cgit v1.2.3 From b0dfd1d19b83f1812317345a68c6bc1ad590be53 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Thu, 5 Nov 2009 15:37:01 -0800 Subject: Update Ruby version check to 1.8.7 --- railties/lib/rails/ruby_version_check.rb | 11 ++------- .../test/initializer/check_ruby_version_test.rb | 28 ++++++++++++++-------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index 68d3acc876..62d7804bf3 100644 --- a/railties/lib/rails/ruby_version_check.rb +++ b/railties/lib/rails/ruby_version_check.rb @@ -1,13 +1,6 @@ -min_release = "1.8.2 (2004-12-25)" +min_release = "1.8.7" ruby_release = "#{RUBY_VERSION} (#{RUBY_RELEASE_DATE})" -if ruby_release =~ /1\.8\.3/ - abort <<-end_message - - Rails does not work with Ruby version 1.8.3. - Please upgrade to version 1.8.4 or downgrade to 1.8.2. - - end_message -elsif ruby_release < min_release +if ruby_release < min_release abort <<-end_message Rails requires Ruby version #{min_release} or later. diff --git a/railties/test/initializer/check_ruby_version_test.rb b/railties/test/initializer/check_ruby_version_test.rb index cf956e68fb..97d884e1be 100644 --- a/railties/test/initializer/check_ruby_version_test.rb +++ b/railties/test/initializer/check_ruby_version_test.rb @@ -14,24 +14,32 @@ module InitializerTests assert_rails_does_not_boot "1.8.1" end - test "rails initializes with ruby version 1.8.2" do - assert_rails_boots "1.8.2" + test "rails does not initialize with ruby version 1.8.2" do + assert_rails_does_not_boot "1.8.2" end test "rails does not initialize with ruby version 1.8.3" do assert_rails_does_not_boot "1.8.3" end - test "rails initializes with ruby version 1.8.4" do - assert_rails_boots "1.8.4" + test "rails does not initialize with ruby version 1.8.4" do + assert_rails_does_not_boot "1.8.4" end - test "rails initializes with ruby version 1.8.5" do - assert_rails_boots "1.8.5" + test "rails does not initializes with ruby version 1.8.5" do + assert_rails_does_not_boot "1.8.5" end - test "rails initializes with ruby version 1.8.6" do - assert_rails_boots "1.8.6" + test "rails does not initialize with ruby version 1.8.6" do + assert_rails_does_not_boot "1.8.6" + end + + test "rails initializes with ruby version 1.8.7" do + assert_rails_boots "1.8.7" + end + + test "rails initializes with the current version of Ruby" do + assert_rails_boots end def set_ruby_version(version) @@ -39,8 +47,8 @@ module InitializerTests Object.const_set(:RUBY_VERSION, version.freeze) end - def assert_rails_boots(version) - set_ruby_version(version) + def assert_rails_boots(version = nil) + set_ruby_version(version) if version assert_nothing_raised "It appears that rails does not boot" do Rails::Initializer.run { |c| c.frameworks = [] } Rails.initialize! -- cgit v1.2.3 From b12f194c396b5d279986dd16a3b2caa360e64d19 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Thu, 5 Nov 2009 15:38:04 -0800 Subject: Update AC::Middleware to play better with the normal AC::Metal stack. This required stopping to use #call for non-rack-related stuff --- actionpack/lib/action_controller/metal.rb | 6 ++-- .../action_controller/metal/rack_convenience.rb | 2 +- actionpack/lib/action_controller/middleware.rb | 40 +++++++++++----------- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 6f89bf5d67..60b3f9a89b 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -49,7 +49,7 @@ module ActionController # and response object available. You might wish to control the # environment and response manually for performance reasons. - attr_internal :status, :headers, :content_type, :app, :response + attr_internal :status, :headers, :content_type, :response def initialize(*) @_headers = {} @@ -69,7 +69,7 @@ module ActionController end # :api: private - def call(name, env) + def dispatch(name, env) @_env = env process(name) to_a @@ -95,7 +95,7 @@ module ActionController end def call(env) - controller = @controller.new.call(@action, env) + @controller.new.dispatch(@action, env) end end diff --git a/actionpack/lib/action_controller/metal/rack_convenience.rb b/actionpack/lib/action_controller/metal/rack_convenience.rb index a80569c530..131d20114d 100644 --- a/actionpack/lib/action_controller/metal/rack_convenience.rb +++ b/actionpack/lib/action_controller/metal/rack_convenience.rb @@ -8,7 +8,7 @@ module ActionController attr_internal :request end - def call(name, env) + def dispatch(action, env) @_request = ActionDispatch::Request.new(env) @_response = ActionDispatch::Response.new @_response.request = request diff --git a/actionpack/lib/action_controller/middleware.rb b/actionpack/lib/action_controller/middleware.rb index fac0ed2645..17275793b7 100644 --- a/actionpack/lib/action_controller/middleware.rb +++ b/actionpack/lib/action_controller/middleware.rb @@ -1,34 +1,34 @@ module ActionController class Middleware < Metal class ActionMiddleware - def initialize(controller) - @controller = controller + def initialize(controller, app) + @controller, @app = controller, app end def call(env) - controller = @controller.allocate - controller.send(:initialize) - controller.app = @app - controller._call(env) + @controller.build(@app).dispatch(:index, env) end + end + + class << self + alias build new - def app=(app) - @app = app + def new(app) + ActionMiddleware.new(self, app) end end - - def self.new(app) - middleware = ActionMiddleware.new(self) - middleware.app = app - middleware + + attr_internal :app + + def process(action) + response = super + self.status, self.headers, self.response_body = response if response.is_a?(Array) + response end - - def _call(env) - @_env = env - @_request = ActionDispatch::Request.new(env) - @_response = ActionDispatch::Response.new - @_response.request = @_request - process(:index) + + def initialize(app) + super() + @_app = app end def index -- cgit v1.2.3 From 73a36b599ae21d444d3b1f4114306a80b37ec8d4 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 5 Nov 2009 16:04:05 -0800 Subject: Shush --- actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb index ab1a828471..0ddc525213 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb @@ -43,6 +43,7 @@ module Racc class Parser + old_verbose, $VERBOSE = $VERBOSE, nil Racc_Runtime_Version = '1.4.5' Racc_Runtime_Revision = '$Revision: 1.7 $'.split[1] @@ -71,6 +72,7 @@ module Racc Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R Racc_Runtime_Type = 'ruby' end + $VERBOSE = old_verbose def Parser.racc_runtime_type Racc_Runtime_Type -- cgit v1.2.3 From 60911c39336fea92536f78a4deb6b52535b613cd Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 5 Nov 2009 16:04:43 -0800 Subject: Ruby 1.9: Rack apps must *always* take an env arg on 1.9 --- railties/test/metal_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/test/metal_test.rb b/railties/test/metal_test.rb index 6864254e4c..2256b191e2 100644 --- a/railties/test/metal_test.rb +++ b/railties/test/metal_test.rb @@ -85,7 +85,7 @@ class MetalTest < Test::Unit::TestCase private def app - lambda{[402,{},["End of the Line"]]} + lambda{|env|[402,{},["End of the Line"]]} end def use_appdir(root) -- cgit v1.2.3 From 1c047be0fc06c74d4b5b9e1682c79749f47109f5 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 5 Nov 2009 16:11:08 -0800 Subject: If class doesn't have a name, there's no implied layout name, so don't set up a _layout method --- actionpack/lib/abstract_controller/layouts.rb | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 8293e79b0a..1616f8030a 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -89,7 +89,7 @@ module AbstractController # ==== Returns # String:: A template name def _implied_layout_name - name.underscore + name && name.underscore end # Takes the specified layout and creates a _layout method to be called @@ -119,17 +119,19 @@ module AbstractController when true raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" when nil - self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def _layout(details) - self.class.cache_layout(details) do - if template_exists?("#{_implied_layout_name}", details, :_prefix => "layouts") - "#{_implied_layout_name}" - else - super + if name + self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def _layout(details) + self.class.cache_layout(details) do + if template_exists?("#{_implied_layout_name}", details, :_prefix => "layouts") + "#{_implied_layout_name}" + else + super + end end end - end - RUBY + RUBY + end end self.class_eval { private :_layout } end -- cgit v1.2.3 From cb9a1759c0b8ad104b8e591b952bc440f9e06dc0 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 5 Nov 2009 16:11:52 -0800 Subject: Fix generators tests that expect a class name --- railties/lib/rails/generators/base.rb | 17 ++++++++++------- railties/test/generators_test.rb | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index e6baf2fc79..af1bf26f4a 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -211,9 +211,8 @@ module Rails # def self.inherited(base) #:nodoc: super - base.source_root # Cache source root - if Rails.root && base.name !~ /Base$/ + if base.name && base.name !~ /Base$/ && defined?(Rails.root) && Rails.root path = File.expand_path(File.join(Rails.root, 'lib', 'templates')) if base.name.include?('::') base.source_paths << File.join(path, base.base_name, base.generator_name) @@ -273,17 +272,21 @@ module Rails # Sets the base_name taking into account the current class namespace. # def self.base_name - @base_name ||= self.name.split('::').first.underscore + if name + @base_name ||= name.split('::').first.underscore + end end # Removes the namespaces and get the generator name. For example, # Rails::Generators::MetalGenerator will return "metal" as generator name. # def self.generator_name - @generator_name ||= begin - klass_name = self.name.split('::').last - klass_name.sub!(/Generator$/, '') - klass_name.underscore + if name + @generator_name ||= begin + klass_name = name.to_s.split('::').last + klass_name.sub!(/Generator$/, '') + klass_name.underscore + end end end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 07f51eca01..9c9a4e6016 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -1,4 +1,4 @@ -require File.join(File.dirname(__FILE__), 'generators', 'generators_test_helper') +require 'generators/generators_test_helper' require 'rails/generators/rails/model/model_generator' require 'rails/generators/test_unit/model/model_generator' require 'mocha' -- cgit v1.2.3 From cbded53671bccccbaf7e9fdfa93ef86cb097daa3 Mon Sep 17 00:00:00 2001 From: Nathan Weizenbaum Date: Thu, 5 Nov 2009 20:07:14 -0800 Subject: When rendering layouts with blocks, use #capture to avoid assuming that the return value is the block's content. Signed-off-by: Yehuda Katz --- actionpack/lib/action_view/render/rendering.rb | 6 ++---- actionpack/test/fixtures/layouts/block_with_layout.erb | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb index fc89726670..7006a5b968 100644 --- a/actionpack/lib/action_view/render/rendering.rb +++ b/actionpack/lib/action_view/render/rendering.rb @@ -71,12 +71,10 @@ module ActionView # In this case, the layout would receive the block passed into render :layout, # and the Struct specified in the layout would be passed into the block. The result # would be Hello David. - def _layout_for(name = nil) + def _layout_for(name = nil, &block) return @_content_for[name || :layout] if !block_given? || name - with_output_buffer do - return yield - end + capture(&block) end def _render_inline(inline, layout, options) diff --git a/actionpack/test/fixtures/layouts/block_with_layout.erb b/actionpack/test/fixtures/layouts/block_with_layout.erb index 6a8b41914b..f25b41271d 100644 --- a/actionpack/test/fixtures/layouts/block_with_layout.erb +++ b/actionpack/test/fixtures/layouts/block_with_layout.erb @@ -1,3 +1,3 @@ -<% render(:layout => "layout_for_partial", :locals => { :name => "Anthony" }) do %>Inside from first block in layout<% end %> +<% render(:layout => "layout_for_partial", :locals => { :name => "Anthony" }) do %>Inside from first block in layout<% "Return value should be discarded" %><% end %> <%= yield %> <% render(:layout => "layout_for_partial", :locals => { :name => "Ramm" }) do %>Inside from second block in layout<% end %> -- cgit v1.2.3 From b43964d6061f4a31320906172f763dd3dd188f4d Mon Sep 17 00:00:00 2001 From: Chris Hapgood Date: Fri, 6 Nov 2009 16:25:11 -0500 Subject: Make some assertions in the ActionView::TestCase tests actually do something. [#3468 state:resolved] Signed-off-by: Eloy Duran --- actionpack/test/template/test_case_test.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index ca72c13ffa..37dcb86d80 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -24,7 +24,7 @@ module ActionView test_case.class_eval do test "helpers defined on ActionView::TestCase are available" do assert test_case.ancestors.include?(ASharedTestHelper) - assert 'Holla!', from_shared_helper + assert_equal 'Holla!', from_shared_helper end end end @@ -41,7 +41,7 @@ module ActionView helper AnotherTestHelper test "additional helper classes can be specified as in a controller" do assert test_case.ancestors.include?(AnotherTestHelper) - assert 'Howdy!', from_another_helper + assert_equal 'Howdy!', from_another_helper end end @@ -58,14 +58,14 @@ module ActionView helper AnotherTestHelper test "additional helper classes can be specified as in a controller" do assert test_case.ancestors.include?(AnotherTestHelper) - assert 'Howdy!', from_another_helper + assert_equal 'Howdy!', from_another_helper test_case.helper_class.module_eval do def render_from_helper from_another_helper end end - assert 'Howdy!', render(:partial => 'test/from_helper') + assert_equal 'Howdy!', render(:partial => 'test/from_helper') end end -- cgit v1.2.3 From c2cfb201984f8dff2b3534163b6145fe2560eb80 Mon Sep 17 00:00:00 2001 From: Chris Hapgood Date: Fri, 6 Nov 2009 17:02:55 -0500 Subject: Share ActionView::TestCase's output_buffer with view for concat support. [#3467 state:resolved] Signed-off-by: Eloy Duran --- actionpack/lib/action_view/test_case.rb | 1 + actionpack/test/template/test_case_test.rb | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index 8beda24aba..86bbad822d 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -120,6 +120,7 @@ module ActionView def _view view = ActionView::Base.new(ActionController::Base.view_paths, _assigns, @controller) view.class.send :include, _helpers + view.output_buffer = self.output_buffer view end diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index 37dcb86d80..05a409d05a 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -38,6 +38,11 @@ module ActionView assert_equal 'Eloy', render('developers/developer', :developer => stub(:name => 'Eloy')) end + test "can render a layout with block" do + assert_equal "Before (ChrisCruft)\n!\nAfter", + render(:layout => "test/layout_for_partial", :locals => {:name => "ChrisCruft"}) {"!"} + end + helper AnotherTestHelper test "additional helper classes can be specified as in a controller" do assert test_case.ancestors.include?(AnotherTestHelper) -- cgit v1.2.3 From f125a34501e21b1e0da2b80d149df7a739482804 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Fri, 6 Nov 2009 23:53:33 +0100 Subject: Define autosave association callbacks when using accepts_nested_attributes_for. This way we don't define all the validation methods for all associations by default, but only when needed. [#3355 state:resolved] --- activerecord/lib/active_record/nested_attributes.rb | 2 ++ activerecord/test/models/pirate.rb | 2 +- activerecord/test/models/ship.rb | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index edcf547e01..ca3110a374 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -250,6 +250,8 @@ module ActiveRecord assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes) end }, __FILE__, __LINE__ + + add_autosave_association_callbacks(reflection) else raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?" end diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index 05c5b666ae..f2c05dd48f 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -18,7 +18,7 @@ class Pirate < ActiveRecord::Base has_many :treasure_estimates, :through => :treasures, :source => :price_estimates # These both have :autosave enabled because accepts_nested_attributes_for is used on them. - has_one :ship, :validate => true + has_one :ship has_one :non_validated_ship, :class_name => 'Ship' has_many :birds has_many :birds_with_method_callbacks, :class_name => "Bird", diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb index d0df951622..06759d64b8 100644 --- a/activerecord/test/models/ship.rb +++ b/activerecord/test/models/ship.rb @@ -1,7 +1,7 @@ class Ship < ActiveRecord::Base self.record_timestamps = false - belongs_to :pirate, :validate => true + belongs_to :pirate has_many :parts, :class_name => 'ShipPart', :autosave => true accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } -- cgit v1.2.3 From e1b5e3cc709df12d2d8495737e524f60015e6f5c Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 7 Nov 2009 11:23:21 -0800 Subject: Break up inflector to reduce the dependency burden on dependency-les methods like constantize. --- actionpack/lib/action_dispatch/http/request.rb | 1 + actionpack/lib/action_dispatch/middleware/stack.rb | 6 +- .../lib/active_support/core_ext/string/access.rb | 2 + activesupport/lib/active_support/inflector.rb | 411 +-------------------- .../lib/active_support/inflector/inflections.rb | 213 +++++++++++ .../lib/active_support/inflector/methods.rb | 139 +++++++ .../lib/active_support/inflector/transliterate.rb | 61 +++ 7 files changed, 424 insertions(+), 409 deletions(-) create mode 100644 activesupport/lib/active_support/inflector/inflections.rb create mode 100644 activesupport/lib/active_support/inflector/methods.rb create mode 100644 activesupport/lib/active_support/inflector/transliterate.rb diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 75be2cc260..9314ff5c53 100755 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -6,6 +6,7 @@ require 'active_support/memoizable' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/object/tap' +require 'active_support/core_ext/string/access' module ActionDispatch class Request < Rack::Request diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 4f71ea6165..3b27309f58 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -1,3 +1,5 @@ +require "active_support/inflector/methods" + module ActionDispatch class MiddlewareStack < Array class Middleware @@ -32,7 +34,7 @@ module ActionDispatch elsif @klass.respond_to?(:call) @klass.call else - @klass.to_s.constantize + ActiveSupport::Inflector.constantize(@klass.to_s) end end @@ -53,7 +55,7 @@ module ActionDispatch when Class klass == middleware else - klass == middleware.to_s.constantize + klass == ActiveSupport::Inflector.constantize(middleware.to_s) end end diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index 57385d86d2..182b3e745d 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -1,3 +1,5 @@ +require "active_support/multibyte" + class String unless '1.9'.respond_to?(:force_encoding) # Returns the character at the +position+ treating the string as an array (where 0 is the first character). diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 67aea2782f..215a60eba7 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -1,410 +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 - # The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, - # and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept - # in inflections.rb. - # - # The Rails core team has stated patches for the inflections library will not be accepted - # in order to avoid breaking legacy applications which may be relying on errant inflections. - # If you discover an incorrect inflection and require it for your application, you'll need - # to correct it yourself (explained below). - module Inflector - extend self - - # A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional - # inflection rules. Examples: - # - # ActiveSupport::Inflector.inflections do |inflect| - # inflect.plural /^(ox)$/i, '\1\2en' - # inflect.singular /^(ox)en/i, '\1' - # - # inflect.irregular 'octopus', 'octopi' - # - # inflect.uncountable "equipment" - # end - # - # New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the - # pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may - # already have been loaded. - class Inflections - def self.instance - @__instance__ ||= new - end - - attr_reader :plurals, :singulars, :uncountables, :humans - - def initialize - @plurals, @singulars, @uncountables, @humans = [], [], [], [] - end - - # Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. - # The replacement should always be a string that may include references to the matched data from the rule. - def plural(rule, replacement) - @uncountables.delete(rule) if rule.is_a?(String) - @uncountables.delete(replacement) - @plurals.insert(0, [rule, replacement]) - end - - # Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. - # The replacement should always be a string that may include references to the matched data from the rule. - def singular(rule, replacement) - @uncountables.delete(rule) if rule.is_a?(String) - @uncountables.delete(replacement) - @singulars.insert(0, [rule, replacement]) - end - - # Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used - # for strings, not regular expressions. You simply pass the irregular in singular and plural form. - # - # Examples: - # irregular 'octopus', 'octopi' - # irregular 'person', 'people' - def irregular(singular, plural) - @uncountables.delete(singular) - @uncountables.delete(plural) - if singular[0,1].upcase == plural[0,1].upcase - plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1]) - plural(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + plural[1..-1]) - singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1]) - else - plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1]) - plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1]) - plural(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), plural[0,1].upcase + plural[1..-1]) - plural(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), plural[0,1].downcase + plural[1..-1]) - singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1]) - singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1]) - end - end - - # Add uncountable words that shouldn't be attempted inflected. - # - # Examples: - # uncountable "money" - # uncountable "money", "information" - # uncountable %w( money information rice ) - def uncountable(*words) - (@uncountables << words).flatten! - end - - # Specifies a humanized form of a string by a regular expression rule or by a string mapping. - # When using a regular expression based replacement, the normal humanize formatting is called after the replacement. - # When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name') - # - # Examples: - # human /_cnt$/i, '\1_count' - # human "legacy_col_person_name", "Name" - def human(rule, replacement) - @humans.insert(0, [rule, replacement]) - end - - # Clears the loaded inflections within a given scope (default is :all). - # Give the scope as a symbol of the inflection type, the options are: :plurals, - # :singulars, :uncountables, :humans. - # - # Examples: - # clear :all - # clear :plurals - def clear(scope = :all) - case scope - when :all - @plurals, @singulars, @uncountables = [], [], [] - else - instance_variable_set "@#{scope}", [] - end - end - end - - # Yields a singleton instance of Inflector::Inflections so you can specify additional - # inflector rules. - # - # Example: - # ActiveSupport::Inflector.inflections do |inflect| - # inflect.uncountable "rails" - # end - def inflections - if block_given? - yield Inflections.instance - else - Inflections.instance - end - end - - # Returns the plural form of the word in the string. - # - # Examples: - # "post".pluralize # => "posts" - # "octopus".pluralize # => "octopi" - # "sheep".pluralize # => "sheep" - # "words".pluralize # => "words" - # "CamelOctopus".pluralize # => "CamelOctopi" - def pluralize(word) - result = word.to_s.dup - - if word.empty? || inflections.uncountables.include?(result.downcase) - result - else - inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } - result - end - end - - # The reverse of +pluralize+, returns the singular form of a word in a string. - # - # Examples: - # "posts".singularize # => "post" - # "octopi".singularize # => "octopus" - # "sheep".singularize # => "sheep" - # "word".singularize # => "word" - # "CamelOctopi".singularize # => "CamelOctopus" - def singularize(word) - result = word.to_s.dup - - if inflections.uncountables.include?(result.downcase) - result - else - inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } - result - end - end - - # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+ - # is set to :lower then +camelize+ produces lowerCamelCase. - # - # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces. - # - # Examples: - # "active_record".camelize # => "ActiveRecord" - # "active_record".camelize(:lower) # => "activeRecord" - # "active_record/errors".camelize # => "ActiveRecord::Errors" - # "active_record/errors".camelize(:lower) # => "activeRecord::Errors" - def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) - if first_letter_in_uppercase - lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } - else - lower_case_and_underscored_word.to_s.first.downcase + camelize(lower_case_and_underscored_word)[1..-1] - end - end - - # Capitalizes all the words and replaces some characters in the string to create - # a nicer looking title. +titleize+ is meant for creating pretty output. It is not - # used in the Rails internals. - # - # +titleize+ is also aliased as as +titlecase+. - # - # Examples: - # "man from the boondocks".titleize # => "Man From The Boondocks" - # "x-men: the last stand".titleize # => "X Men: The Last Stand" - def titleize(word) - humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize } - end - - # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string. - # - # Changes '::' to '/' to convert namespaces to paths. - # - # Examples: - # "ActiveRecord".underscore # => "active_record" - # "ActiveRecord::Errors".underscore # => active_record/errors - def underscore(camel_cased_word) - camel_cased_word.to_s.gsub(/::/, '/'). - gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). - gsub(/([a-z\d])([A-Z])/,'\1_\2'). - tr("-", "_"). - downcase - end - - # Replaces underscores with dashes in the string. - # - # Example: - # "puni_puni" # => "puni-puni" - def dasherize(underscored_word) - underscored_word.gsub(/_/, '-') - end - - # Capitalizes the first word and turns underscores into spaces and strips a - # trailing "_id", if any. Like +titleize+, this is meant for creating pretty output. - # - # Examples: - # "employee_salary" # => "Employee salary" - # "author_id" # => "Author" - def humanize(lower_case_and_underscored_word) - result = lower_case_and_underscored_word.to_s.dup - - inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } - result.gsub(/_id$/, "").gsub(/_/, " ").capitalize - end - - # Removes the module part from the expression in the string. - # - # Examples: - # "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections" - # "Inflections".demodulize # => "Inflections" - def demodulize(class_name_in_module) - class_name_in_module.to_s.gsub(/^.*::/, '') - end - - # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. - # - # ==== Examples - # - # class Person - # def to_param - # "#{id}-#{name.parameterize}" - # end - # end - # - # @person = Person.find(1) - # # => # - # - # <%= link_to(@person.name, person_path(@person)) %> - # # => Donald E. Knuth - def parameterize(string, sep = '-') - # replace accented chars with their ascii equivalents - parameterized_string = transliterate(string) - # Turn unwanted chars into the separator - parameterized_string.gsub!(/[^a-z0-9\-_\+]+/i, sep) - unless sep.blank? - re_sep = Regexp.escape(sep) - # No more than one of the separator in a row. - parameterized_string.gsub!(/#{re_sep}{2,}/, sep) - # Remove leading/trailing separator. - parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '') - end - parameterized_string.downcase - end - - - # Replaces accented characters with their ascii equivalents. - def transliterate(string) - Iconv.iconv('ascii//ignore//translit', 'utf-8', string).to_s - end - - if RUBY_VERSION >= '1.9' - undef_method :transliterate - def transliterate(string) - warn "Ruby 1.9 doesn't support Unicode normalization yet" - string.dup - end - - # The iconv transliteration code doesn't function correctly - # on some platforms, but it's very fast where it does function. - elsif "foo" != (Inflector.transliterate("föö") rescue nil) - undef_method :transliterate - def transliterate(string) - string.mb_chars.normalize(:kd). # Decompose accented characters - gsub(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics). - end - end - - # Create the name of a table like Rails does for models to table names. This method - # uses the +pluralize+ method on the last word in the string. - # - # Examples - # "RawScaledScorer".tableize # => "raw_scaled_scorers" - # "egg_and_ham".tableize # => "egg_and_hams" - # "fancyCategory".tableize # => "fancy_categories" - def tableize(class_name) - pluralize(underscore(class_name)) - end - - # Create a class name from a plural table name like Rails does for table names to models. - # Note that this returns a string and not a Class. (To convert to an actual class - # follow +classify+ with +constantize+.) - # - # Examples: - # "egg_and_hams".classify # => "EggAndHam" - # "posts".classify # => "Post" - # - # Singular names are not handled correctly: - # "business".classify # => "Busines" - def classify(table_name) - # strip out any leading schema name - camelize(singularize(table_name.to_s.sub(/.*\./, ''))) - end - - # Creates a foreign key name from a class name. - # +separate_class_name_and_id_with_underscore+ sets whether - # the method should put '_' between the name and 'id'. - # - # Examples: - # "Message".foreign_key # => "message_id" - # "Message".foreign_key(false) # => "messageid" - # "Admin::Post".foreign_key # => "post_id" - def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) - underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") - end - - # Ruby 1.9 introduces an inherit argument for Module#const_get and - # #const_defined? and changes their default behavior. - if Module.method(:const_get).arity == 1 - # Tries to find a constant with the name specified in the argument string: - # - # "Module".constantize # => Module - # "Test::Unit".constantize # => Test::Unit - # - # The name is assumed to be the one of a top-level constant, no matter whether - # it starts with "::" or not. No lexical context is taken into account: - # - # C = 'outside' - # module M - # C = 'inside' - # C # => 'inside' - # "C".constantize # => 'outside', same as ::C - # end - # - # NameError is raised when the name is not in CamelCase or the constant is - # unknown. - def constantize(camel_cased_word) - names = camel_cased_word.split('::') - names.shift if names.empty? || names.first.empty? - - constant = Object - names.each do |name| - constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) - end - constant - end - else - def constantize(camel_cased_word) #:nodoc: - names = camel_cased_word.split('::') - names.shift if names.empty? || names.first.empty? - - constant = Object - names.each do |name| - constant = constant.const_get(name, false) || constant.const_missing(name) - end - constant - end - end - - # Turns a number into an ordinal string used to denote the position in an - # ordered sequence such as 1st, 2nd, 3rd, 4th. - # - # Examples: - # ordinalize(1) # => "1st" - # ordinalize(2) # => "2nd" - # ordinalize(1002) # => "1002nd" - # ordinalize(1003) # => "1003rd" - def ordinalize(number) - if (11..13).include?(number.to_i % 100) - "#{number}th" - else - case number.to_i % 10 - when 1; "#{number}st" - when 2; "#{number}nd" - when 3; "#{number}rd" - else "#{number}th" - end - end - end - end -end - # in case active_support/inflector is required without the rest of active_support +require 'active_support/inflector/inflections' +require 'active_support/inflector/transliterate' +require 'active_support/inflector/methods' + require 'active_support/inflections' require 'active_support/core_ext/string/inflections' diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb new file mode 100644 index 0000000000..24ce58e5c2 --- /dev/null +++ b/activesupport/lib/active_support/inflector/inflections.rb @@ -0,0 +1,213 @@ +# require "active_support/core_ext/string/access" + +module ActiveSupport + module Inflector + # A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional + # inflection rules. Examples: + # + # ActiveSupport::Inflector.inflections do |inflect| + # inflect.plural /^(ox)$/i, '\1\2en' + # inflect.singular /^(ox)en/i, '\1' + # + # inflect.irregular 'octopus', 'octopi' + # + # inflect.uncountable "equipment" + # end + # + # New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the + # pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may + # already have been loaded. + class Inflections + def self.instance + @__instance__ ||= new + end + + attr_reader :plurals, :singulars, :uncountables, :humans + + def initialize + @plurals, @singulars, @uncountables, @humans = [], [], [], [] + end + + # Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. + # The replacement should always be a string that may include references to the matched data from the rule. + def plural(rule, replacement) + @uncountables.delete(rule) if rule.is_a?(String) + @uncountables.delete(replacement) + @plurals.insert(0, [rule, replacement]) + end + + # Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. + # The replacement should always be a string that may include references to the matched data from the rule. + def singular(rule, replacement) + @uncountables.delete(rule) if rule.is_a?(String) + @uncountables.delete(replacement) + @singulars.insert(0, [rule, replacement]) + end + + # Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used + # for strings, not regular expressions. You simply pass the irregular in singular and plural form. + # + # Examples: + # irregular 'octopus', 'octopi' + # irregular 'person', 'people' + def irregular(singular, plural) + @uncountables.delete(singular) + @uncountables.delete(plural) + if singular[0,1].upcase == plural[0,1].upcase + plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1]) + plural(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + plural[1..-1]) + singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1]) + else + plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1]) + plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1]) + plural(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), plural[0,1].upcase + plural[1..-1]) + plural(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), plural[0,1].downcase + plural[1..-1]) + singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1]) + singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1]) + end + end + + # Add uncountable words that shouldn't be attempted inflected. + # + # Examples: + # uncountable "money" + # uncountable "money", "information" + # uncountable %w( money information rice ) + def uncountable(*words) + (@uncountables << words).flatten! + end + + # Specifies a humanized form of a string by a regular expression rule or by a string mapping. + # When using a regular expression based replacement, the normal humanize formatting is called after the replacement. + # When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name') + # + # Examples: + # human /_cnt$/i, '\1_count' + # human "legacy_col_person_name", "Name" + def human(rule, replacement) + @humans.insert(0, [rule, replacement]) + end + + # Clears the loaded inflections within a given scope (default is :all). + # Give the scope as a symbol of the inflection type, the options are: :plurals, + # :singulars, :uncountables, :humans. + # + # Examples: + # clear :all + # clear :plurals + def clear(scope = :all) + case scope + when :all + @plurals, @singulars, @uncountables = [], [], [] + else + instance_variable_set "@#{scope}", [] + end + end + end + + # Yields a singleton instance of Inflector::Inflections so you can specify additional + # inflector rules. + # + # Example: + # ActiveSupport::Inflector.inflections do |inflect| + # inflect.uncountable "rails" + # end + def inflections + if block_given? + yield Inflections.instance + else + Inflections.instance + end + end + + # Returns the plural form of the word in the string. + # + # Examples: + # "post".pluralize # => "posts" + # "octopus".pluralize # => "octopi" + # "sheep".pluralize # => "sheep" + # "words".pluralize # => "words" + # "CamelOctopus".pluralize # => "CamelOctopi" + def pluralize(word) + result = word.to_s.dup + + if word.empty? || inflections.uncountables.include?(result.downcase) + result + else + inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } + result + end + end + + # The reverse of +pluralize+, returns the singular form of a word in a string. + # + # Examples: + # "posts".singularize # => "post" + # "octopi".singularize # => "octopus" + # "sheep".singularize # => "sheep" + # "word".singularize # => "word" + # "CamelOctopi".singularize # => "CamelOctopus" + def singularize(word) + result = word.to_s.dup + + if inflections.uncountables.include?(result.downcase) + result + else + inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } + result + end + end + + # Capitalizes the first word and turns underscores into spaces and strips a + # trailing "_id", if any. Like +titleize+, this is meant for creating pretty output. + # + # Examples: + # "employee_salary" # => "Employee salary" + # "author_id" # => "Author" + def humanize(lower_case_and_underscored_word) + result = lower_case_and_underscored_word.to_s.dup + + inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } + result.gsub(/_id$/, "").gsub(/_/, " ").capitalize + end + + # Capitalizes all the words and replaces some characters in the string to create + # a nicer looking title. +titleize+ is meant for creating pretty output. It is not + # used in the Rails internals. + # + # +titleize+ is also aliased as as +titlecase+. + # + # Examples: + # "man from the boondocks".titleize # => "Man From The Boondocks" + # "x-men: the last stand".titleize # => "X Men: The Last Stand" + def titleize(word) + humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize } + end + + # Create the name of a table like Rails does for models to table names. This method + # uses the +pluralize+ method on the last word in the string. + # + # Examples + # "RawScaledScorer".tableize # => "raw_scaled_scorers" + # "egg_and_ham".tableize # => "egg_and_hams" + # "fancyCategory".tableize # => "fancy_categories" + def tableize(class_name) + pluralize(underscore(class_name)) + end + + # Create a class name from a plural table name like Rails does for table names to models. + # Note that this returns a string and not a Class. (To convert to an actual class + # follow +classify+ with +constantize+.) + # + # Examples: + # "egg_and_hams".classify # => "EggAndHam" + # "posts".classify # => "Post" + # + # Singular names are not handled correctly: + # "business".classify # => "Busines" + def classify(table_name) + # strip out any leading schema name + camelize(singularize(table_name.to_s.sub(/.*\./, ''))) + end + end +end \ No newline at end of file diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb new file mode 100644 index 0000000000..41277893e3 --- /dev/null +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -0,0 +1,139 @@ +module ActiveSupport + # The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, + # and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept + # in inflections.rb. + # + # The Rails core team has stated patches for the inflections library will not be accepted + # in order to avoid breaking legacy applications which may be relying on errant inflections. + # If you discover an incorrect inflection and require it for your application, you'll need + # to correct it yourself (explained below). + module Inflector + extend self + + # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+ + # is set to :lower then +camelize+ produces lowerCamelCase. + # + # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces. + # + # Examples: + # "active_record".camelize # => "ActiveRecord" + # "active_record".camelize(:lower) # => "activeRecord" + # "active_record/errors".camelize # => "ActiveRecord::Errors" + # "active_record/errors".camelize(:lower) # => "activeRecord::Errors" + def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) + if first_letter_in_uppercase + lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } + else + lower_case_and_underscored_word.to_s[0].chr.downcase + camelize(lower_case_and_underscored_word)[1..-1] + end + end + + # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string. + # + # Changes '::' to '/' to convert namespaces to paths. + # + # Examples: + # "ActiveRecord".underscore # => "active_record" + # "ActiveRecord::Errors".underscore # => active_record/errors + def underscore(camel_cased_word) + camel_cased_word.to_s.gsub(/::/, '/'). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr("-", "_"). + downcase + end + + # Replaces underscores with dashes in the string. + # + # Example: + # "puni_puni" # => "puni-puni" + def dasherize(underscored_word) + underscored_word.gsub(/_/, '-') + end + + # Removes the module part from the expression in the string. + # + # Examples: + # "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections" + # "Inflections".demodulize # => "Inflections" + def demodulize(class_name_in_module) + class_name_in_module.to_s.gsub(/^.*::/, '') + end + + # Creates a foreign key name from a class name. + # +separate_class_name_and_id_with_underscore+ sets whether + # the method should put '_' between the name and 'id'. + # + # Examples: + # "Message".foreign_key # => "message_id" + # "Message".foreign_key(false) # => "messageid" + # "Admin::Post".foreign_key # => "post_id" + def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) + underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") + end + + # Ruby 1.9 introduces an inherit argument for Module#const_get and + # #const_defined? and changes their default behavior. + if Module.method(:const_get).arity == 1 + # Tries to find a constant with the name specified in the argument string: + # + # "Module".constantize # => Module + # "Test::Unit".constantize # => Test::Unit + # + # The name is assumed to be the one of a top-level constant, no matter whether + # it starts with "::" or not. No lexical context is taken into account: + # + # C = 'outside' + # module M + # C = 'inside' + # C # => 'inside' + # "C".constantize # => 'outside', same as ::C + # end + # + # NameError is raised when the name is not in CamelCase or the constant is + # unknown. + def constantize(camel_cased_word) + names = camel_cased_word.split('::') + names.shift if names.empty? || names.first.empty? + + constant = Object + names.each do |name| + constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) + end + constant + end + else + def constantize(camel_cased_word) #:nodoc: + names = camel_cased_word.split('::') + names.shift if names.empty? || names.first.empty? + + constant = Object + names.each do |name| + constant = constant.const_get(name, false) || constant.const_missing(name) + end + constant + end + end + + # Turns a number into an ordinal string used to denote the position in an + # ordered sequence such as 1st, 2nd, 3rd, 4th. + # + # Examples: + # ordinalize(1) # => "1st" + # ordinalize(2) # => "2nd" + # ordinalize(1002) # => "1002nd" + # ordinalize(1003) # => "1003rd" + def ordinalize(number) + if (11..13).include?(number.to_i % 100) + "#{number}th" + else + case number.to_i % 10 + when 1; "#{number}st" + when 2; "#{number}nd" + when 3; "#{number}rd" + else "#{number}th" + end + end + end + end +end \ No newline at end of file diff --git a/activesupport/lib/active_support/inflector/transliterate.rb b/activesupport/lib/active_support/inflector/transliterate.rb new file mode 100644 index 0000000000..30a9072ee1 --- /dev/null +++ b/activesupport/lib/active_support/inflector/transliterate.rb @@ -0,0 +1,61 @@ +# encoding: utf-8 +require 'iconv' +require 'active_support/core_ext/string/multibyte' + +module ActiveSupport + module Inflector + extend self + + # Replaces accented characters with their ascii equivalents. + def transliterate(string) + Iconv.iconv('ascii//ignore//translit', 'utf-8', string).to_s + end + + if RUBY_VERSION >= '1.9' + undef_method :transliterate + def transliterate(string) + warn "Ruby 1.9 doesn't support Unicode normalization yet" + string.dup + end + + # The iconv transliteration code doesn't function correctly + # on some platforms, but it's very fast where it does function. + elsif "foo" != (Inflector.transliterate("föö") rescue nil) + undef_method :transliterate + def transliterate(string) + string.mb_chars.normalize(:kd). # Decompose accented characters + gsub(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics). + end + end + + # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. + # + # ==== Examples + # + # class Person + # def to_param + # "#{id}-#{name.parameterize}" + # end + # end + # + # @person = Person.find(1) + # # => # + # + # <%= link_to(@person.name, person_path(@person)) %> + # # => Donald E. Knuth + def parameterize(string, sep = '-') + # replace accented chars with their ascii equivalents + parameterized_string = transliterate(string) + # Turn unwanted chars into the separator + parameterized_string.gsub!(/[^a-z0-9\-_\+]+/i, sep) + unless sep.nil? || sep.empty? + re_sep = Regexp.escape(sep) + # No more than one of the separator in a row. + parameterized_string.gsub!(/#{re_sep}{2,}/, sep) + # Remove leading/trailing separator. + parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '') + end + parameterized_string.downcase + end + end +end \ No newline at end of file -- cgit v1.2.3 From 103b29831e6d6a6c4363fd0e59ffcc6c343a14aa Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 7 Nov 2009 11:23:34 -0800 Subject: Since we require 1.8.7 we don't need to shim instance_exec anymore --- .../active_support/core_ext/object/extending.rb | 27 ---------------------- 1 file changed, 27 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/object/extending.rb b/activesupport/lib/active_support/core_ext/object/extending.rb index bbf6f8563b..0cc74c8298 100644 --- a/activesupport/lib/active_support/core_ext/object/extending.rb +++ b/activesupport/lib/active_support/core_ext/object/extending.rb @@ -50,31 +50,4 @@ class Object def extend_with_included_modules_from(object) #:nodoc: object.extended_by.each { |mod| extend mod } end - - unless defined? instance_exec # 1.9 - module InstanceExecMethods #:nodoc: - end - include InstanceExecMethods - - # Evaluate the block with the given arguments within the context of - # this object, so self is set to the method receiver. - # - # From Mauricio's http://eigenclass.org/hiki/bounded+space+instance_exec - def instance_exec(*args, &block) - begin - old_critical, Thread.critical = Thread.critical, true - n = 0 - n += 1 while respond_to?(method_name = "__instance_exec#{n}") - InstanceExecMethods.module_eval { define_method(method_name, &block) } - ensure - Thread.critical = old_critical - end - - begin - send(method_name, *args) - ensure - InstanceExecMethods.module_eval { remove_method(method_name) } rescue nil - end - end - end end -- cgit v1.2.3 From a595abff211eee97d75c51c085cfdc821b1edb46 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 12:12:45 -0800 Subject: Unknown :format param should result in empty request.formats --- actionpack/lib/action_dispatch/http/request.rb | 2 +- actionpack/test/dispatch/request_test.rb | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 9314ff5c53..c24b404e2f 100755 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -167,7 +167,7 @@ module ActionDispatch @env["action_dispatch.request.formats"] ||= if parameters[:format] - [Mime[parameters[:format]]] + Array.wrap(Mime[parameters[:format]]) elsif xhr? || (accept && !accept.include?(?,)) accepts else diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 239fda98e0..b62df9a6b2 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -432,6 +432,10 @@ class RequestTest < ActiveSupport::TestCase request = stub_request request.expects(:parameters).at_least_once.returns({ :format => :txt }) assert_equal with_set(Mime::TEXT), request.formats + + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => :unknown }) + assert request.formats.empty? end test "negotiate_mime" do -- cgit v1.2.3 From 216e8c6bfad6800f5f2a772d40cab29442efdaf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 6 Nov 2009 23:28:58 -0200 Subject: Update Rails Generators to use Thor 0.12.0. Signed-off-by: Yehuda Katz --- railties/lib/rails/generators.rb | 2 +- railties/lib/rails/generators/base.rb | 4 + .../lib/rails/vendor/thor-0.11.8/CHANGELOG.rdoc | 77 --- railties/lib/rails/vendor/thor-0.11.8/LICENSE | 20 - railties/lib/rails/vendor/thor-0.11.8/README.rdoc | 234 ---------- railties/lib/rails/vendor/thor-0.11.8/Thorfile | 63 --- railties/lib/rails/vendor/thor-0.11.8/lib/thor.rb | 242 ---------- .../rails/vendor/thor-0.11.8/lib/thor/actions.rb | 273 ----------- .../thor-0.11.8/lib/thor/actions/create_file.rb | 102 ---- .../thor-0.11.8/lib/thor/actions/directory.rb | 89 ---- .../lib/thor/actions/empty_directory.rb | 133 ------ .../lib/thor/actions/file_manipulation.rb | 219 --------- .../lib/thor/actions/inject_into_file.rb | 101 ---- .../lib/rails/vendor/thor-0.11.8/lib/thor/base.rb | 517 --------------------- .../thor/core_ext/hash_with_indifferent_access.rb | 75 --- .../thor-0.11.8/lib/thor/core_ext/ordered_hash.rb | 100 ---- .../lib/rails/vendor/thor-0.11.8/lib/thor/error.rb | 27 -- .../lib/rails/vendor/thor-0.11.8/lib/thor/group.rb | 263 ----------- .../vendor/thor-0.11.8/lib/thor/invocation.rb | 178 ------- .../rails/vendor/thor-0.11.8/lib/thor/parser.rb | 4 - .../vendor/thor-0.11.8/lib/thor/parser/argument.rb | 67 --- .../thor-0.11.8/lib/thor/parser/arguments.rb | 145 ------ .../vendor/thor-0.11.8/lib/thor/parser/option.rb | 132 ------ .../vendor/thor-0.11.8/lib/thor/parser/options.rb | 142 ------ .../vendor/thor-0.11.8/lib/thor/rake_compat.rb | 66 --- .../rails/vendor/thor-0.11.8/lib/thor/runner.rb | 299 ------------ .../lib/rails/vendor/thor-0.11.8/lib/thor/shell.rb | 78 ---- .../vendor/thor-0.11.8/lib/thor/shell/basic.rb | 219 --------- .../vendor/thor-0.11.8/lib/thor/shell/color.rb | 108 ----- .../lib/rails/vendor/thor-0.11.8/lib/thor/task.rb | 122 ----- .../lib/rails/vendor/thor-0.11.8/lib/thor/util.rb | 251 ---------- .../rails/vendor/thor-0.11.8/lib/thor/version.rb | 3 - .../lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc | 82 ++++ railties/lib/rails/vendor/thor-0.12.0/LICENSE | 20 + railties/lib/rails/vendor/thor-0.12.0/README.rdoc | 234 ++++++++++ railties/lib/rails/vendor/thor-0.12.0/Thorfile | 63 +++ railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb | 242 ++++++++++ .../rails/vendor/thor-0.12.0/lib/thor/actions.rb | 273 +++++++++++ .../thor-0.12.0/lib/thor/actions/create_file.rb | 103 ++++ .../thor-0.12.0/lib/thor/actions/directory.rb | 93 ++++ .../lib/thor/actions/empty_directory.rb | 134 ++++++ .../lib/thor/actions/file_manipulation.rb | 219 +++++++++ .../lib/thor/actions/inject_into_file.rb | 101 ++++ .../lib/rails/vendor/thor-0.12.0/lib/thor/base.rb | 517 +++++++++++++++++++++ .../thor/core_ext/hash_with_indifferent_access.rb | 75 +++ .../thor-0.12.0/lib/thor/core_ext/ordered_hash.rb | 100 ++++ .../lib/rails/vendor/thor-0.12.0/lib/thor/error.rb | 27 ++ .../lib/rails/vendor/thor-0.12.0/lib/thor/group.rb | 263 +++++++++++ .../vendor/thor-0.12.0/lib/thor/invocation.rb | 178 +++++++ .../rails/vendor/thor-0.12.0/lib/thor/parser.rb | 4 + .../vendor/thor-0.12.0/lib/thor/parser/argument.rb | 67 +++ .../thor-0.12.0/lib/thor/parser/arguments.rb | 145 ++++++ .../vendor/thor-0.12.0/lib/thor/parser/option.rb | 132 ++++++ .../vendor/thor-0.12.0/lib/thor/parser/options.rb | 142 ++++++ .../vendor/thor-0.12.0/lib/thor/rake_compat.rb | 66 +++ .../rails/vendor/thor-0.12.0/lib/thor/runner.rb | 299 ++++++++++++ .../lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb | 78 ++++ .../vendor/thor-0.12.0/lib/thor/shell/basic.rb | 219 +++++++++ .../vendor/thor-0.12.0/lib/thor/shell/color.rb | 108 +++++ .../lib/rails/vendor/thor-0.12.0/lib/thor/task.rb | 122 +++++ .../lib/rails/vendor/thor-0.12.0/lib/thor/util.rb | 251 ++++++++++ .../rails/vendor/thor-0.12.0/lib/thor/version.rb | 3 + 62 files changed, 4365 insertions(+), 4350 deletions(-) delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/CHANGELOG.rdoc delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/LICENSE delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/README.rdoc delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/Thorfile delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/create_file.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/directory.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/empty_directory.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/file_manipulation.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/inject_into_file.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/base.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/hash_with_indifferent_access.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/ordered_hash.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/error.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/group.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/invocation.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/argument.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/arguments.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/option.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/options.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/rake_compat.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/runner.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell/basic.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell/color.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/task.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/util.rb delete mode 100644 railties/lib/rails/vendor/thor-0.11.8/lib/thor/version.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc create mode 100644 railties/lib/rails/vendor/thor-0.12.0/LICENSE create mode 100644 railties/lib/rails/vendor/thor-0.12.0/README.rdoc create mode 100644 railties/lib/rails/vendor/thor-0.12.0/Thorfile create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/color.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/task.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb create mode 100644 railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index fa2c11795b..19412c259e 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -9,7 +9,7 @@ require 'active_support/core_ext/module/attribute_accessors' require 'active_support/core_ext/string/inflections' # TODO: Do not always push on vendored thor -$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/vendor/thor-0.11.8/lib") +$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/vendor/thor-0.12.0/lib") require 'rails/generators/base' require 'rails/generators/named_base' diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index af1bf26f4a..a64005497b 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -212,6 +212,10 @@ module Rails def self.inherited(base) #:nodoc: super + # Cache source root, we need to do this, since __FILE__ is a relative value + # and can point to wrong directions when inside an specified directory. + base.source_root + if base.name && base.name !~ /Base$/ && defined?(Rails.root) && Rails.root path = File.expand_path(File.join(Rails.root, 'lib', 'templates')) if base.name.include?('::') diff --git a/railties/lib/rails/vendor/thor-0.11.8/CHANGELOG.rdoc b/railties/lib/rails/vendor/thor-0.11.8/CHANGELOG.rdoc deleted file mode 100644 index dba25b7205..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/CHANGELOG.rdoc +++ /dev/null @@ -1,77 +0,0 @@ -== TODO - -* Improve spec coverage for Thor::Runner - -== 0.11.x, released 2009-07-01 - -* Added a rake compatibility layer. It allows you to use spec and rdoc tasks on - Thor classes. - -* BACKWARDS INCOMPATIBLE: aliases are not generated automatically anymore - since it wrong behavior to the invocation system. - -* thor help now show information about any class/task. All those calls are - possible: - - thor help describe - thor help describe:amazing - - Or even with default namespaces: - - thor help :spec - -* Thor::Runner now invokes the default task if none is supplied: - - thor describe # invokes the default task, usually help - -* Thor::Runner now works with mappings: - - thor describe -h - -* Added some documentation and code refactoring. - -== 0.9.8, released 2008-10-20 - -* Fixed some tiny issues that were introduced lately. - -== 0.9.7, released 2008-10-13 - -* Setting global method options on the initialize method works as expected: - All other tasks will accept these global options in addition to their own. -* Added 'group' notion to Thor task sets (class Thor); by default all tasks - are in the 'standard' group. Running 'thor -T' will only show the standard - tasks - adding --all will show all tasks. You can also filter on a specific - group using the --group option: thor -T --group advanced - -== 0.9.6, released 2008-09-13 - -* Generic improvements - -== 0.9.5, released 2008-08-27 - -* Improve Windows compatibility -* Update (incorrect) README and task.thor sample file -* Options hash is now frozen (once returned) -* Allow magic predicates on options object. For instance: `options.force?` -* Add support for :numeric type -* BACKWARDS INCOMPATIBLE: Refactor Thor::Options. You cannot access shorthand forms in options hash anymore (for instance, options[:f]) -* Allow specifying optional args with default values: method_options(:user => "mislav") -* Don't write options for nil or false values. This allows, for example, turning color off when running specs. -* Exit with the status of the spec command to help CI stuff out some. - -== 0.9.4, released 2008-08-13 - -* Try to add Windows compatibility. -* BACKWARDS INCOMPATIBLE: options hash is now accessed as a property in your class and is not passed as last argument anymore -* Allow options at the beginning of the argument list as well as the end. -* Make options available with symbol keys in addition to string keys. -* Allow true to be passed to Thor#method_options to denote a boolean option. -* If loading a thor file fails, don't give up, just print a warning and keep going. -* Make sure that we re-raise errors if they happened further down the pipe than we care about. -* Only delete the old file on updating when the installation of the new one is a success -* Make it Ruby 1.8.5 compatible. -* Don't raise an error if a boolean switch is defined multiple times. -* Thor::Options now doesn't parse through things that look like options but aren't. -* Add URI detection to install task, and make sure we don't append ".thor" to URIs -* Add rake2thor to the gem binfiles. -* Make sure local Thorfiles override system-wide ones. diff --git a/railties/lib/rails/vendor/thor-0.11.8/LICENSE b/railties/lib/rails/vendor/thor-0.11.8/LICENSE deleted file mode 100644 index 98722da459..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008 Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/railties/lib/rails/vendor/thor-0.11.8/README.rdoc b/railties/lib/rails/vendor/thor-0.11.8/README.rdoc deleted file mode 100644 index f1106f02b6..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/README.rdoc +++ /dev/null @@ -1,234 +0,0 @@ -= thor - -Map options to a class. Simply create a class with the appropriate annotations -and have options automatically map to functions and parameters. - -Example: - - class App < Thor # [1] - map "-L" => :list # [2] - - desc "install APP_NAME", "install one of the available apps" # [3] - method_options :force => :boolean, :alias => :string # [4] - def install(name) - user_alias = options[:alias] - if options.force? - # do something - end - # other code - end - - desc "list [SEARCH]", "list all of the available apps, limited by SEARCH" - def list(search="") - # list everything - end - end - -Thor automatically maps commands as such: - - thor app:install myname --force - -That gets converted to: - - App.new.install("myname") - # with {'force' => true} as options hash - -1. Inherit from Thor to turn a class into an option mapper -2. Map additional non-valid identifiers to specific methods. In this case, convert -L to :list -3. Describe the method immediately below. The first parameter is the usage information, and the second parameter is the description -4. Provide any additional options that will be available the instance method options. - -== Types for method_options - -* :boolean - is parsed as --option or --option=true -* :string - is parsed as --option=VALUE -* :numeric - is parsed as --option=N -* :array - is parsed as --option=one two three -* :hash - is parsed as --option=name:string age:integer - -Besides, method_option allows a default value to be given, examples: - - method_options :force => false - #=> Creates a boolean option with default value false - - method_options :alias => "bar" - #=> Creates a string option with default value "bar" - - method_options :threshold => 3.0 - #=> Creates a numeric option with default value 3.0 - -You can also supply :option => :required to mark an option as required. The -type is assumed to be string. If you want a required hash with default values -as option, you can use method_option which uses a more declarative style: - - method_option :attributes, :type => :hash, :default => {}, :required => true - -All arguments can be set to nil (except required arguments), by suppling a no or -skip variant. For example: - - thor app name --no-attributes - -In previous versions, aliases for options were created automatically, but now -they should be explicit. You can supply aliases in both short and declarative -styles: - - method_options %w( force -f ) => :boolean - -Or: - - method_option :force, :type => :boolean, :aliases => "-f" - -You can supply as many aliases as you want. - -NOTE: Type :optional available in Thor 0.9.0 was deprecated. Use :string or :boolean instead. - -== Namespaces - -By default, your Thor tasks are invoked using Ruby namespace. In the example -above, tasks are invoked as: - - thor app:install name --force - -However, you could namespace your class as: - - module Sinatra - class App < Thor - # tasks - end - end - -And then you should invoke your tasks as: - - thor sinatra:app:install name --force - -If desired, you can change the namespace: - - module Sinatra - class App < Thor - namespace :myapp - # tasks - end - end - -And then your tasks hould be invoked as: - - thor myapp:install name --force - -== Invocations - -Thor comes with a invocation-dependency system as well which allows a task to be -invoked only once. For example: - - class Counter < Thor - desc "one", "Prints 1, 2, 3" - def one - puts 1 - invoke :two - invoke :three - end - - desc "two", "Prints 2, 3" - def two - puts 2 - invoke :three - end - - desc "three", "Prints 3" - def three - puts 3 - end - end - -When invoking the task one: - - thor counter:one - -The output is "1 2 3", which means that the three task was invoked only once. -You can even invoke tasks from another class, so be sure to check the -documentation. - -== Thor::Group - -Thor has a special class called Thor::Group. The main difference to Thor class -is that it invokes all tasks at once. The example above could be rewritten in -Thor::Group as this: - - class Counter < Thor::Group - desc "Prints 1, 2, 3" - - def one - puts 1 - end - - def two - puts 2 - end - - def three - puts 3 - end - end - -When invoked: - - thor counter - -It prints "1 2 3" as well. Notice you should describe (using the method desc) -only the class and not each task anymore. Thor::Group is a great tool to create -generators, since you can define several steps which are invoked in the order they -are defined (Thor::Group is the tool use in generators in Rails 3.0). - -Besides, Thor::Group can parse arguments and options as Thor tasks: - - class Counter < Thor::Group - # number will be available as attr_accessor - argument :number, :type => :numeric, :desc => "The number to start counting" - desc "Prints the 'number' given upto 'number+2'" - - def one - puts number + 0 - end - - def two - puts number + 1 - end - - def three - puts number + 2 - end - end - -The counter above expects one parameter and has the folling outputs: - - thor counter 5 - # Prints "5 6 7" - - thor counter 11 - # Prints "11 12 13" - -You can also give options to Thor::Group, but instead of using method_option -and method_options, you should use class_option and class_options. -Both argument and class_options methods are available to Thor class as well. - -== Actions - -Thor comes with several actions which helps with script and generator tasks. You -might be familiar with them since some came from Rails Templates. They are: -say, ask, yes?, no?, add_file, -remove_file, copy_file, template, directory, -inside, run, inject_into_file and a couple more. - -To use them, you just need to include Thor::Actions in your Thor classes: - - class App < Thor - include Thor::Actions - # tasks - end - -Some actions like copy file requires that a class method called source_root is -defined in your class. This is the directory where your templates should be -placed. Be sure to check the documentation. - -== License - -See MIT LICENSE. diff --git a/railties/lib/rails/vendor/thor-0.11.8/Thorfile b/railties/lib/rails/vendor/thor-0.11.8/Thorfile deleted file mode 100644 index f71a1e57e2..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/Thorfile +++ /dev/null @@ -1,63 +0,0 @@ -# enconding: utf-8 - -require File.join(File.dirname(__FILE__), "lib", "thor", "version") -require 'thor/rake_compat' -require 'spec/rake/spectask' -require 'rdoc/task' - -GEM_NAME = 'thor' -EXTRA_RDOC_FILES = ["README.rdoc", "LICENSE", "CHANGELOG.rdoc", "VERSION", "Thorfile"] - -class Default < Thor - include Thor::RakeCompat - - Spec::Rake::SpecTask.new(:spec) do |t| - t.libs << 'lib' - t.spec_opts = ['--options', "spec/spec.opts"] - t.spec_files = FileList['spec/**/*_spec.rb'] - end - - Spec::Rake::SpecTask.new(:rcov) do |t| - t.libs << 'lib' - t.spec_opts = ['--options', "spec/spec.opts"] - t.spec_files = FileList['spec/**/*_spec.rb'] - t.rcov = true - t.rcov_dir = "rcov" - end - - RDoc::Task.new do |rdoc| - rdoc.main = "README.rdoc" - rdoc.rdoc_dir = "rdoc" - rdoc.title = GEM_NAME - rdoc.rdoc_files.include(*EXTRA_RDOC_FILES) - rdoc.rdoc_files.include('lib/**/*.rb') - rdoc.options << '--line-numbers' << '--inline-source' - end - - begin - require 'jeweler' - Jeweler::Tasks.new do |s| - s.name = GEM_NAME - s.version = Thor::VERSION - s.rubyforge_project = "textmate" - s.platform = Gem::Platform::RUBY - s.summary = "A scripting framework that replaces rake, sake and rubigen" - s.email = "ruby-thor@googlegroups.com" - s.homepage = "http://yehudakatz.com" - s.description = "A scripting framework that replaces rake, sake and rubigen" - s.authors = ['Yehuda Katz', 'José Valim'] - s.has_rdoc = true - s.extra_rdoc_files = EXTRA_RDOC_FILES - s.require_path = 'lib' - s.bindir = "bin" - s.executables = %w( thor rake2thor ) - s.files = s.extra_rdoc_files + Dir.glob("{bin,lib}/**/*") - s.files.exclude 'spec/sandbox/**/*' - s.test_files.exclude 'spec/sandbox/**/*' - end - - Jeweler::RubyforgeTasks.new - rescue LoadError - puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor.rb deleted file mode 100644 index 68944f140d..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor.rb +++ /dev/null @@ -1,242 +0,0 @@ -require 'thor/base' -require 'thor/group' -require 'thor/actions' - -class Thor - class << self - # Sets the default task when thor is executed without an explicit task to be called. - # - # ==== Parameters - # meth:: name of the defaut task - # - def default_task(meth=nil) - case meth - when :none - @default_task = 'help' - when nil - @default_task ||= from_superclass(:default_task, 'help') - else - @default_task = meth.to_s - end - end - - # Defines the usage and the description of the next task. - # - # ==== Parameters - # usage - # description - # - def desc(usage, description, options={}) - if options[:for] - task = find_and_refresh_task(options[:for]) - task.usage = usage if usage - task.description = description if description - else - @usage, @desc = usage, description - end - end - - # Maps an input to a task. If you define: - # - # map "-T" => "list" - # - # Running: - # - # thor -T - # - # Will invoke the list task. - # - # ==== Parameters - # Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given task. - # - def map(mappings=nil) - @map ||= from_superclass(:map, {}) - - if mappings - mappings.each do |key, value| - if key.respond_to?(:each) - key.each {|subkey| @map[subkey] = value} - else - @map[key] = value - end - end - end - - @map - end - - # Declares the options for the next task to be declared. - # - # ==== Parameters - # Hash[Symbol => Object]:: The hash key is the name of the option and the value - # is the type of the option. Can be :string, :array, :hash, :boolean, :numeric - # or :required (string). If you give a value, the type of the value is used. - # - def method_options(options=nil) - @method_options ||= {} - build_options(options, @method_options) if options - @method_options - end - - # Adds an option to the set of class options. If :for is given as option, - # it allows you to change the options from a previous defined task. - # - # def previous_task - # # magic - # end - # - # method_options :foo => :bar, :for => :previous_task - # - # def next_task - # # magic - # end - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described below. - # - # ==== Options - # :desc - Description for the argument. - # :required - If the argument is required or not. - # :default - Default value for this argument. It cannot be required and have default values. - # :aliases - Aliases for this option. - # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. - # :group - The group for this options. Use by class options to output options in different levels. - # :banner - String to show on usage notes. - # - def method_option(name, options={}) - scope = if options[:for] - find_and_refresh_task(options[:for]).options - else - method_options - end - - build_option(name, options, scope) - end - - # Parses the task and options from the given args, instantiate the class - # and invoke the task. This method is used when the arguments must be parsed - # from an array. If you are inside Ruby and want to use a Thor class, you - # can simply initialize it: - # - # script = MyScript.new(args, options, config) - # script.invoke(:task, first_arg, second_arg, third_arg) - # - def start(given_args=ARGV, config={}) - super do - meth = normalize_task_name(given_args.shift) - task = all_tasks[meth] - - if task - args, opts = Thor::Options.split(given_args) - config.merge!(:task_options => task.options) - else - args, opts = given_args, {} - end - - task ||= Thor::Task::Dynamic.new(meth) - trailing = args[Range.new(arguments.size, -1)] - new(args, opts, config).invoke(task, trailing || []) - end - end - - # Prints help information. If a task name is given, it shows information - # only about the specific task. - # - # ==== Parameters - # meth:: An optional task name to print usage information about. - # - # ==== Options - # namespace:: When true, shows the namespace in the output before the usage. - # skip_inherited:: When true, does not show tasks from superclass. - # - def help(shell, meth=nil, options={}) - meth, options = nil, meth if meth.is_a?(Hash) - - if meth - task = all_tasks[meth] - raise UndefinedTaskError, "task '#{meth}' could not be found in namespace '#{self.namespace}'" unless task - - shell.say "Usage:" - shell.say " #{banner(task, options[:namespace], false)}" - shell.say - class_options_help(shell, "Class", :Method => task.options.map { |_, o| o }) - shell.say task.description - else - list = (options[:short] ? tasks : all_tasks).map do |_, task| - item = [ banner(task, options[:namespace]) ] - item << "# #{task.short_description}" if task.short_description - item << " " - end - - options[:ident] ||= 2 - if options[:short] - shell.print_list(list, :ident => options[:ident]) - else - shell.say "Tasks:" - shell.print_list(list, :ident => options[:ident]) - end - - Thor::Util.thor_classes_in(self).each do |subclass| - namespace = options[:namespace] == true || subclass.namespace.gsub(/^#{self.namespace}:/, '') - subclass.help(shell, options.merge(:short => true, :namespace => namespace)) - end - - class_options_help(shell, "Class") unless options[:short] - end - end - - protected - - # The banner for this class. You can customize it if you are invoking the - # thor class by another ways which is not the Thor::Runner. It receives - # the task that is going to be invoked and a boolean which indicates if - # the namespace should be displayed as arguments. - # - def banner(task, namespace=true, show_options=true) - task.formatted_usage(self, namespace, show_options) - end - - def baseclass #:nodoc: - Thor - end - - def create_task(meth) #:nodoc: - if @usage && @desc - tasks[meth.to_s] = Thor::Task.new(meth, @desc, @usage, method_options) - @usage, @desc, @method_options = nil - true - elsif self.all_tasks[meth.to_s] || meth.to_sym == :method_missing - true - else - puts "[WARNING] Attempted to create task #{meth.inspect} without usage or description. " << - "Call desc if you want this method to be available as task or declare it inside a " << - "no_tasks{} block. Invoked from #{caller[1].inspect}." - false - end - end - - def initialize_added #:nodoc: - class_options.merge!(method_options) - @method_options = nil - end - - # Receives a task name (can be nil), and try to get a map from it. - # If a map can't be found use the sent name or the default task. - # - def normalize_task_name(meth) #:nodoc: - mapping = map[meth.to_s] - meth = mapping || meth || default_task - meth.to_s.gsub('-','_') # treat foo-bar > foo_bar - end - end - - include Thor::Base - - map HELP_MAPPINGS => :help - - desc "help [TASK]", "Describe available tasks or one specific task" - def help(task=nil) - self.class.help(shell, task, :namespace => task && task.include?(?:)) - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions.rb deleted file mode 100644 index d561ccb2aa..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions.rb +++ /dev/null @@ -1,273 +0,0 @@ -require 'fileutils' - -Dir[File.join(File.dirname(__FILE__), "actions", "*.rb")].each do |action| - require action -end - -class Thor - module Actions - attr_accessor :behavior - - def self.included(base) #:nodoc: - base.extend ClassMethods - end - - module ClassMethods - # Hold source paths for one Thor instance. source_paths_for_search is the - # method responsible to gather source_paths from this current class, - # inherited paths and the source root. - # - def source_paths - @source_paths ||= [] - end - - # Returns the source paths in the following order: - # - # 1) This class source paths - # 2) Source root - # 3) Parents source paths - # - def source_paths_for_search - paths = [] - paths += self.source_paths - paths << self.source_root if self.respond_to?(:source_root) - paths += from_superclass(:source_paths, []) - paths - end - - # Add runtime options that help actions execution. - # - def add_runtime_options! - class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime, - :desc => "Run but do not make any changes" - - class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime, - :desc => "Overwrite files that already exist" - - class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime, - :desc => "Skip files that already exist" - - class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime, - :desc => "Supress status output" - end - end - - # Extends initializer to add more configuration options. - # - # ==== Configuration - # behavior:: The actions default behavior. Can be :invoke or :revoke. - # It also accepts :force, :skip and :pretend to set the behavior - # and the respective option. - # - # destination_root:: The root directory needed for some actions. - # - def initialize(args=[], options={}, config={}) - self.behavior = case config[:behavior].to_s - when "force", "skip" - _cleanup_options_and_set(options, config[:behavior]) - :invoke - when "revoke" - :revoke - else - :invoke - end - - super - self.destination_root = config[:destination_root] - end - - # Wraps an action object and call it accordingly to the thor class behavior. - # - def action(instance) #:nodoc: - if behavior == :revoke - instance.revoke! - else - instance.invoke! - end - end - - # Returns the root for this thor class (also aliased as destination root). - # - def destination_root - @destination_stack.last - end - - # Sets the root for this thor class. Relatives path are added to the - # directory where the script was invoked and expanded. - # - def destination_root=(root) - @destination_stack ||= [] - @destination_stack[0] = File.expand_path(root || '') - end - - # Returns the given path relative to the absolute root (ie, root where - # the script started). - # - def relative_to_original_destination_root(path, remove_dot=true) - path = path.gsub(@destination_stack[0], '.') - remove_dot ? (path[2..-1] || '') : path - end - - # Holds source paths in instance so they can be manipulated. - # - def source_paths - @source_paths ||= self.class.source_paths_for_search - end - - # Receives a file or directory and search for it in the source paths. - # - def find_in_source_paths(file) - relative_root = relative_to_original_destination_root(destination_root, false) - - source_paths.each do |source| - source_file = File.expand_path(file, File.join(source, relative_root)) - return source_file if File.exists?(source_file) - end - - if source_paths.empty? - raise Error, "You don't have any source path defined for class #{self.class.name}. To fix this, " << - "you can define a source_root in your class." - else - raise Error, "Could not find #{file.inspect} in source paths." - end - end - - # Do something in the root or on a provided subfolder. If a relative path - # is given it's referenced from the current root. The full path is yielded - # to the block you provide. The path is set back to the previous path when - # the method exits. - # - # ==== Parameters - # dir:: the directory to move to. - # config:: give :verbose => true to log and use padding. - # - def inside(dir='', config={}, &block) - verbose = config.fetch(:verbose, false) - - say_status :inside, dir, verbose - shell.padding += 1 if verbose - @destination_stack.push File.expand_path(dir, destination_root) - - FileUtils.mkdir_p(destination_root) unless File.exist?(destination_root) - FileUtils.cd(destination_root) { block.arity == 1 ? yield(destination_root) : yield } - - @destination_stack.pop - shell.padding -= 1 if verbose - end - - # Goes to the root and execute the given block. - # - def in_root - inside(@destination_stack.first) { yield } - end - - # Loads an external file and execute it in the instance binding. - # - # ==== Parameters - # path:: The path to the file to execute. Can be a web address or - # a relative path from the source root. - # - # ==== Examples - # - # apply "http://gist.github.com/103208" - # - # apply "recipes/jquery.rb" - # - def apply(path, config={}) - verbose = config.fetch(:verbose, true) - path = find_in_source_paths(path) unless path =~ /^http\:\/\// - - say_status :apply, path, verbose - shell.padding += 1 if verbose - instance_eval(open(path).read) - shell.padding -= 1 if verbose - end - - # Executes a command. - # - # ==== Parameters - # command:: the command to be executed. - # config:: give :verbose => false to not log the status. Specify :with - # to append an executable to command executation. - # - # ==== Example - # - # inside('vendor') do - # run('ln -s ~/edge rails') - # end - # - def run(command, config={}) - return unless behavior == :invoke - - destination = relative_to_original_destination_root(destination_root, false) - desc = "#{command} from #{destination.inspect}" - - if config[:with] - desc = "#{File.basename(config[:with].to_s)} #{desc}" - command = "#{config[:with]} #{command}" - end - - say_status :run, desc, config.fetch(:verbose, true) - system(command) unless options[:pretend] - end - - # Executes a ruby script (taking into account WIN32 platform quirks). - # - # ==== Parameters - # command:: the command to be executed. - # config:: give :verbose => false to not log the status. - # - def run_ruby_script(command, config={}) - return unless behavior == :invoke - run "#{command}", config.merge(:with => Thor::Util.ruby_command) - end - - # Run a thor command. A hash of options can be given and it's converted to - # switches. - # - # ==== Parameters - # task:: the task to be invoked - # args:: arguments to the task - # config:: give :verbose => false to not log the status. Other options - # are given as parameter to Thor. - # - # ==== Examples - # - # thor :install, "http://gist.github.com/103208" - # #=> thor install http://gist.github.com/103208 - # - # thor :list, :all => true, :substring => 'rails' - # #=> thor list --all --substring=rails - # - def thor(task, *args) - config = args.last.is_a?(Hash) ? args.pop : {} - verbose = config.key?(:verbose) ? config.delete(:verbose) : true - - args.unshift task - args.push Thor::Options.to_switches(config) - command = args.join(' ').strip - - run command, :with => :thor, :verbose => verbose - end - - protected - - # Allow current root to be shared between invocations. - # - def _shared_configuration #:nodoc: - super.merge!(:destination_root => self.destination_root) - end - - def _cleanup_options_and_set(options, key) #:nodoc: - case options - when Array - %w(--force -f --skip -s).each { |i| options.delete(i) } - options << "--#{key}" - when Hash - [:force, :skip, "force", "skip"].each { |i| options.delete(i) } - options.merge!(key => true) - end - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/create_file.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/create_file.rb deleted file mode 100644 index 8f6badee27..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/create_file.rb +++ /dev/null @@ -1,102 +0,0 @@ -require 'thor/actions/empty_directory' - -class Thor - module Actions - - # Create a new file relative to the destination root with the given data, - # which is the return value of a block or a data string. - # - # ==== Parameters - # destination:: the relative path to the destination root. - # data:: the data to append to the file. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # create_file "lib/fun_party.rb" do - # hostname = ask("What is the virtual hostname I should use?") - # "vhost.name = #{hostname}" - # end - # - # create_file "config/apach.conf", "your apache config" - # - def create_file(destination, data=nil, config={}, &block) - action CreateFile.new(self, destination, block || data.to_s, config) - end - alias :add_file :create_file - - # AddFile is a subset of Template, which instead of rendering a file with - # ERB, it gets the content from the user. - # - class CreateFile < EmptyDirectory #:nodoc: - attr_reader :data - - def initialize(base, destination, data, config={}) - @data = data - super(base, destination, config) - end - - # Checks if the content of the file at the destination is identical to the rendered result. - # - # ==== Returns - # Boolean:: true if it is identical, false otherwise. - # - def identical? - exists? && File.read(destination) == render - end - - # Holds the content to be added to the file. - # - def render - @render ||= if data.is_a?(Proc) - data.call - else - data - end - end - - def invoke! - invoke_with_conflict_check do - FileUtils.mkdir_p(File.dirname(destination)) - File.open(destination, 'w'){ |f| f.write render } - end - end - - protected - - # Now on conflict we check if the file is identical or not. - # - def on_conflict_behavior(&block) - if identical? - say_status :identical, :blue - else - options = base.options.merge(config) - force_or_skip_or_conflict(options[:force], options[:skip], &block) - end - end - - # If force is true, run the action, otherwise check if it's not being - # skipped. If both are false, show the file_collision menu, if the menu - # returns true, force it, otherwise skip. - # - def force_or_skip_or_conflict(force, skip, &block) - if force - say_status :force, :yellow - block.call unless pretend? - elsif skip - say_status :skip, :yellow - else - say_status :conflict, :red - force_or_skip_or_conflict(force_on_collision?, true, &block) - end - end - - # Shows the file collision menu to the user and gets the result. - # - def force_on_collision? - base.shell.file_collision(destination){ render } - end - - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/directory.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/directory.rb deleted file mode 100644 index 063ac57406..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/directory.rb +++ /dev/null @@ -1,89 +0,0 @@ -require 'thor/actions/empty_directory' - -class Thor - module Actions - - # Copies recursively the files from source directory to root directory. - # If any of the files finishes with .tt, it's considered to be a template - # and is placed in the destination without the extension .tt. If any - # empty directory is found, it's copied and all .empty_directory files are - # ignored. Remember that file paths can also be encoded, let's suppose a doc - # directory with the following files: - # - # doc/ - # components/.empty_directory - # README - # rdoc.rb.tt - # %app_name%.rb - # - # When invoked as: - # - # directory "doc" - # - # It will create a doc directory in the destination with the following - # files (assuming that the app_name is "blog"): - # - # doc/ - # components/ - # README - # rdoc.rb - # blog.rb - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # If :recursive => false, does not look for paths recursively. - # - # ==== Examples - # - # directory "doc" - # directory "doc", "docs", :recursive => false - # - def directory(source, destination=nil, config={}) - action Directory.new(self, source, destination || source, config) - end - - class Directory < EmptyDirectory #:nodoc: - attr_reader :source - - def initialize(base, source, destination=nil, config={}) - @source = File.expand_path(base.find_in_source_paths(source.to_s)) - super(base, destination, { :recursive => true }.merge(config)) - end - - def invoke! - base.empty_directory given_destination, config - execute! - end - - def revoke! - execute! - end - - protected - - def execute! - lookup = config[:recursive] ? File.join(source, '**') : source - lookup = File.join(lookup, '{*,.[a-z]*}') - - Dir[lookup].each do |file_source| - next if File.directory?(file_source) - file_destination = File.join(given_destination, file_source.gsub(source, '.')) - - case file_source - when /\.empty_directory$/ - dirname = File.dirname(file_destination).gsub(/\/\.$/, '') - next if dirname == given_destination - base.empty_directory(dirname, config) - when /\.tt$/ - base.template(file_source, file_destination[0..-4], config) - else - base.copy_file(file_source, file_destination, config) - end - end - end - - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/empty_directory.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/empty_directory.rb deleted file mode 100644 index 03c1fe4af1..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/empty_directory.rb +++ /dev/null @@ -1,133 +0,0 @@ -class Thor - module Actions - - # Creates an empty directory. - # - # ==== Parameters - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # empty_directory "doc" - # - def empty_directory(destination, config={}) - action EmptyDirectory.new(self, destination, config) - end - - # Class which holds create directory logic. This is the base class for - # other actions like create_file and directory. - # - # This implementation is based in Templater actions, created by Jonas Nicklas - # and Michael S. Klishin under MIT LICENSE. - # - class EmptyDirectory #:nodoc: - attr_reader :base, :destination, :given_destination, :relative_destination, :config - - # Initializes given the source and destination. - # - # ==== Parameters - # base:: A Thor::Base instance - # source:: Relative path to the source of this file - # destination:: Relative path to the destination of this file - # config:: give :verbose => false to not log the status. - # - def initialize(base, destination, config={}) - @base, @config = base, { :verbose => true }.merge(config) - self.destination = destination - end - - # Checks if the destination file already exists. - # - # ==== Returns - # Boolean:: true if the file exists, false otherwise. - # - def exists? - ::File.exists?(destination) - end - - def invoke! - invoke_with_conflict_check do - ::FileUtils.mkdir_p(destination) - end - end - - def revoke! - say_status :remove, :red - ::FileUtils.rm_rf(destination) if !pretend? && exists? - end - - protected - - # Shortcut for pretend. - # - def pretend? - base.options[:pretend] - end - - # Sets the absolute destination value from a relative destination value. - # It also stores the given and relative destination. Let's suppose our - # script is being executed on "dest", it sets the destination root to - # "dest". The destination, given_destination and relative_destination - # are related in the following way: - # - # inside "bar" do - # empty_directory "baz" - # end - # - # destination #=> dest/bar/baz - # relative_destination #=> bar/baz - # given_destination #=> baz - # - def destination=(destination) - if destination - @given_destination = convert_encoded_instructions(destination.to_s) - @destination = ::File.expand_path(@given_destination, base.destination_root) - @relative_destination = base.relative_to_original_destination_root(@destination) - end - end - - # Filenames in the encoded form are converted. If you have a file: - # - # %class_name%.rb - # - # It gets the class name from the base and replace it: - # - # user.rb - # - def convert_encoded_instructions(filename) - filename.gsub(/%(.*?)%/) do |string| - instruction = $1.strip - base.respond_to?(instruction) ? base.send(instruction) : string - end - end - - # Receives a hash of options and just execute the block if some - # conditions are met. - # - def invoke_with_conflict_check(&block) - if exists? - on_conflict_behavior(&block) - else - say_status :create, :green - block.call unless pretend? - end - - destination - end - - # What to do when the destination file already exists. - # - def on_conflict_behavior(&block) - say_status :exist, :blue - end - - # Shortcut to say_status shell method. - # - def say_status(status, color) - base.shell.say_status status, relative_destination, color if config[:verbose] - end - - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/file_manipulation.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/file_manipulation.rb deleted file mode 100644 index d77d90d448..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/file_manipulation.rb +++ /dev/null @@ -1,219 +0,0 @@ -require 'erb' -require 'open-uri' - -class Thor - module Actions - - # Copies the file from the relative source to the relative destination. If - # the destination is not given it's assumed to be equal to the source. - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # copy_file "README", "doc/README" - # - # copy_file "doc/README" - # - def copy_file(source, destination=nil, config={}) - destination ||= source - source = File.expand_path(find_in_source_paths(source.to_s)) - - create_file destination, nil, config do - File.read(source) - end - end - - # Gets the content at the given address and places it at the given relative - # destination. If a block is given instead of destination, the content of - # the url is yielded and used as location. - # - # ==== Parameters - # source:: the address of the given content. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # get "http://gist.github.com/103208", "doc/README" - # - # get "http://gist.github.com/103208" do |content| - # content.split("\n").first - # end - # - def get(source, destination=nil, config={}, &block) - source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ /^http\:\/\// - render = open(source).read - - destination ||= if block_given? - block.arity == 1 ? block.call(render) : block.call - else - File.basename(source) - end - - create_file destination, render, config - end - - # Gets an ERB template at the relative source, executes it and makes a copy - # at the relative destination. If the destination is not given it's assumed - # to be equal to the source removing .tt from the filename. - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # template "README", "doc/README" - # - # template "doc/README" - # - def template(source, destination=nil, config={}) - destination ||= source - source = File.expand_path(find_in_source_paths(source.to_s)) - context = instance_eval('binding') - - create_file destination, nil, config do - ERB.new(::File.read(source), nil, '-').result(context) - end - end - - # Changes the mode of the given file or directory. - # - # ==== Parameters - # mode:: the file mode - # path:: the name of the file to change mode - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # chmod "script/*", 0755 - # - def chmod(path, mode, config={}) - return unless behavior == :invoke - path = File.expand_path(path, destination_root) - say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true) - FileUtils.chmod_R(mode, path) unless options[:pretend] - end - - # Prepend text to a file. Since it depends on inject_into_file, it's reversible. - # - # ==== Parameters - # path:: path of the file to be changed - # data:: the data to prepend to the file, can be also given as a block. - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # prepend_file 'config/environments/test.rb', 'config.gem "rspec"' - # - # prepend_file 'config/environments/test.rb' do - # 'config.gem "rspec"' - # end - # - def prepend_file(path, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - config.merge!(:after => /\A/) - inject_into_file(path, *(args << config), &block) - end - - # Append text to a file. Since it depends on inject_into_file, it's reversible. - # - # ==== Parameters - # path:: path of the file to be changed - # data:: the data to append to the file, can be also given as a block. - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # append_file 'config/environments/test.rb', 'config.gem "rspec"' - # - # append_file 'config/environments/test.rb' do - # 'config.gem "rspec"' - # end - # - def append_file(path, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - config.merge!(:before => /\z/) - inject_into_file(path, *(args << config), &block) - end - - # Injects text right after the class definition. Since it depends on - # inject_into_file, it's reversible. - # - # ==== Parameters - # path:: path of the file to be changed - # klass:: the class to be manipulated - # data:: the data to append to the class, can be also given as a block. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # inject_into_class "app/controllers/application_controller.rb", " filter_parameter :password\n" - # - # inject_into_class "app/controllers/application_controller.rb", ApplicationController do - # " filter_parameter :password\n" - # end - # - def inject_into_class(path, klass, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - config.merge!(:after => /class #{klass}\n|class #{klass} .*\n/) - inject_into_file(path, *(args << config), &block) - end - - # Run a regular expression replacement on a file. - # - # ==== Parameters - # path:: path of the file to be changed - # flag:: the regexp or string to be replaced - # replacement:: the replacement, can be also given as a block - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1' - # - # gsub_file 'README', /rake/, :green do |match| - # match << " no more. Use thor!" - # end - # - def gsub_file(path, flag, *args, &block) - return unless behavior == :invoke - config = args.last.is_a?(Hash) ? args.pop : {} - - path = File.expand_path(path, destination_root) - say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true) - - unless options[:pretend] - content = File.read(path) - content.gsub!(flag, *args, &block) - File.open(path, 'wb') { |file| file.write(content) } - end - end - - # Removes a file at the given location. - # - # ==== Parameters - # path:: path of the file to be changed - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # remove_file 'README' - # remove_file 'app/controllers/application_controller.rb' - # - def remove_file(path, config={}) - return unless behavior == :invoke - path = File.expand_path(path, destination_root) - - say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true) - ::FileUtils.rm_rf(path) if !options[:pretend] && File.exists?(path) - end - alias :remove_dir :remove_file - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/inject_into_file.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/inject_into_file.rb deleted file mode 100644 index 0636ec6591..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/actions/inject_into_file.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'thor/actions/empty_directory' - -class Thor - module Actions - - # Injects the given content into a file. Different from gsub_file, this - # method is reversible. - # - # ==== Parameters - # destination:: Relative path to the destination root - # data:: Data to add to the file. Can be given as a block. - # config:: give :verbose => false to not log the status and the flag - # for injection (:after or :before). - # - # ==== Examples - # - # inject_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n" - # - # inject_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do - # gems = ask "Which gems would you like to add?" - # gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n") - # end - # - def inject_into_file(destination, *args, &block) - if block_given? - data, config = block, args.shift - else - data, config = args.shift, args.shift - end - action InjectIntoFile.new(self, destination, data, config) - end - - class InjectIntoFile < EmptyDirectory #:nodoc: - attr_reader :replacement, :flag, :behavior - - def initialize(base, destination, data, config) - super(base, destination, { :verbose => true }.merge(config)) - - @behavior, @flag = if @config.key?(:after) - [:after, @config.delete(:after)] - else - [:before, @config.delete(:before)] - end - - @replacement = data.is_a?(Proc) ? data.call : data - @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp) - end - - def invoke! - say_status :invoke - - content = if @behavior == :after - '\0' + replacement - else - replacement + '\0' - end - - replace!(/#{flag}/, content) - end - - def revoke! - say_status :revoke - - regexp = if @behavior == :after - content = '\1\2' - /(#{flag})(.*)(#{Regexp.escape(replacement)})/m - else - content = '\2\3' - /(#{Regexp.escape(replacement)})(.*)(#{flag})/m - end - - replace!(regexp, content) - end - - protected - - def say_status(behavior) - status = if flag == /\A/ - behavior == :invoke ? :prepend : :unprepend - elsif flag == /\z/ - behavior == :invoke ? :append : :unappend - else - behavior == :invoke ? :inject : :deinject - end - - super(status, config[:verbose]) - end - - # Adds the content to the file. - # - def replace!(regexp, string) - unless base.options[:pretend] - content = File.read(destination) - content.gsub!(regexp, string) - File.open(destination, 'wb') { |file| file.write(content) } - end - end - - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/base.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/base.rb deleted file mode 100644 index 700d794123..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/base.rb +++ /dev/null @@ -1,517 +0,0 @@ -require 'thor/core_ext/hash_with_indifferent_access' -require 'thor/core_ext/ordered_hash' -require 'thor/error' -require 'thor/shell' -require 'thor/invocation' -require 'thor/parser' -require 'thor/task' -require 'thor/util' - -class Thor - # Shortcuts for help. - HELP_MAPPINGS = %w(-h -? --help -D) - - # Thor methods that should not be overwritten by the user. - THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root - action add_file create_file in_root inside run run_ruby_script) - - module Base - attr_accessor :options - - # It receives arguments in an Array and two hashes, one for options and - # other for configuration. - # - # Notice that it does not check if all required arguments were supplied. - # It should be done by the parser. - # - # ==== Parameters - # args:: An array of objects. The objects are applied to their - # respective accessors declared with argument. - # - # options:: An options hash that will be available as self.options. - # The hash given is converted to a hash with indifferent - # access, magic predicates (options.skip?) and then frozen. - # - # config:: Configuration for this Thor class. - # - def initialize(args=[], options={}, config={}) - Thor::Arguments.parse(self.class.arguments, args).each do |key, value| - send("#{key}=", value) - end - - parse_options = self.class.class_options - - if options.is_a?(Array) - task_options = config.delete(:task_options) # hook for start - parse_options = parse_options.merge(task_options) if task_options - array_options, hash_options = options, {} - else - array_options, hash_options = [], options - end - - options = Thor::Options.parse(parse_options, array_options) - self.options = Thor::CoreExt::HashWithIndifferentAccess.new(options).merge!(hash_options) - self.options.freeze - end - - class << self - def included(base) #:nodoc: - base.send :extend, ClassMethods - base.send :include, Invocation - base.send :include, Shell - end - - # Returns the classes that inherits from Thor or Thor::Group. - # - # ==== Returns - # Array[Class] - # - def subclasses - @subclasses ||= [] - end - - # Returns the files where the subclasses are kept. - # - # ==== Returns - # Hash[path => Class] - # - def subclass_files - @subclass_files ||= Hash.new{ |h,k| h[k] = [] } - end - - # Whenever a class inherits from Thor or Thor::Group, we should track the - # class and the file on Thor::Base. This is the method responsable for it. - # - def register_klass_file(klass) #:nodoc: - file = caller[1].match(/(.*):\d+/)[1] - Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass) - - file_subclasses = Thor::Base.subclass_files[File.expand_path(file)] - file_subclasses << klass unless file_subclasses.include?(klass) - end - end - - module ClassMethods - # Adds an argument to the class and creates an attr_accessor for it. - # - # Arguments are different from options in several aspects. The first one - # is how they are parsed from the command line, arguments are retrieved - # from position: - # - # thor task NAME - # - # Instead of: - # - # thor task --name=NAME - # - # Besides, arguments are used inside your code as an accessor (self.argument), - # while options are all kept in a hash (self.options). - # - # Finally, arguments cannot have type :default or :boolean but can be - # optional (supplying :optional => :true or :required => false), although - # you cannot have a required argument after a non-required argument. If you - # try it, an error is raised. - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described below. - # - # ==== Options - # :desc - Description for the argument. - # :required - If the argument is required or not. - # :optional - If the argument is optional or not. - # :type - The type of the argument, can be :string, :hash, :array, :numeric. - # :default - Default value for this argument. It cannot be required and have default values. - # :banner - String to show on usage notes. - # - # ==== Errors - # ArgumentError:: Raised if you supply a required argument after a non required one. - # - def argument(name, options={}) - is_thor_reserved_word?(name, :argument) - no_tasks { attr_accessor name } - - required = if options.key?(:optional) - !options[:optional] - elsif options.key?(:required) - options[:required] - else - options[:default].nil? - end - - remove_argument name - - arguments.each do |argument| - next if argument.required? - raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " << - "the non-required argument #{argument.human_name.inspect}." - end if required - - arguments << Thor::Argument.new(name, options[:desc], required, options[:type], - options[:default], options[:banner]) - end - - # Returns this class arguments, looking up in the ancestors chain. - # - # ==== Returns - # Array[Thor::Argument] - # - def arguments - @arguments ||= from_superclass(:arguments, []) - end - - # Adds a bunch of options to the set of class options. - # - # class_options :foo => false, :bar => :required, :baz => :string - # - # If you prefer more detailed declaration, check class_option. - # - # ==== Parameters - # Hash[Symbol => Object] - # - def class_options(options=nil) - @class_options ||= from_superclass(:class_options, {}) - build_options(options, @class_options) if options - @class_options - end - - # Adds an option to the set of class options - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described below. - # - # ==== Options - # :desc - Description for the argument. - # :required - If the argument is required or not. - # :default - Default value for this argument. - # :group - The group for this options. Use by class options to output options in different levels. - # :aliases - Aliases for this option. - # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. - # :banner - String to show on usage notes. - # - def class_option(name, options={}) - build_option(name, options, class_options) - end - - # Removes a previous defined argument. If :undefine is given, undefine - # accessors as well. - # - # ==== Paremeters - # names:: Arguments to be removed - # - # ==== Examples - # - # remove_argument :foo - # remove_argument :foo, :bar, :baz, :undefine => true - # - def remove_argument(*names) - options = names.last.is_a?(Hash) ? names.pop : {} - - names.each do |name| - arguments.delete_if { |a| a.name == name.to_s } - undef_method name, "#{name}=" if options[:undefine] - end - end - - # Removes a previous defined class option. - # - # ==== Paremeters - # names:: Class options to be removed - # - # ==== Examples - # - # remove_class_option :foo - # remove_class_option :foo, :bar, :baz - # - def remove_class_option(*names) - names.each do |name| - class_options.delete(name) - end - end - - # Defines the group. This is used when thor list is invoked so you can specify - # that only tasks from a pre-defined group will be shown. Defaults to standard. - # - # ==== Parameters - # name - # - def group(name=nil) - case name - when nil - @group ||= from_superclass(:group, 'standard') - else - @group = name.to_s - end - end - - # Returns the tasks for this Thor class. - # - # ==== Returns - # OrderedHash:: An ordered hash with tasks names as keys and Thor::Task - # objects as values. - # - def tasks - @tasks ||= Thor::CoreExt::OrderedHash.new - end - - # Returns the tasks for this Thor class and all subclasses. - # - # ==== Returns - # OrderedHash:: An ordered hash with tasks names as keys and Thor::Task - # objects as values. - # - def all_tasks - @all_tasks ||= from_superclass(:all_tasks, Thor::CoreExt::OrderedHash.new) - @all_tasks.merge(tasks) - end - - # Removes a given task from this Thor class. This is usually done if you - # are inheriting from another class and don't want it to be available - # anymore. - # - # By default it only remove the mapping to the task. But you can supply - # :undefine => true to undefine the method from the class as well. - # - # ==== Parameters - # name:: The name of the task to be removed - # options:: You can give :undefine => true if you want tasks the method - # to be undefined from the class as well. - # - def remove_task(*names) - options = names.last.is_a?(Hash) ? names.pop : {} - - names.each do |name| - tasks.delete(name.to_s) - all_tasks.delete(name.to_s) - undef_method name if options[:undefine] - end - end - - # All methods defined inside the given block are not added as tasks. - # - # So you can do: - # - # class MyScript < Thor - # no_tasks do - # def this_is_not_a_task - # end - # end - # end - # - # You can also add the method and remove it from the task list: - # - # class MyScript < Thor - # def this_is_not_a_task - # end - # remove_task :this_is_not_a_task - # end - # - def no_tasks - @no_tasks = true - yield - @no_tasks = false - end - - # Sets the namespace for the Thor or Thor::Group class. By default the - # namespace is retrieved from the class name. If your Thor class is named - # Scripts::MyScript, the help method, for example, will be called as: - # - # thor scripts:my_script -h - # - # If you change the namespace: - # - # namespace :my_scripts - # - # You change how your tasks are invoked: - # - # thor my_scripts -h - # - # Finally, if you change your namespace to default: - # - # namespace :default - # - # Your tasks can be invoked with a shortcut. Instead of: - # - # thor :my_task - # - def namespace(name=nil) - case name - when nil - @namespace ||= Thor::Util.namespace_from_thor_class(self, false) - else - @namespace = name.to_s - end - end - - # Default way to start generators from the command line. - # - def start(given_args=ARGV, config={}) - config[:shell] ||= Thor::Base.shell.new - yield - rescue Thor::Error => e - if given_args.include?("--debug") - raise e - else - config[:shell].error e.message - end - exit(1) if exit_on_failure? - end - - protected - - # Prints the class options per group. If an option does not belong to - # any group, it uses the ungrouped name value. This method provide to - # hooks to add extra options, one of them if the third argument called - # extra_group that should be a hash in the format :group => Array[Options]. - # - # The second is by returning a lambda used to print values. The lambda - # requires two options: the group name and the array of options. - # - def class_options_help(shell, ungrouped_name=nil, extra_group=nil) #:nodoc: - groups = {} - - class_options.each do |_, value| - groups[value.group] ||= [] - groups[value.group] << value - end - - printer = proc do |group_name, options| - list = [] - padding = options.collect{ |o| o.aliases.size }.max.to_i * 4 - - options.each do |option| - item = [ option.usage(padding) ] - item.push(option.description ? "# #{option.description}" : "") - - list << item - list << [ "", "# Default: #{option.default}" ] if option.show_default? - end - - unless list.empty? - shell.say(group_name ? "#{group_name} options:" : "Options:") - shell.print_table(list, :ident => 2) - shell.say "" - end - end - - # Deal with default group - global_options = groups.delete(nil) || [] - printer.call(ungrouped_name, global_options) if global_options - - # Print all others - groups = extra_group.merge(groups) if extra_group - groups.each(&printer) - printer - end - - # Raises an error if the word given is a Thor reserved word. - # - def is_thor_reserved_word?(word, type) #:nodoc: - return false unless THOR_RESERVED_WORDS.include?(word.to_s) - raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}" - end - - # Build an option and adds it to the given scope. - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described in both class_option and method_option. - # - def build_option(name, options, scope) #:nodoc: - scope[name] = Thor::Option.new(name, options[:desc], options[:required], - options[:type], options[:default], options[:banner], - options[:group], options[:aliases]) - end - - # Receives a hash of options, parse them and add to the scope. This is a - # fast way to set a bunch of options: - # - # build_options :foo => true, :bar => :required, :baz => :string - # - # ==== Parameters - # Hash[Symbol => Object] - # - def build_options(options, scope) #:nodoc: - options.each do |key, value| - scope[key] = Thor::Option.parse(key, value) - end - end - - # Finds a task with the given name. If the task belongs to the current - # class, just return it, otherwise dup it and add the fresh copy to the - # current task hash. - # - def find_and_refresh_task(name) #:nodoc: - task = if task = tasks[name.to_s] - task - elsif task = all_tasks[name.to_s] - tasks[name.to_s] = task.clone - else - raise ArgumentError, "You supplied :for => #{name.inspect}, but the task #{name.inspect} could not be found." - end - end - - # Everytime someone inherits from a Thor class, register the klass - # and file into baseclass. - # - def inherited(klass) - Thor::Base.register_klass_file(klass) - end - - # Fire this callback whenever a method is added. Added methods are - # tracked as tasks by invoking the create_task method. - # - def method_added(meth) - meth = meth.to_s - - if meth == "initialize" - initialize_added - return - end - - # Return if it's not a public instance method - return unless public_instance_methods.include?(meth) || - public_instance_methods.include?(meth.to_sym) - - return if @no_tasks || !create_task(meth) - - is_thor_reserved_word?(meth, :task) - Thor::Base.register_klass_file(self) - end - - # Retrieves a value from superclass. If it reaches the baseclass, - # returns default. - # - def from_superclass(method, default=nil) - if self == baseclass || !superclass.respond_to?(method, true) - default - else - value = superclass.send(method) - value.dup if value - end - end - - # A flag that makes the process exit with status 1 if any error happens. - # - def exit_on_failure? - false - end - - # SIGNATURE: Sets the baseclass. This is where the superclass lookup - # finishes. - def baseclass #:nodoc: - end - - # SIGNATURE: Creates a new task if valid_task? is true. This method is - # called when a new method is added to the class. - def create_task(meth) #:nodoc: - end - - # SIGNATURE: Defines behavior when the initialize method is added to the - # class. - def initialize_added #:nodoc: - end - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/hash_with_indifferent_access.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/hash_with_indifferent_access.rb deleted file mode 100644 index 78bc5cf4bf..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/hash_with_indifferent_access.rb +++ /dev/null @@ -1,75 +0,0 @@ -class Thor - module CoreExt #:nodoc: - - # A hash with indifferent access and magic predicates. - # - # hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true - # - # hash[:foo] #=> 'bar' - # hash['foo'] #=> 'bar' - # hash.foo? #=> true - # - class HashWithIndifferentAccess < ::Hash #:nodoc: - - def initialize(hash={}) - super() - hash.each do |key, value| - self[convert_key(key)] = value - end - end - - def [](key) - super(convert_key(key)) - end - - def []=(key, value) - super(convert_key(key), value) - end - - def delete(key) - super(convert_key(key)) - end - - def values_at(*indices) - indices.collect { |key| self[convert_key(key)] } - end - - def merge(other) - dup.merge!(other) - end - - def merge!(other) - other.each do |key, value| - self[convert_key(key)] = value - end - self - end - - protected - - def convert_key(key) - key.is_a?(Symbol) ? key.to_s : key - end - - # Magic predicates. For instance: - # - # options.force? # => !!options['force'] - # options.shebang # => "/usr/lib/local/ruby" - # options.test_framework?(:rspec) # => options[:test_framework] == :rspec - # - def method_missing(method, *args, &block) - method = method.to_s - if method =~ /^(\w+)\?$/ - if args.empty? - !!self[$1] - else - self[$1] == args.first - end - else - self[method] - end - end - - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/ordered_hash.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/ordered_hash.rb deleted file mode 100644 index 27fea5bb35..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/core_ext/ordered_hash.rb +++ /dev/null @@ -1,100 +0,0 @@ -class Thor - module CoreExt #:nodoc: - - if RUBY_VERSION >= '1.9' - class OrderedHash < ::Hash - end - else - # This class is based on the Ruby 1.9 ordered hashes. - # - # It keeps the semantics and most of the efficiency of normal hashes - # while also keeping track of the order in which elements were set. - # - class OrderedHash #:nodoc: - include Enumerable - - Node = Struct.new(:key, :value, :next, :prev) - - def initialize - @hash = {} - end - - def [](key) - @hash[key] && @hash[key].value - end - - def []=(key, value) - if node = @hash[key] - node.value = value - else - node = Node.new(key, value) - - if @first.nil? - @first = @last = node - else - node.prev = @last - @last.next = node - @last = node - end - end - - @hash[key] = node - value - end - - def delete(key) - if node = @hash[key] - prev_node = node.prev - next_node = node.next - - next_node.prev = prev_node if next_node - prev_node.next = next_node if prev_node - - @first = next_node if @first == node - @last = prev_node if @last == node - - value = node.value - end - - @hash.delete(key) - value - end - - def keys - self.map { |k, v| k } - end - - def values - self.map { |k, v| v } - end - - def each - return unless @first - yield [@first.key, @first.value] - node = @first - yield [node.key, node.value] while node = node.next - self - end - - def merge(other) - hash = self.class.new - - self.each do |key, value| - hash[key] = value - end - - other.each do |key, value| - hash[key] = value - end - - hash - end - - def empty? - @hash.empty? - end - end - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/error.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/error.rb deleted file mode 100644 index f9b31a35d1..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/error.rb +++ /dev/null @@ -1,27 +0,0 @@ -class Thor - # Thor::Error is raised when it's caused by wrong usage of thor classes. Those - # errors have their backtrace supressed and are nicely shown to the user. - # - # Errors that are caused by the developer, like declaring a method which - # overwrites a thor keyword, it SHOULD NOT raise a Thor::Error. This way, we - # ensure that developer errors are shown with full backtrace. - # - class Error < StandardError - end - - # Raised when a task was not found. - # - class UndefinedTaskError < Error - end - - # Raised when a task was found, but not invoked properly. - # - class InvocationError < Error - end - - class RequiredArgumentMissingError < InvocationError - end - - class MalformattedArgumentError < InvocationError - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/group.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/group.rb deleted file mode 100644 index 1e59df2313..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/group.rb +++ /dev/null @@ -1,263 +0,0 @@ -# Thor has a special class called Thor::Group. The main difference to Thor class -# is that it invokes all tasks at once. It also include some methods that allows -# invocations to be done at the class method, which are not available to Thor -# tasks. -# -class Thor::Group - class << self - # The descrition for this Thor::Group. If none is provided, but a source root - # exists, tries to find the USAGE one folder above it, otherwise searches - # in the superclass. - # - # ==== Parameters - # description:: The description for this Thor::Group. - # - def desc(description=nil) - case description - when nil - @desc ||= from_superclass(:desc, nil) - else - @desc = description - end - end - - # Start works differently in Thor::Group, it simply invokes all tasks - # inside the class. - # - def start(given_args=ARGV, config={}) - super do - if Thor::HELP_MAPPINGS.include?(given_args.first) - help(config[:shell]) - return - end - - args, opts = Thor::Options.split(given_args) - new(args, opts, config).invoke - end - end - - # Prints help information. - # - # ==== Options - # short:: When true, shows only usage. - # - def help(shell, options={}) - if options[:short] - shell.say banner - else - shell.say "Usage:" - shell.say " #{banner}" - shell.say - class_options_help(shell) - shell.say self.desc if self.desc - end - end - - # Stores invocations for this class merging with superclass values. - # - def invocations #:nodoc: - @invocations ||= from_superclass(:invocations, {}) - end - - # Stores invocation blocks used on invoke_from_option. - # - def invocation_blocks #:nodoc: - @invocation_blocks ||= from_superclass(:invocation_blocks, {}) - end - - # Invoke the given namespace or class given. It adds an instance - # method that will invoke the klass and task. You can give a block to - # configure how it will be invoked. - # - # The namespace/class given will have its options showed on the help - # usage. Check invoke_from_option for more information. - # - def invoke(*names, &block) - options = names.last.is_a?(Hash) ? names.pop : {} - verbose = options.fetch(:verbose, :white) - - names.each do |name| - invocations[name] = false - invocation_blocks[name] = block if block_given? - - class_eval <<-METHOD, __FILE__, __LINE__ - def _invoke_#{name.to_s.gsub(/\W/, '_')} - klass, task = self.class.prepare_for_invocation(nil, #{name.inspect}) - - if klass - say_status :invoke, #{name.inspect}, #{verbose.inspect} - block = self.class.invocation_blocks[#{name.inspect}] - _invoke_for_class_method klass, task, &block - else - say_status :error, %(#{name.inspect} [not found]), :red - end - end - METHOD - end - end - - # Invoke a thor class based on the value supplied by the user to the - # given option named "name". A class option must be created before this - # method is invoked for each name given. - # - # ==== Examples - # - # class GemGenerator < Thor::Group - # class_option :test_framework, :type => :string - # invoke_from_option :test_framework - # end - # - # ==== Boolean options - # - # In some cases, you want to invoke a thor class if some option is true or - # false. This is automatically handled by invoke_from_option. Then the - # option name is used to invoke the generator. - # - # ==== Preparing for invocation - # - # In some cases you want to customize how a specified hook is going to be - # invoked. You can do that by overwriting the class method - # prepare_for_invocation. The class method must necessarily return a klass - # and an optional task. - # - # ==== Custom invocations - # - # You can also supply a block to customize how the option is giong to be - # invoked. The block receives two parameters, an instance of the current - # class and the klass to be invoked. - # - def invoke_from_option(*names, &block) - options = names.last.is_a?(Hash) ? names.pop : {} - verbose = options.fetch(:verbose, :white) - - names.each do |name| - unless class_options.key?(name) - raise ArgumentError, "You have to define the option #{name.inspect} " << - "before setting invoke_from_option." - end - - invocations[name] = true - invocation_blocks[name] = block if block_given? - - class_eval <<-METHOD, __FILE__, __LINE__ - def _invoke_from_option_#{name.to_s.gsub(/\W/, '_')} - return unless options[#{name.inspect}] - - value = options[#{name.inspect}] - value = #{name.inspect} if TrueClass === value - klass, task = self.class.prepare_for_invocation(#{name.inspect}, value) - - if klass - say_status :invoke, value, #{verbose.inspect} - block = self.class.invocation_blocks[#{name.inspect}] - _invoke_for_class_method klass, task, &block - else - say_status :error, %(\#{value} [not found]), :red - end - end - METHOD - end - end - - # Remove a previously added invocation. - # - # ==== Examples - # - # remove_invocation :test_framework - # - def remove_invocation(*names) - names.each do |name| - remove_task(name) - remove_class_option(name) - invocations.delete(name) - invocation_blocks.delete(name) - end - end - - # Overwrite class options help to allow invoked generators options to be - # shown recursively when invoking a generator. - # - def class_options_help(shell, ungrouped_name=nil, extra_group=nil) #:nodoc: - group_options = {} - - get_options_from_invocations(group_options, class_options) do |klass| - klass.send(:get_options_from_invocations, group_options, class_options) - end - - group_options.merge!(extra_group) if extra_group - super(shell, ungrouped_name, group_options) - end - - # Get invocations array and merge options from invocations. Those - # options are added to group_options hash. Options that already exists - # in base_options are not added twice. - # - def get_options_from_invocations(group_options, base_options) #:nodoc: - invocations.each do |name, from_option| - value = if from_option - option = class_options[name] - option.type == :boolean ? name : option.default - else - name - end - next unless value - - klass, task = prepare_for_invocation(name, value) - next unless klass && klass.respond_to?(:class_options) - - value = value.to_s - human_name = value.respond_to?(:classify) ? value.classify : value - - group_options[human_name] ||= [] - group_options[human_name] += klass.class_options.values.select do |option| - base_options[option.name.to_sym].nil? && option.group.nil? && - !group_options.values.flatten.any? { |i| i.name == option.name } - end - - yield klass if block_given? - end - end - - protected - - # The banner for this class. You can customize it if you are invoking the - # thor class by another ways which is not the Thor::Runner. - # - def banner - "#{self.namespace} #{self.arguments.map {|a| a.usage }.join(' ')}" - end - - def baseclass #:nodoc: - Thor::Group - end - - def create_task(meth) #:nodoc: - tasks[meth.to_s] = Thor::Task.new(meth, nil, nil, nil) - true - end - end - - include Thor::Base - - protected - - # Shortcut to invoke with padding and block handling. Use internally by - # invoke and invoke_from_option class methods. - # - def _invoke_for_class_method(klass, task=nil, *args, &block) #:nodoc: - shell.padding += 1 - - result = if block_given? - if block.arity == 2 - block.call(self, klass) - else - block.call(self, klass, task) - end - else - invoke klass, task, *args - end - - shell.padding -= 1 - result - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/invocation.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/invocation.rb deleted file mode 100644 index 32e6a72454..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/invocation.rb +++ /dev/null @@ -1,178 +0,0 @@ -class Thor - module Invocation - def self.included(base) #:nodoc: - base.extend ClassMethods - end - - module ClassMethods - # Prepare for class methods invocations. This method must return a klass to - # have the invoked class options showed in help messages in generators. - # - def prepare_for_invocation(key, name) #:nodoc: - case name - when Symbol, String - Thor::Util.namespace_to_thor_class_and_task(name.to_s, false) - else - name - end - end - end - - # Make initializer aware of invocations and the initializer proc. - # - def initialize(args=[], options={}, config={}, &block) #:nodoc: - @_invocations = config[:invocations] || Hash.new { |h,k| h[k] = [] } - @_initializer = [ args, options, config ] - super - end - - # Receives a name and invokes it. The name can be a string (either "task" or - # "namespace:task"), a Thor::Task, a Class or a Thor instance. If the task - # cannot be guessed by name, it can also be supplied as second argument. - # - # You can also supply the arguments, options and configuration values for - # the task to be invoked, if none is given, the same values used to - # initialize the invoker are used to initialize the invoked. - # - # ==== Examples - # - # class A < Thor - # def foo - # invoke :bar - # invoke "b:hello", ["José"] - # end - # - # def bar - # invoke "b:hello", ["José"] - # end - # end - # - # class B < Thor - # def hello(name) - # puts "hello #{name}" - # end - # end - # - # You can notice that the method "foo" above invokes two tasks: "bar", - # which belongs to the same class and "hello" which belongs to the class B. - # - # By using an invocation system you ensure that a task is invoked only once. - # In the example above, invoking "foo" will invoke "b:hello" just once, even - # if it's invoked later by "bar" method. - # - # When class A invokes class B, all arguments used on A initialization are - # supplied to B. This allows lazy parse of options. Let's suppose you have - # some rspec tasks: - # - # class Rspec < Thor::Group - # class_option :mock_framework, :type => :string, :default => :rr - # - # def invoke_mock_framework - # invoke "rspec:#{options[:mock_framework]}" - # end - # end - # - # As you noticed, it invokes the given mock framework, which might have its - # own options: - # - # class Rspec::RR < Thor::Group - # class_option :style, :type => :string, :default => :mock - # end - # - # Since it's not rspec concern to parse mock framework options, when RR - # is invoked all options are parsed again, so RR can extract only the options - # that it's going to use. - # - # If you want Rspec::RR to be initialized with its own set of options, you - # have to do that explicitely: - # - # invoke "rspec:rr", [], :style => :foo - # - # Besides giving an instance, you can also give a class to invoke: - # - # invoke Rspec::RR, [], :style => :foo - # - def invoke(name=nil, task=nil, args=nil, opts=nil, config=nil) - task, args, opts, config = nil, task, args, opts if task.nil? || task.is_a?(Array) - args, opts, config = nil, args, opts if args.is_a?(Hash) - - object, task = _prepare_for_invocation(name, task) - klass, instance = _initialize_klass_with_initializer(object, args, opts, config) - - method_args = [] - current = @_invocations[klass] - - iterator = proc do |_, task| - unless current.include?(task.name) - current << task.name - task.run(instance, method_args) - end - end - - if task - args ||= [] - method_args = args[Range.new(klass.arguments.size, -1)] || [] - iterator.call(nil, task) - else - klass.all_tasks.map(&iterator) - end - end - - protected - - # Configuration values that are shared between invocations. - # - def _shared_configuration #:nodoc: - { :invocations => @_invocations } - end - - # Prepare for invocation in the instance level. In this case, we have to - # take into account that a just a task name from the current class was - # given or even a Thor::Task object. - # - def _prepare_for_invocation(name, sent_task=nil) #:nodoc: - if name.is_a?(Thor::Task) - task = name - elsif task = self.class.all_tasks[name.to_s] - object = self - else - object, task = self.class.prepare_for_invocation(nil, name) - task ||= sent_task - end - - # If the object was not set, use self and use the name as task. - object, task = self, name unless object - return object, _validate_task(object, task) - end - - # Check if the object given is a Thor class object and get a task object - # for it. - # - def _validate_task(object, task) #:nodoc: - klass = object.is_a?(Class) ? object : object.class - raise "Expected Thor class, got #{klass}" unless klass <= Thor::Base - - task ||= klass.default_task if klass <= Thor - task = klass.all_tasks[task.to_s] || Thor::Task::Dynamic.new(task) if task && !task.is_a?(Thor::Task) - task - end - - # Initialize klass using values stored in the @_initializer. - # - def _initialize_klass_with_initializer(object, args, opts, config) #:nodoc: - if object.is_a?(Class) - klass = object - - stored_args, stored_opts, stored_config = @_initializer - args ||= stored_args.dup - opts ||= stored_opts.dup - - config ||= {} - config = stored_config.merge(_shared_configuration).merge!(config) - [ klass, klass.new(args, opts, config) ] - else - [ object.class, object ] - end - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser.rb deleted file mode 100644 index 57a3f6e1a5..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser.rb +++ /dev/null @@ -1,4 +0,0 @@ -require 'thor/parser/argument' -require 'thor/parser/arguments' -require 'thor/parser/option' -require 'thor/parser/options' diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/argument.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/argument.rb deleted file mode 100644 index aa8ace4719..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/argument.rb +++ /dev/null @@ -1,67 +0,0 @@ -class Thor - class Argument #:nodoc: - VALID_TYPES = [ :numeric, :hash, :array, :string ] - - attr_reader :name, :description, :required, :type, :default, :banner - alias :human_name :name - - def initialize(name, description=nil, required=true, type=:string, default=nil, banner=nil) - class_name = self.class.name.split("::").last - - raise ArgumentError, "#{class_name} name can't be nil." if name.nil? - raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type) - - @name = name.to_s - @description = description - @required = required || false - @type = (type || :string).to_sym - @default = default - @banner = banner || default_banner - - validate! # Trigger specific validations - end - - def usage - required? ? banner : "[#{banner}]" - end - - def required? - required - end - - def show_default? - case default - when Array, String, Hash - !default.empty? - else - default - end - end - - protected - - def validate! - raise ArgumentError, "An argument cannot be required and have default value." if required? && !default.nil? - end - - def valid_type?(type) - VALID_TYPES.include?(type.to_sym) - end - - def default_banner - case type - when :boolean - nil - when :string, :default - human_name.upcase - when :numeric - "N" - when :hash - "key:value" - when :array - "one two three" - end - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/arguments.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/arguments.rb deleted file mode 100644 index fb5d965e06..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/arguments.rb +++ /dev/null @@ -1,145 +0,0 @@ -class Thor - class Arguments #:nodoc: - NUMERIC = /(\d*\.\d+|\d+)/ - - # Receives an array of args and returns two arrays, one with arguments - # and one with switches. - # - def self.split(args) - arguments = [] - - args.each do |item| - break if item =~ /^-/ - arguments << item - end - - return arguments, args[Range.new(arguments.size, -1)] - end - - def self.parse(base, args) - new(base).parse(args) - end - - # Takes an array of Thor::Argument objects. - # - def initialize(arguments=[]) - @assigns, @non_assigned_required = {}, [] - @switches = arguments - - arguments.each do |argument| - if argument.default - @assigns[argument.human_name] = argument.default - elsif argument.required? - @non_assigned_required << argument - end - end - end - - def parse(args) - @pile = args.dup - - @switches.each do |argument| - break unless peek - @non_assigned_required.delete(argument) - @assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name) - end - - check_requirement! - @assigns - end - - private - - def peek - @pile.first - end - - def shift - @pile.shift - end - - def unshift(arg) - unless arg.kind_of?(Array) - @pile.unshift(arg) - else - @pile = arg + @pile - end - end - - def current_is_value? - peek && peek.to_s !~ /^-/ - end - - # Runs through the argument array getting strings that contains ":" and - # mark it as a hash: - # - # [ "name:string", "age:integer" ] - # - # Becomes: - # - # { "name" => "string", "age" => "integer" } - # - def parse_hash(name) - return shift if peek.is_a?(Hash) - hash = {} - - while current_is_value? && peek.include?(?:) - key, value = shift.split(':') - hash[key] = value - end - hash - end - - # Runs through the argument array getting all strings until no string is - # found or a switch is found. - # - # ["a", "b", "c"] - # - # And returns it as an array: - # - # ["a", "b", "c"] - # - def parse_array(name) - return shift if peek.is_a?(Array) - array = [] - - while current_is_value? - array << shift - end - array - end - - # Check if the peel is numeric ofrmat and return a Float or Integer. - # Otherwise raises an error. - # - def parse_numeric(name) - return shift if peek.is_a?(Numeric) - - unless peek =~ NUMERIC && $& == peek - raise MalformattedArgumentError, "expected numeric value for '#{name}'; got #{peek.inspect}" - end - - $&.index('.') ? shift.to_f : shift.to_i - end - - # Parse string, i.e., just return the current value in the pile. - # - def parse_string(name) - shift - end - - # Raises an error if @non_assigned_required array is not empty. - # - def check_requirement! - unless @non_assigned_required.empty? - names = @non_assigned_required.map do |o| - o.respond_to?(:switch_name) ? o.switch_name : o.human_name - end.join("', '") - - class_name = self.class.name.split('::').last.downcase - raise RequiredArgumentMissingError, "no value provided for required #{class_name} '#{names}'" - end - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/option.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/option.rb deleted file mode 100644 index 9e40ec73fa..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/option.rb +++ /dev/null @@ -1,132 +0,0 @@ -class Thor - class Option < Argument #:nodoc: - attr_reader :aliases, :group - - VALID_TYPES = [:boolean, :numeric, :hash, :array, :string] - - def initialize(name, description=nil, required=nil, type=nil, default=nil, banner=nil, group=nil, aliases=nil) - super(name, description, required, type, default, banner) - @aliases = [*aliases].compact - @group = group.to_s.capitalize if group - end - - # This parse quick options given as method_options. It makes several - # assumptions, but you can be more specific using the option method. - # - # parse :foo => "bar" - # #=> Option foo with default value bar - # - # parse [:foo, :baz] => "bar" - # #=> Option foo with default value bar and alias :baz - # - # parse :foo => :required - # #=> Required option foo without default value - # - # parse :foo => 2 - # #=> Option foo with default value 2 and type numeric - # - # parse :foo => :numeric - # #=> Option foo without default value and type numeric - # - # parse :foo => true - # #=> Option foo with default value true and type boolean - # - # The valid types are :boolean, :numeric, :hash, :array and :string. If none - # is given a default type is assumed. This default type accepts arguments as - # string (--foo=value) or booleans (just --foo). - # - # By default all options are optional, unless :required is given. - # - def self.parse(key, value) - if key.is_a?(Array) - name, *aliases = key - else - name, aliases = key, [] - end - - name = name.to_s - default = value - - type = case value - when Symbol - default = nil - - if VALID_TYPES.include?(value) - value - elsif required = (value == :required) - :string - elsif value == :optional - # TODO Remove this warning in the future. - warn "Optional type is deprecated. Choose :boolean or :string instead. Assumed to be :boolean." - :boolean - end - when TrueClass, FalseClass - :boolean - when Numeric - :numeric - when Hash, Array, String - value.class.name.downcase.to_sym - end - - self.new(name.to_s, nil, required, type, default, nil, nil, aliases) - end - - def switch_name - @switch_name ||= dasherized? ? name : dasherize(name) - end - - def human_name - @human_name ||= dasherized? ? undasherize(name) : name - end - - def usage(padding=0) - sample = if banner && !banner.to_s.empty? - "#{switch_name}=#{banner}" - else - switch_name - end - - sample = "[#{sample}]" unless required? - - if aliases.empty? - (" " * padding) << sample - else - "#{aliases.join(', ')}, #{sample}" - end - end - - # Allow some type predicates as: boolean?, string? and etc. - # - def method_missing(method, *args, &block) - given = method.to_s.sub(/\?$/, '').to_sym - if valid_type?(given) - self.type == given - else - super - end - end - - protected - - def validate! - raise ArgumentError, "An option cannot be boolean and required." if boolean? && required? - end - - def valid_type?(type) - VALID_TYPES.include?(type.to_sym) - end - - def dasherized? - name.index('-') == 0 - end - - def undasherize(str) - str.sub(/^-{1,2}/, '') - end - - def dasherize(str) - (str.length > 1 ? "--" : "-") + str.gsub('_', '-') - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/options.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/options.rb deleted file mode 100644 index 75092308b5..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/parser/options.rb +++ /dev/null @@ -1,142 +0,0 @@ -class Thor - # This is a modified version of Daniel Berger's Getopt::Long class, licensed - # under Ruby's license. - # - class Options < Arguments #:nodoc: - LONG_RE = /^(--\w+[-\w+]*)$/ - SHORT_RE = /^(-[a-z])$/i - EQ_RE = /^(--\w+[-\w+]*|-[a-z])=(.*)$/i - SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args - SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i - - # Receives a hash and makes it switches. - # - def self.to_switches(options) - options.map do |key, value| - case value - when true - "--#{key}" - when Array - "--#{key} #{value.map{ |v| v.inspect }.join(' ')}" - when Hash - "--#{key} #{value.map{ |k,v| "#{k}:#{v}" }.join(' ')}" - when nil, false - "" - else - "--#{key} #{value.inspect}" - end - end.join(" ") - end - - # Takes a hash of Thor::Option objects. - # - def initialize(options={}) - options = options.values - super(options) - @shorts, @switches = {}, {} - - options.each do |option| - @switches[option.switch_name] = option - - option.aliases.each do |short| - @shorts[short.to_s] ||= option.switch_name - end - end - end - - def parse(args) - @pile = args.dup - - while peek - if current_is_switch? - case shift - when SHORT_SQ_RE - unshift($1.split('').map { |f| "-#{f}" }) - next - when EQ_RE, SHORT_NUM - unshift($2) - switch = $1 - when LONG_RE, SHORT_RE - switch = $1 - end - - switch = normalize_switch(switch) - next unless option = switch_option(switch) - - @assigns[option.human_name] = parse_peek(switch, option) - else - shift - end - end - - check_requirement! - @assigns - end - - protected - - # Returns true if the current value in peek is a registered switch. - # - def current_is_switch? - case peek - when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM - switch?($1) - when SHORT_SQ_RE - $1.split('').any? { |f| switch?("-#{f}") } - end - end - - def switch?(arg) - switch_option(arg) || @shorts.key?(arg) - end - - def switch_option(arg) - if match = no_or_skip?(arg) - @switches[arg] || @switches["--#{match}"] - else - @switches[arg] - end - end - - def no_or_skip?(arg) - arg =~ /^--(no|skip)-([-\w]+)$/ - $2 - end - - # Check if the given argument is actually a shortcut. - # - def normalize_switch(arg) - @shorts.key?(arg) ? @shorts[arg] : arg - end - - # Parse boolean values which can be given as --foo=true, --foo or --no-foo. - # - def parse_boolean(switch) - if current_is_value? - ["true", "TRUE", "t", "T", true].include?(shift) - else - @switches.key?(switch) || !no_or_skip?(switch) - end - end - - # Parse the value at the peek analyzing if it requires an input or not. - # - def parse_peek(switch, option) - unless current_is_value? - if option.boolean? - # No problem for boolean types - elsif no_or_skip?(switch) - return nil # User set value to nil - elsif option.string? && !option.required? - return option.human_name # Return the option name - else - raise MalformattedArgumentError, "no value provided for option '#{switch}'" - end - end - - @non_assigned_required.delete(option) - send(:"parse_#{option.type}", switch) - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/rake_compat.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/rake_compat.rb deleted file mode 100644 index 0d0757fdda..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/rake_compat.rb +++ /dev/null @@ -1,66 +0,0 @@ -require 'rake' - -class Thor - # Adds a compatibility layer to your Thor classes which allows you to use - # rake package tasks. For example, to use rspec rake tasks, one can do: - # - # require 'thor/rake_compat' - # - # class Default < Thor - # include Thor::RakeCompat - # - # Spec::Rake::SpecTask.new(:spec) do |t| - # t.spec_opts = ['--options', "spec/spec.opts"] - # t.spec_files = FileList['spec/**/*_spec.rb'] - # end - # end - # - module RakeCompat - def self.rake_classes - @rake_classes ||= [] - end - - def self.included(base) - # Hack. Make rakefile point to invoker, so rdoc task is generated properly. - rakefile = File.basename(caller[0].match(/(.*):\d+/)[1]) - Rake.application.instance_variable_set(:@rakefile, rakefile) - self.rake_classes << base - end - end -end - -class Object #:nodoc: - alias :rake_task :task - alias :rake_namespace :namespace - - def task(*args, &block) - task = rake_task(*args, &block) - - if klass = Thor::RakeCompat.rake_classes.last - non_namespaced_name = task.name.split(':').last - - description = non_namespaced_name - description << task.arg_names.map{ |n| n.to_s.upcase }.join(' ') - description.strip! - - klass.desc description, task.comment || non_namespaced_name - klass.send :define_method, non_namespaced_name do |*args| - Rake::Task[task.name.to_sym].invoke(*args) - end - end - - task - end - - def namespace(name, &block) - if klass = Thor::RakeCompat.rake_classes.last - const_name = Thor::Util.camel_case(name.to_s).to_sym - klass.const_set(const_name, Class.new(Thor)) - new_klass = klass.const_get(const_name) - Thor::RakeCompat.rake_classes << new_klass - end - - rake_namespace(name, &block) - Thor::RakeCompat.rake_classes.pop - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/runner.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/runner.rb deleted file mode 100644 index 9dc70ea069..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/runner.rb +++ /dev/null @@ -1,299 +0,0 @@ -require 'fileutils' -require 'open-uri' -require 'yaml' -require 'digest/md5' -require 'pathname' - -class Thor::Runner < Thor #:nodoc: - map "-T" => :list, "-i" => :install, "-u" => :update - - # Override Thor#help so it can give information about any class and any method. - # - def help(meth=nil) - if meth && !self.respond_to?(meth) - initialize_thorfiles(meth) - klass, task = Thor::Util.namespace_to_thor_class_and_task(meth) - # Send mapping -h because it works with Thor::Group too - klass.start(["-h", task].compact, :shell => self.shell) - else - super - end - end - - # If a task is not found on Thor::Runner, method missing is invoked and - # Thor::Runner is then responsable for finding the task in all classes. - # - def method_missing(meth, *args) - meth = meth.to_s - initialize_thorfiles(meth) - klass, task = Thor::Util.namespace_to_thor_class_and_task(meth) - args.unshift(task) if task - klass.start(args, :shell => shell) - end - - desc "install NAME", "Install an optionally named Thor file into your system tasks" - method_options :as => :string, :relative => :boolean - def install(name) - initialize_thorfiles - - # If a directory name is provided as the argument, look for a 'main.thor' - # task in said directory. - begin - if File.directory?(File.expand_path(name)) - base, package = File.join(name, "main.thor"), :directory - contents = open(base).read - else - base, package = name, :file - contents = open(name).read - end - rescue OpenURI::HTTPError - raise Error, "Error opening URI '#{name}'" - rescue Errno::ENOENT - raise Error, "Error opening file '#{name}'" - end - - say "Your Thorfile contains:" - say contents - - return false if no?("Do you wish to continue [y/N]?") - - as = options["as"] || begin - first_line = contents.split("\n")[0] - (match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil - end - - unless as - basename = File.basename(name) - as = ask("Please specify a name for #{name} in the system repository [#{basename}]:") - as = basename if as.empty? - end - - location = if options[:relative] || name =~ /^http:\/\// - name - else - File.expand_path(name) - end - - thor_yaml[as] = { - :filename => Digest::MD5.hexdigest(name + as), - :location => location, - :namespaces => Thor::Util.namespaces_in_content(contents, base) - } - - save_yaml(thor_yaml) - say "Storing thor file in your system repository" - destination = File.join(thor_root, thor_yaml[as][:filename]) - - if package == :file - File.open(destination, "w") { |f| f.puts contents } - else - FileUtils.cp_r(name, destination) - end - - thor_yaml[as][:filename] # Indicate success - end - - desc "uninstall NAME", "Uninstall a named Thor module" - def uninstall(name) - raise Error, "Can't find module '#{name}'" unless thor_yaml[name] - say "Uninstalling #{name}." - FileUtils.rm_rf(File.join(thor_root, "#{thor_yaml[name][:filename]}")) - - thor_yaml.delete(name) - save_yaml(thor_yaml) - - puts "Done." - end - - desc "update NAME", "Update a Thor file from its original location" - def update(name) - raise Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location] - - say "Updating '#{name}' from #{thor_yaml[name][:location]}" - - old_filename = thor_yaml[name][:filename] - self.options = self.options.merge("as" => name) - filename = install(thor_yaml[name][:location]) - - unless filename == old_filename - File.delete(File.join(thor_root, old_filename)) - end - end - - desc "installed", "List the installed Thor modules and tasks" - method_options :internal => :boolean - def installed - initialize_thorfiles(nil, true) - - klasses = Thor::Base.subclasses - klasses -= [Thor, Thor::Runner] unless options["internal"] - - display_klasses(true, klasses) - end - - desc "list [SEARCH]", "List the available thor tasks (--substring means .*SEARCH)" - method_options :substring => :boolean, :group => :string, :all => :boolean - def list(search="") - initialize_thorfiles - - search = ".*#{search}" if options["substring"] - search = /^#{search}.*/i - group = options[:group] || "standard" - - klasses = Thor::Base.subclasses.select do |k| - (options[:all] || k.group == group) && k.namespace =~ search - end - - display_klasses(false, klasses) - end - - private - - def thor_root - Thor::Util.thor_root - end - - def thor_yaml - @thor_yaml ||= begin - yaml_file = File.join(thor_root, "thor.yml") - yaml = YAML.load_file(yaml_file) if File.exists?(yaml_file) - yaml || {} - end - end - - # Save the yaml file. If none exists in thor root, creates one. - # - def save_yaml(yaml) - yaml_file = File.join(thor_root, "thor.yml") - - unless File.exists?(yaml_file) - FileUtils.mkdir_p(thor_root) - yaml_file = File.join(thor_root, "thor.yml") - FileUtils.touch(yaml_file) - end - - File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml } - end - - def self.exit_on_failure? - true - end - - # Load the thorfiles. If relevant_to is supplied, looks for specific files - # in the thor_root instead of loading them all. - # - # By default, it also traverses the current path until find Thor files, as - # described in thorfiles. This look up can be skipped by suppliying - # skip_lookup true. - # - def initialize_thorfiles(relevant_to=nil, skip_lookup=false) - thorfiles(relevant_to, skip_lookup).each do |f| - Thor::Util.load_thorfile(f) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f)) - end - end - - # Finds Thorfiles by traversing from your current directory down to the root - # directory of your system. If at any time we find a Thor file, we stop. - # - # We also ensure that system-wide Thorfiles are loaded first, so local - # Thorfiles can override them. - # - # ==== Example - # - # If we start at /Users/wycats/dev/thor ... - # - # 1. /Users/wycats/dev/thor - # 2. /Users/wycats/dev - # 3. /Users/wycats <-- we find a Thorfile here, so we stop - # - # Suppose we start at c:\Documents and Settings\james\dev\thor ... - # - # 1. c:\Documents and Settings\james\dev\thor - # 2. c:\Documents and Settings\james\dev - # 3. c:\Documents and Settings\james - # 4. c:\Documents and Settings - # 5. c:\ <-- no Thorfiles found! - # - def thorfiles(relevant_to=nil, skip_lookup=false) - # TODO Remove this dealing with deprecated thor when :namespaces: is available as constants - save_yaml(thor_yaml) if Thor::Util.convert_constants_to_namespaces(thor_yaml) - - thorfiles = [] - - unless skip_lookup - Pathname.pwd.ascend do |path| - thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten - break unless thorfiles.empty? - end - end - - files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob) - files += thorfiles - files -= ["#{thor_root}/thor.yml"] - - files.map! do |file| - File.directory?(file) ? File.join(file, "main.thor") : file - end - end - - # Load thorfiles relevant to the given method. If you provide "foo:bar" it - # will load all thor files in the thor.yaml that has "foo" e "foo:bar" - # namespaces registered. - # - def thorfiles_relevant_to(meth) - lookup = [ meth, meth.split(":")[0...-1].join(":") ] - - files = thor_yaml.select do |k, v| - v[:namespaces] && !(v[:namespaces] & lookup).empty? - end - - files.map { |k, v| File.join(thor_root, "#{v[:filename]}") } - end - - # Display information about the given klasses. If with_module is given, - # it shows a table with information extracted from the yaml file. - # - def display_klasses(with_modules=false, klasses=Thor.subclasses) - klasses -= [Thor, Thor::Runner] unless with_modules - raise Error, "No Thor tasks available" if klasses.empty? - - if with_modules && !thor_yaml.empty? - info = [] - labels = ["Modules", "Namespaces"] - - info << labels - info << [ "-" * labels[0].size, "-" * labels[1].size ] - - thor_yaml.each do |name, hash| - info << [ name, hash[:namespaces].join(", ") ] - end - - print_table info - say "" - end - - unless klasses.empty? - klasses.dup.each do |klass| - klasses -= Thor::Util.thor_classes_in(klass) - end - - klasses.each { |k| display_tasks(k) } - else - say "\033[1;34mNo Thor tasks available\033[0m" - end - end - - # Display tasks from the given Thor class. - # - def display_tasks(klass) - unless klass.tasks.empty? - base = klass.namespace - - color = base == "default" ? :magenta : :blue - say shell.set_color(base, color, true) - say "-" * base.length - - klass.help(shell, :short => true, :ident => 0, :namespace => true) - end - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell.rb deleted file mode 100644 index 1dc8f0e5b4..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell.rb +++ /dev/null @@ -1,78 +0,0 @@ -require 'rbconfig' -require 'thor/shell/color' - -class Thor - module Base - # Returns the shell used in all Thor classes. If you are in a Unix platform - # it will use a colored log, otherwise it will use a basic one without color. - # - def self.shell - @shell ||= if Config::CONFIG['host_os'] =~ /mswin|mingw/ - Thor::Shell::Basic - else - Thor::Shell::Color - end - end - - # Sets the shell used in all Thor classes. - # - def self.shell=(klass) - @shell = klass - end - end - - module Shell - SHELL_DELEGATED_METHODS = [:ask, :yes?, :no?, :say, :say_status, :print_list, :print_table] - - # Add shell to initialize config values. - # - # ==== Configuration - # shell:: An instance of the shell to be used. - # - # ==== Examples - # - # class MyScript < Thor - # argument :first, :type => :numeric - # end - # - # MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new - # - def initialize(args=[], options={}, config={}) - super - self.shell = config[:shell] - self.shell.base ||= self if self.shell.respond_to?(:base) - end - - # Holds the shell for the given Thor instance. If no shell is given, - # it gets a default shell from Thor::Base.shell. - # - def shell - @shell ||= Thor::Base.shell.new - end - - # Sets the shell for this thor class. - # - def shell=(shell) - @shell = shell - end - - # Common methods that are delegated to the shell. - # - SHELL_DELEGATED_METHODS.each do |method| - module_eval <<-METHOD, __FILE__, __LINE__ - def #{method}(*args) - shell.#{method}(*args) - end - METHOD - end - - protected - - # Allow shell to be shared between invocations. - # - def _shared_configuration #:nodoc: - super.merge!(:shell => self.shell) - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell/basic.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell/basic.rb deleted file mode 100644 index ea9665380b..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/shell/basic.rb +++ /dev/null @@ -1,219 +0,0 @@ -require 'tempfile' - -class Thor - module Shell - class Basic - attr_accessor :base, :padding - - # Initialize base and padding to nil. - # - def initialize #:nodoc: - @base, @padding = nil, 0 - end - - # Sets the output padding, not allowing less than zero values. - # - def padding=(value) - @padding = [0, value].max - end - - # Ask something to the user and receives a response. - # - # ==== Example - # ask("What is your name?") - # - def ask(statement, color=nil) - say("#{statement} ", color) - $stdin.gets.strip - end - - # Say (print) something to the user. If the sentence ends with a whitespace - # or tab character, a new line is not appended (print + flush). Otherwise - # are passed straight to puts (behavior got from Highline). - # - # ==== Example - # say("I know you knew that.") - # - def say(message="", color=nil, force_new_line=(message.to_s !~ /( |\t)$/)) - message = message.to_s - message = set_color(message, color) if color - - if force_new_line - $stdout.puts(message) - else - $stdout.print(message) - $stdout.flush - end - end - - # Say a status with the given color and appends the message. Since this - # method is used frequently by actions, it allows nil or false to be given - # in log_status, avoiding the message from being shown. If a Symbol is - # given in log_status, it's used as the color. - # - def say_status(status, message, log_status=true) - return if quiet? || log_status == false - spaces = " " * (padding + 1) - color = log_status.is_a?(Symbol) ? log_status : :green - - status = status.to_s.rjust(12) - status = set_color status, color, true if color - say "#{status}#{spaces}#{message}", nil, true - end - - # Make a question the to user and returns true if the user replies "y" or - # "yes". - # - def yes?(statement, color=nil) - ask(statement, color) =~ is?(:yes) - end - - # Make a question the to user and returns true if the user replies "n" or - # "no". - # - def no?(statement, color=nil) - !yes?(statement, color) - end - - # Prints a list of items. - # - # ==== Parameters - # list - # - # ==== Options - # mode:: Can be :rows or :inline. Defaults to :rows. - # ident:: Ident each item with the value given. - # - def print_list(list, options={}) - return if list.empty? - - ident = " " * (options[:ident] || 0) - content = case options[:mode] - when :inline - last = list.pop - "#{list.join(", ")}, and #{last}" - else # rows - ident + list.join("\n#{ident}") - end - - $stdout.puts content - end - - # Prints a table. - # - # ==== Parameters - # Array[Array[String, String, ...]] - # - # ==== Options - # ident:: Ident the first column by ident value. - # - def print_table(table, options={}) - return if table.empty? - - formats = [] - 0.upto(table.first.length - 2) do |i| - maxima = table.max{ |a,b| a[i].size <=> b[i].size }[i].size - formats << "%-#{maxima + 2}s" - end - - formats[0] = formats[0].insert(0, " " * options[:ident]) if options[:ident] - formats << "%s" - - table.each do |row| - row.each_with_index do |column, i| - $stdout.print formats[i] % column.to_s - end - $stdout.puts - end - end - - # Deals with file collision and returns true if the file should be - # overwriten and false otherwise. If a block is given, it uses the block - # response as the content for the diff. - # - # ==== Parameters - # destination:: the destination file to solve conflicts - # block:: an optional block that returns the value to be used in diff - # - def file_collision(destination) - return true if @always_force - options = block_given? ? "[Ynaqdh]" : "[Ynaqh]" - - while true - answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}] - - case answer - when is?(:yes), is?(:force) - return true - when is?(:no), is?(:skip) - return false - when is?(:always) - return @always_force = true - when is?(:quit) - say 'Aborting...' - raise SystemExit - when is?(:diff) - show_diff(destination, yield) if block_given? - say 'Retrying...' - else - say file_collision_help - end - end - end - - # Called if something goes wrong during the execution. This is used by Thor - # internally and should not be used inside your scripts. If someone went - # wrong, you can always raise an exception. If you raise a Thor::Error, it - # will be rescued and wrapped in the method below. - # - def error(statement) - $stderr.puts statement - end - - # Apply color to the given string with optional bold. Disabled in the - # Thor::Shell::Basic class. - # - def set_color(string, color, bold=false) #:nodoc: - string - end - - protected - - def is?(value) #:nodoc: - value = value.to_s - - if value.size == 1 - /\A#{value}\z/i - else - /\A(#{value}|#{value[0,1]})\z/i - end - end - - def file_collision_help #:nodoc: -< e - parse_argument_error(instance, e, caller) - rescue NoMethodError => e - parse_no_method_error(instance, e) - end - - # Returns the formatted usage. If a class is given, the class arguments are - # injected in the usage. - # - def formatted_usage(klass=nil, namespace=false, show_options=true) - formatted = if namespace.is_a?(String) - "#{namespace}:" - elsif klass && namespace - "#{klass.namespace.gsub(/^default/,'')}:" - else - "" - end - - formatted << formatted_arguments(klass) - formatted << " #{formatted_options}" if show_options - formatted.strip! - formatted - end - - # Injects the class arguments into the task usage. - # - def formatted_arguments(klass) - if klass && !klass.arguments.empty? - usage.to_s.gsub(/^#{name}/) do |match| - match << " " << klass.arguments.map{ |a| a.usage }.join(' ') - end - else - usage.to_s - end - end - - # Returns the options usage for this task. - # - def formatted_options - @formatted_options ||= options.map{ |_, o| o.usage }.sort.join(" ") - end - - protected - - # Given a target, checks if this class name is not a private/protected method. - # - def public_method?(instance) #:nodoc: - collection = instance.private_methods + instance.protected_methods - (collection & [name.to_s, name.to_sym]).empty? - end - - # Clean everything that comes from the Thor gempath and remove the caller. - # - def sans_backtrace(backtrace, caller) #:nodoc: - dirname = /^#{Regexp.escape(File.dirname(__FILE__))}/ - saned = backtrace.reject { |frame| frame =~ dirname } - saned -= caller - end - - def parse_argument_error(instance, e, caller) #:nodoc: - backtrace = sans_backtrace(e.backtrace, caller) - - if backtrace.empty? && e.message =~ /wrong number of arguments/ - if instance.is_a?(Thor::Group) - raise e, "'#{name}' was called incorrectly. Are you sure it has arity equals to 0?" - else - raise InvocationError, "'#{name}' was called incorrectly. Call as " << - "'#{formatted_usage(instance.class, true)}'" - end - else - raise e - end - end - - def parse_no_method_error(instance, e) #:nodoc: - if e.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/ - raise UndefinedTaskError, "The #{instance.class.namespace} namespace " << - "doesn't have a '#{name}' task" - else - raise e - end - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/util.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/util.rb deleted file mode 100644 index ebae0a3193..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/util.rb +++ /dev/null @@ -1,251 +0,0 @@ -require 'rbconfig' - -class Thor - module Sandbox #:nodoc: - end - - # This module holds several utilities: - # - # 1) Methods to convert thor namespaces to constants and vice-versa. - # - # Thor::Utils.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz" - # - # 2) Loading thor files and sandboxing: - # - # Thor::Utils.load_thorfile("~/.thor/foo") - # - module Util - - # Receives a namespace and search for it in the Thor::Base subclasses. - # - # ==== Parameters - # namespace:: The namespace to search for. - # - def self.find_by_namespace(namespace) - namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/ - - Thor::Base.subclasses.find do |klass| - klass.namespace == namespace - end - end - - # Receives a constant and converts it to a Thor namespace. Since Thor tasks - # can be added to a sandbox, this method is also responsable for removing - # the sandbox namespace. - # - # This method should not be used in general because it's used to deal with - # older versions of Thor. On current versions, if you need to get the - # namespace from a class, just call namespace on it. - # - # ==== Parameters - # constant:: The constant to be converted to the thor path. - # - # ==== Returns - # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz" - # - def self.namespace_from_thor_class(constant, remove_default=true) - constant = constant.to_s.gsub(/^Thor::Sandbox::/, "") - constant = snake_case(constant).squeeze(":") - constant.gsub!(/^default/, '') if remove_default - constant - end - - # Given the contents, evaluate it inside the sandbox and returns the - # namespaces defined in the sandbox. - # - # ==== Parameters - # contents - # - # ==== Returns - # Array[Object] - # - def self.namespaces_in_content(contents, file=__FILE__) - old_constants = Thor::Base.subclasses.dup - Thor::Base.subclasses.clear - - load_thorfile(file, contents) - - new_constants = Thor::Base.subclasses.dup - Thor::Base.subclasses.replace(old_constants) - - new_constants.map!{ |c| c.namespace } - new_constants.compact! - new_constants - end - - # Returns the thor classes declared inside the given class. - # - def self.thor_classes_in(klass) - Thor::Base.subclasses.select do |subclass| - klass.constants.include?(subclass.name.gsub("#{klass.name}::", '')) - end - end - - # Receives a string and convert it to snake case. SnakeCase returns snake_case. - # - # ==== Parameters - # String - # - # ==== Returns - # String - # - def self.snake_case(str) - return str.downcase if str =~ /^[A-Z_]+$/ - str.gsub(/\B[A-Z]/, '_\&').squeeze('_') =~ /_*(.*)/ - return $+.downcase - end - - # Receives a string and convert it to camel case. camel_case returns CamelCase. - # - # ==== Parameters - # String - # - # ==== Returns - # String - # - def self.camel_case(str) - return str if str !~ /_/ && str =~ /[A-Z]+.*/ - str.split('_').map { |i| i.capitalize }.join - end - - # Receives a namespace and tries to retrieve a Thor or Thor::Group class - # from it. It first searches for a class using the all the given namespace, - # if it's not found, removes the highest entry and searches for the class - # again. If found, returns the highest entry as the class name. - # - # ==== Examples - # - # class Foo::Bar < Thor - # def baz - # end - # end - # - # class Baz::Foo < Thor::Group - # end - # - # Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default task - # Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil - # Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz" - # - # ==== Parameters - # namespace - # - # ==== Errors - # Thor::Error:: raised if the namespace cannot be found. - # - # Thor::Error:: raised if the namespace evals to a class which does not - # inherit from Thor or Thor::Group. - # - def self.namespace_to_thor_class_and_task(namespace, raise_if_nil=true) - if namespace.include?(?:) - pieces = namespace.split(":") - task = pieces.pop - klass = Thor::Util.find_by_namespace(pieces.join(":")) - end - - unless klass - klass, task = Thor::Util.find_by_namespace(namespace), nil - end - - raise Error, "could not find Thor class or task '#{namespace}'" if raise_if_nil && klass.nil? - return klass, task - end - - # Receives a path and load the thor file in the path. The file is evaluated - # inside the sandbox to avoid namespacing conflicts. - # - def self.load_thorfile(path, content=nil) - content ||= File.read(path) - - begin - Thor::Sandbox.class_eval(content, path) - rescue Exception => e - $stderr.puts "WARNING: unable to load thorfile #{path.inspect}: #{e.message}" - end - end - - # Receives a yaml (hash) and updates all constants entries to namespace. - # This was added to deal with deprecated versions of Thor. - # - # TODO Deprecate this method in the future. - # - # ==== Returns - # TrueClass|FalseClass:: Returns true if any change to the yaml file was made. - # - def self.convert_constants_to_namespaces(yaml) - yaml_changed = false - - yaml.each do |k, v| - next unless v[:constants] && v[:namespaces].nil? - yaml_changed = true - yaml[k][:namespaces] = v[:constants].map{|c| Thor::Util.namespace_from_thor_class(c)} - end - - yaml_changed - end - - def self.user_home - @@user_home ||= if ENV["HOME"] - ENV["HOME"] - elsif ENV["USERPROFILE"] - ENV["USERPROFILE"] - elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"] - File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"]) - elsif ENV["APPDATA"] - ENV["APPDATA"] - else - begin - File.expand_path("~") - rescue - if File::ALT_SEPARATOR - "C:/" - else - "/" - end - end - end - end - - # Returns the root where thor files are located, dependending on the OS. - # - def self.thor_root - File.join(user_home, ".thor").gsub(/\\/, '/') - end - - # Returns the files in the thor root. On Windows thor_root will be something - # like this: - # - # C:\Documents and Settings\james\.thor - # - # If we don't #gsub the \ character, Dir.glob will fail. - # - def self.thor_root_glob - files = Dir["#{thor_root}/*"] - - files.map! do |file| - File.directory?(file) ? File.join(file, "main.thor") : file - end - end - - # Where to look for Thor files. - # - def self.globs_for(path) - ["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"] - end - - # Return the path to the ruby interpreter taking into account multiple - # installations and windows extensions. - # - def self.ruby_command - @ruby_command ||= begin - ruby = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']) - ruby << Config::CONFIG['EXEEXT'] - - # escape string in case path to ruby executable contain spaces. - ruby.sub!(/.*\s.*/m, '"\&"') - ruby - end - end - - end -end diff --git a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/version.rb b/railties/lib/rails/vendor/thor-0.11.8/lib/thor/version.rb deleted file mode 100644 index 885230fac4..0000000000 --- a/railties/lib/rails/vendor/thor-0.11.8/lib/thor/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -class Thor - VERSION = "0.11.8".freeze -end diff --git a/railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc b/railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc new file mode 100644 index 0000000000..adedfeca9d --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc @@ -0,0 +1,82 @@ +== TODO + +* Improve spec coverage for Thor::Runner + +== 0.12, released 2009-11-06 + +* [#7] Do not force white color on status +* [#8] Yield a block with the filename on directory + +== 0.11, released 2009-07-01 + +* Added a rake compatibility layer. It allows you to use spec and rdoc tasks on + Thor classes. + +* BACKWARDS INCOMPATIBLE: aliases are not generated automatically anymore + since it wrong behavior to the invocation system. + +* thor help now show information about any class/task. All those calls are + possible: + + thor help describe + thor help describe:amazing + + Or even with default namespaces: + + thor help :spec + +* Thor::Runner now invokes the default task if none is supplied: + + thor describe # invokes the default task, usually help + +* Thor::Runner now works with mappings: + + thor describe -h + +* Added some documentation and code refactoring. + +== 0.9.8, released 2008-10-20 + +* Fixed some tiny issues that were introduced lately. + +== 0.9.7, released 2008-10-13 + +* Setting global method options on the initialize method works as expected: + All other tasks will accept these global options in addition to their own. +* Added 'group' notion to Thor task sets (class Thor); by default all tasks + are in the 'standard' group. Running 'thor -T' will only show the standard + tasks - adding --all will show all tasks. You can also filter on a specific + group using the --group option: thor -T --group advanced + +== 0.9.6, released 2008-09-13 + +* Generic improvements + +== 0.9.5, released 2008-08-27 + +* Improve Windows compatibility +* Update (incorrect) README and task.thor sample file +* Options hash is now frozen (once returned) +* Allow magic predicates on options object. For instance: `options.force?` +* Add support for :numeric type +* BACKWARDS INCOMPATIBLE: Refactor Thor::Options. You cannot access shorthand forms in options hash anymore (for instance, options[:f]) +* Allow specifying optional args with default values: method_options(:user => "mislav") +* Don't write options for nil or false values. This allows, for example, turning color off when running specs. +* Exit with the status of the spec command to help CI stuff out some. + +== 0.9.4, released 2008-08-13 + +* Try to add Windows compatibility. +* BACKWARDS INCOMPATIBLE: options hash is now accessed as a property in your class and is not passed as last argument anymore +* Allow options at the beginning of the argument list as well as the end. +* Make options available with symbol keys in addition to string keys. +* Allow true to be passed to Thor#method_options to denote a boolean option. +* If loading a thor file fails, don't give up, just print a warning and keep going. +* Make sure that we re-raise errors if they happened further down the pipe than we care about. +* Only delete the old file on updating when the installation of the new one is a success +* Make it Ruby 1.8.5 compatible. +* Don't raise an error if a boolean switch is defined multiple times. +* Thor::Options now doesn't parse through things that look like options but aren't. +* Add URI detection to install task, and make sure we don't append ".thor" to URIs +* Add rake2thor to the gem binfiles. +* Make sure local Thorfiles override system-wide ones. diff --git a/railties/lib/rails/vendor/thor-0.12.0/LICENSE b/railties/lib/rails/vendor/thor-0.12.0/LICENSE new file mode 100644 index 0000000000..98722da459 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008 Yehuda Katz + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/railties/lib/rails/vendor/thor-0.12.0/README.rdoc b/railties/lib/rails/vendor/thor-0.12.0/README.rdoc new file mode 100644 index 0000000000..f1106f02b6 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/README.rdoc @@ -0,0 +1,234 @@ += thor + +Map options to a class. Simply create a class with the appropriate annotations +and have options automatically map to functions and parameters. + +Example: + + class App < Thor # [1] + map "-L" => :list # [2] + + desc "install APP_NAME", "install one of the available apps" # [3] + method_options :force => :boolean, :alias => :string # [4] + def install(name) + user_alias = options[:alias] + if options.force? + # do something + end + # other code + end + + desc "list [SEARCH]", "list all of the available apps, limited by SEARCH" + def list(search="") + # list everything + end + end + +Thor automatically maps commands as such: + + thor app:install myname --force + +That gets converted to: + + App.new.install("myname") + # with {'force' => true} as options hash + +1. Inherit from Thor to turn a class into an option mapper +2. Map additional non-valid identifiers to specific methods. In this case, convert -L to :list +3. Describe the method immediately below. The first parameter is the usage information, and the second parameter is the description +4. Provide any additional options that will be available the instance method options. + +== Types for method_options + +* :boolean - is parsed as --option or --option=true +* :string - is parsed as --option=VALUE +* :numeric - is parsed as --option=N +* :array - is parsed as --option=one two three +* :hash - is parsed as --option=name:string age:integer + +Besides, method_option allows a default value to be given, examples: + + method_options :force => false + #=> Creates a boolean option with default value false + + method_options :alias => "bar" + #=> Creates a string option with default value "bar" + + method_options :threshold => 3.0 + #=> Creates a numeric option with default value 3.0 + +You can also supply :option => :required to mark an option as required. The +type is assumed to be string. If you want a required hash with default values +as option, you can use method_option which uses a more declarative style: + + method_option :attributes, :type => :hash, :default => {}, :required => true + +All arguments can be set to nil (except required arguments), by suppling a no or +skip variant. For example: + + thor app name --no-attributes + +In previous versions, aliases for options were created automatically, but now +they should be explicit. You can supply aliases in both short and declarative +styles: + + method_options %w( force -f ) => :boolean + +Or: + + method_option :force, :type => :boolean, :aliases => "-f" + +You can supply as many aliases as you want. + +NOTE: Type :optional available in Thor 0.9.0 was deprecated. Use :string or :boolean instead. + +== Namespaces + +By default, your Thor tasks are invoked using Ruby namespace. In the example +above, tasks are invoked as: + + thor app:install name --force + +However, you could namespace your class as: + + module Sinatra + class App < Thor + # tasks + end + end + +And then you should invoke your tasks as: + + thor sinatra:app:install name --force + +If desired, you can change the namespace: + + module Sinatra + class App < Thor + namespace :myapp + # tasks + end + end + +And then your tasks hould be invoked as: + + thor myapp:install name --force + +== Invocations + +Thor comes with a invocation-dependency system as well which allows a task to be +invoked only once. For example: + + class Counter < Thor + desc "one", "Prints 1, 2, 3" + def one + puts 1 + invoke :two + invoke :three + end + + desc "two", "Prints 2, 3" + def two + puts 2 + invoke :three + end + + desc "three", "Prints 3" + def three + puts 3 + end + end + +When invoking the task one: + + thor counter:one + +The output is "1 2 3", which means that the three task was invoked only once. +You can even invoke tasks from another class, so be sure to check the +documentation. + +== Thor::Group + +Thor has a special class called Thor::Group. The main difference to Thor class +is that it invokes all tasks at once. The example above could be rewritten in +Thor::Group as this: + + class Counter < Thor::Group + desc "Prints 1, 2, 3" + + def one + puts 1 + end + + def two + puts 2 + end + + def three + puts 3 + end + end + +When invoked: + + thor counter + +It prints "1 2 3" as well. Notice you should describe (using the method desc) +only the class and not each task anymore. Thor::Group is a great tool to create +generators, since you can define several steps which are invoked in the order they +are defined (Thor::Group is the tool use in generators in Rails 3.0). + +Besides, Thor::Group can parse arguments and options as Thor tasks: + + class Counter < Thor::Group + # number will be available as attr_accessor + argument :number, :type => :numeric, :desc => "The number to start counting" + desc "Prints the 'number' given upto 'number+2'" + + def one + puts number + 0 + end + + def two + puts number + 1 + end + + def three + puts number + 2 + end + end + +The counter above expects one parameter and has the folling outputs: + + thor counter 5 + # Prints "5 6 7" + + thor counter 11 + # Prints "11 12 13" + +You can also give options to Thor::Group, but instead of using method_option +and method_options, you should use class_option and class_options. +Both argument and class_options methods are available to Thor class as well. + +== Actions + +Thor comes with several actions which helps with script and generator tasks. You +might be familiar with them since some came from Rails Templates. They are: +say, ask, yes?, no?, add_file, +remove_file, copy_file, template, directory, +inside, run, inject_into_file and a couple more. + +To use them, you just need to include Thor::Actions in your Thor classes: + + class App < Thor + include Thor::Actions + # tasks + end + +Some actions like copy file requires that a class method called source_root is +defined in your class. This is the directory where your templates should be +placed. Be sure to check the documentation. + +== License + +See MIT LICENSE. diff --git a/railties/lib/rails/vendor/thor-0.12.0/Thorfile b/railties/lib/rails/vendor/thor-0.12.0/Thorfile new file mode 100644 index 0000000000..f71a1e57e2 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/Thorfile @@ -0,0 +1,63 @@ +# enconding: utf-8 + +require File.join(File.dirname(__FILE__), "lib", "thor", "version") +require 'thor/rake_compat' +require 'spec/rake/spectask' +require 'rdoc/task' + +GEM_NAME = 'thor' +EXTRA_RDOC_FILES = ["README.rdoc", "LICENSE", "CHANGELOG.rdoc", "VERSION", "Thorfile"] + +class Default < Thor + include Thor::RakeCompat + + Spec::Rake::SpecTask.new(:spec) do |t| + t.libs << 'lib' + t.spec_opts = ['--options', "spec/spec.opts"] + t.spec_files = FileList['spec/**/*_spec.rb'] + end + + Spec::Rake::SpecTask.new(:rcov) do |t| + t.libs << 'lib' + t.spec_opts = ['--options', "spec/spec.opts"] + t.spec_files = FileList['spec/**/*_spec.rb'] + t.rcov = true + t.rcov_dir = "rcov" + end + + RDoc::Task.new do |rdoc| + rdoc.main = "README.rdoc" + rdoc.rdoc_dir = "rdoc" + rdoc.title = GEM_NAME + rdoc.rdoc_files.include(*EXTRA_RDOC_FILES) + rdoc.rdoc_files.include('lib/**/*.rb') + rdoc.options << '--line-numbers' << '--inline-source' + end + + begin + require 'jeweler' + Jeweler::Tasks.new do |s| + s.name = GEM_NAME + s.version = Thor::VERSION + s.rubyforge_project = "textmate" + s.platform = Gem::Platform::RUBY + s.summary = "A scripting framework that replaces rake, sake and rubigen" + s.email = "ruby-thor@googlegroups.com" + s.homepage = "http://yehudakatz.com" + s.description = "A scripting framework that replaces rake, sake and rubigen" + s.authors = ['Yehuda Katz', 'José Valim'] + s.has_rdoc = true + s.extra_rdoc_files = EXTRA_RDOC_FILES + s.require_path = 'lib' + s.bindir = "bin" + s.executables = %w( thor rake2thor ) + s.files = s.extra_rdoc_files + Dir.glob("{bin,lib}/**/*") + s.files.exclude 'spec/sandbox/**/*' + s.test_files.exclude 'spec/sandbox/**/*' + end + + Jeweler::RubyforgeTasks.new + rescue LoadError + puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb new file mode 100644 index 0000000000..68944f140d --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb @@ -0,0 +1,242 @@ +require 'thor/base' +require 'thor/group' +require 'thor/actions' + +class Thor + class << self + # Sets the default task when thor is executed without an explicit task to be called. + # + # ==== Parameters + # meth:: name of the defaut task + # + def default_task(meth=nil) + case meth + when :none + @default_task = 'help' + when nil + @default_task ||= from_superclass(:default_task, 'help') + else + @default_task = meth.to_s + end + end + + # Defines the usage and the description of the next task. + # + # ==== Parameters + # usage + # description + # + def desc(usage, description, options={}) + if options[:for] + task = find_and_refresh_task(options[:for]) + task.usage = usage if usage + task.description = description if description + else + @usage, @desc = usage, description + end + end + + # Maps an input to a task. If you define: + # + # map "-T" => "list" + # + # Running: + # + # thor -T + # + # Will invoke the list task. + # + # ==== Parameters + # Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given task. + # + def map(mappings=nil) + @map ||= from_superclass(:map, {}) + + if mappings + mappings.each do |key, value| + if key.respond_to?(:each) + key.each {|subkey| @map[subkey] = value} + else + @map[key] = value + end + end + end + + @map + end + + # Declares the options for the next task to be declared. + # + # ==== Parameters + # Hash[Symbol => Object]:: The hash key is the name of the option and the value + # is the type of the option. Can be :string, :array, :hash, :boolean, :numeric + # or :required (string). If you give a value, the type of the value is used. + # + def method_options(options=nil) + @method_options ||= {} + build_options(options, @method_options) if options + @method_options + end + + # Adds an option to the set of class options. If :for is given as option, + # it allows you to change the options from a previous defined task. + # + # def previous_task + # # magic + # end + # + # method_options :foo => :bar, :for => :previous_task + # + # def next_task + # # magic + # end + # + # ==== Parameters + # name:: The name of the argument. + # options:: Described below. + # + # ==== Options + # :desc - Description for the argument. + # :required - If the argument is required or not. + # :default - Default value for this argument. It cannot be required and have default values. + # :aliases - Aliases for this option. + # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. + # :group - The group for this options. Use by class options to output options in different levels. + # :banner - String to show on usage notes. + # + def method_option(name, options={}) + scope = if options[:for] + find_and_refresh_task(options[:for]).options + else + method_options + end + + build_option(name, options, scope) + end + + # Parses the task and options from the given args, instantiate the class + # and invoke the task. This method is used when the arguments must be parsed + # from an array. If you are inside Ruby and want to use a Thor class, you + # can simply initialize it: + # + # script = MyScript.new(args, options, config) + # script.invoke(:task, first_arg, second_arg, third_arg) + # + def start(given_args=ARGV, config={}) + super do + meth = normalize_task_name(given_args.shift) + task = all_tasks[meth] + + if task + args, opts = Thor::Options.split(given_args) + config.merge!(:task_options => task.options) + else + args, opts = given_args, {} + end + + task ||= Thor::Task::Dynamic.new(meth) + trailing = args[Range.new(arguments.size, -1)] + new(args, opts, config).invoke(task, trailing || []) + end + end + + # Prints help information. If a task name is given, it shows information + # only about the specific task. + # + # ==== Parameters + # meth:: An optional task name to print usage information about. + # + # ==== Options + # namespace:: When true, shows the namespace in the output before the usage. + # skip_inherited:: When true, does not show tasks from superclass. + # + def help(shell, meth=nil, options={}) + meth, options = nil, meth if meth.is_a?(Hash) + + if meth + task = all_tasks[meth] + raise UndefinedTaskError, "task '#{meth}' could not be found in namespace '#{self.namespace}'" unless task + + shell.say "Usage:" + shell.say " #{banner(task, options[:namespace], false)}" + shell.say + class_options_help(shell, "Class", :Method => task.options.map { |_, o| o }) + shell.say task.description + else + list = (options[:short] ? tasks : all_tasks).map do |_, task| + item = [ banner(task, options[:namespace]) ] + item << "# #{task.short_description}" if task.short_description + item << " " + end + + options[:ident] ||= 2 + if options[:short] + shell.print_list(list, :ident => options[:ident]) + else + shell.say "Tasks:" + shell.print_list(list, :ident => options[:ident]) + end + + Thor::Util.thor_classes_in(self).each do |subclass| + namespace = options[:namespace] == true || subclass.namespace.gsub(/^#{self.namespace}:/, '') + subclass.help(shell, options.merge(:short => true, :namespace => namespace)) + end + + class_options_help(shell, "Class") unless options[:short] + end + end + + protected + + # The banner for this class. You can customize it if you are invoking the + # thor class by another ways which is not the Thor::Runner. It receives + # the task that is going to be invoked and a boolean which indicates if + # the namespace should be displayed as arguments. + # + def banner(task, namespace=true, show_options=true) + task.formatted_usage(self, namespace, show_options) + end + + def baseclass #:nodoc: + Thor + end + + def create_task(meth) #:nodoc: + if @usage && @desc + tasks[meth.to_s] = Thor::Task.new(meth, @desc, @usage, method_options) + @usage, @desc, @method_options = nil + true + elsif self.all_tasks[meth.to_s] || meth.to_sym == :method_missing + true + else + puts "[WARNING] Attempted to create task #{meth.inspect} without usage or description. " << + "Call desc if you want this method to be available as task or declare it inside a " << + "no_tasks{} block. Invoked from #{caller[1].inspect}." + false + end + end + + def initialize_added #:nodoc: + class_options.merge!(method_options) + @method_options = nil + end + + # Receives a task name (can be nil), and try to get a map from it. + # If a map can't be found use the sent name or the default task. + # + def normalize_task_name(meth) #:nodoc: + mapping = map[meth.to_s] + meth = mapping || meth || default_task + meth.to_s.gsub('-','_') # treat foo-bar > foo_bar + end + end + + include Thor::Base + + map HELP_MAPPINGS => :help + + desc "help [TASK]", "Describe available tasks or one specific task" + def help(task=nil) + self.class.help(shell, task, :namespace => task && task.include?(?:)) + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb new file mode 100644 index 0000000000..d561ccb2aa --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb @@ -0,0 +1,273 @@ +require 'fileutils' + +Dir[File.join(File.dirname(__FILE__), "actions", "*.rb")].each do |action| + require action +end + +class Thor + module Actions + attr_accessor :behavior + + def self.included(base) #:nodoc: + base.extend ClassMethods + end + + module ClassMethods + # Hold source paths for one Thor instance. source_paths_for_search is the + # method responsible to gather source_paths from this current class, + # inherited paths and the source root. + # + def source_paths + @source_paths ||= [] + end + + # Returns the source paths in the following order: + # + # 1) This class source paths + # 2) Source root + # 3) Parents source paths + # + def source_paths_for_search + paths = [] + paths += self.source_paths + paths << self.source_root if self.respond_to?(:source_root) + paths += from_superclass(:source_paths, []) + paths + end + + # Add runtime options that help actions execution. + # + def add_runtime_options! + class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime, + :desc => "Run but do not make any changes" + + class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime, + :desc => "Overwrite files that already exist" + + class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime, + :desc => "Skip files that already exist" + + class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime, + :desc => "Supress status output" + end + end + + # Extends initializer to add more configuration options. + # + # ==== Configuration + # behavior:: The actions default behavior. Can be :invoke or :revoke. + # It also accepts :force, :skip and :pretend to set the behavior + # and the respective option. + # + # destination_root:: The root directory needed for some actions. + # + def initialize(args=[], options={}, config={}) + self.behavior = case config[:behavior].to_s + when "force", "skip" + _cleanup_options_and_set(options, config[:behavior]) + :invoke + when "revoke" + :revoke + else + :invoke + end + + super + self.destination_root = config[:destination_root] + end + + # Wraps an action object and call it accordingly to the thor class behavior. + # + def action(instance) #:nodoc: + if behavior == :revoke + instance.revoke! + else + instance.invoke! + end + end + + # Returns the root for this thor class (also aliased as destination root). + # + def destination_root + @destination_stack.last + end + + # Sets the root for this thor class. Relatives path are added to the + # directory where the script was invoked and expanded. + # + def destination_root=(root) + @destination_stack ||= [] + @destination_stack[0] = File.expand_path(root || '') + end + + # Returns the given path relative to the absolute root (ie, root where + # the script started). + # + def relative_to_original_destination_root(path, remove_dot=true) + path = path.gsub(@destination_stack[0], '.') + remove_dot ? (path[2..-1] || '') : path + end + + # Holds source paths in instance so they can be manipulated. + # + def source_paths + @source_paths ||= self.class.source_paths_for_search + end + + # Receives a file or directory and search for it in the source paths. + # + def find_in_source_paths(file) + relative_root = relative_to_original_destination_root(destination_root, false) + + source_paths.each do |source| + source_file = File.expand_path(file, File.join(source, relative_root)) + return source_file if File.exists?(source_file) + end + + if source_paths.empty? + raise Error, "You don't have any source path defined for class #{self.class.name}. To fix this, " << + "you can define a source_root in your class." + else + raise Error, "Could not find #{file.inspect} in source paths." + end + end + + # Do something in the root or on a provided subfolder. If a relative path + # is given it's referenced from the current root. The full path is yielded + # to the block you provide. The path is set back to the previous path when + # the method exits. + # + # ==== Parameters + # dir:: the directory to move to. + # config:: give :verbose => true to log and use padding. + # + def inside(dir='', config={}, &block) + verbose = config.fetch(:verbose, false) + + say_status :inside, dir, verbose + shell.padding += 1 if verbose + @destination_stack.push File.expand_path(dir, destination_root) + + FileUtils.mkdir_p(destination_root) unless File.exist?(destination_root) + FileUtils.cd(destination_root) { block.arity == 1 ? yield(destination_root) : yield } + + @destination_stack.pop + shell.padding -= 1 if verbose + end + + # Goes to the root and execute the given block. + # + def in_root + inside(@destination_stack.first) { yield } + end + + # Loads an external file and execute it in the instance binding. + # + # ==== Parameters + # path:: The path to the file to execute. Can be a web address or + # a relative path from the source root. + # + # ==== Examples + # + # apply "http://gist.github.com/103208" + # + # apply "recipes/jquery.rb" + # + def apply(path, config={}) + verbose = config.fetch(:verbose, true) + path = find_in_source_paths(path) unless path =~ /^http\:\/\// + + say_status :apply, path, verbose + shell.padding += 1 if verbose + instance_eval(open(path).read) + shell.padding -= 1 if verbose + end + + # Executes a command. + # + # ==== Parameters + # command:: the command to be executed. + # config:: give :verbose => false to not log the status. Specify :with + # to append an executable to command executation. + # + # ==== Example + # + # inside('vendor') do + # run('ln -s ~/edge rails') + # end + # + def run(command, config={}) + return unless behavior == :invoke + + destination = relative_to_original_destination_root(destination_root, false) + desc = "#{command} from #{destination.inspect}" + + if config[:with] + desc = "#{File.basename(config[:with].to_s)} #{desc}" + command = "#{config[:with]} #{command}" + end + + say_status :run, desc, config.fetch(:verbose, true) + system(command) unless options[:pretend] + end + + # Executes a ruby script (taking into account WIN32 platform quirks). + # + # ==== Parameters + # command:: the command to be executed. + # config:: give :verbose => false to not log the status. + # + def run_ruby_script(command, config={}) + return unless behavior == :invoke + run "#{command}", config.merge(:with => Thor::Util.ruby_command) + end + + # Run a thor command. A hash of options can be given and it's converted to + # switches. + # + # ==== Parameters + # task:: the task to be invoked + # args:: arguments to the task + # config:: give :verbose => false to not log the status. Other options + # are given as parameter to Thor. + # + # ==== Examples + # + # thor :install, "http://gist.github.com/103208" + # #=> thor install http://gist.github.com/103208 + # + # thor :list, :all => true, :substring => 'rails' + # #=> thor list --all --substring=rails + # + def thor(task, *args) + config = args.last.is_a?(Hash) ? args.pop : {} + verbose = config.key?(:verbose) ? config.delete(:verbose) : true + + args.unshift task + args.push Thor::Options.to_switches(config) + command = args.join(' ').strip + + run command, :with => :thor, :verbose => verbose + end + + protected + + # Allow current root to be shared between invocations. + # + def _shared_configuration #:nodoc: + super.merge!(:destination_root => self.destination_root) + end + + def _cleanup_options_and_set(options, key) #:nodoc: + case options + when Array + %w(--force -f --skip -s).each { |i| options.delete(i) } + options << "--#{key}" + when Hash + [:force, :skip, "force", "skip"].each { |i| options.delete(i) } + options.merge!(key => true) + end + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb new file mode 100644 index 0000000000..a3d9296823 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb @@ -0,0 +1,103 @@ +require 'thor/actions/empty_directory' + +class Thor + module Actions + + # Create a new file relative to the destination root with the given data, + # which is the return value of a block or a data string. + # + # ==== Parameters + # destination:: the relative path to the destination root. + # data:: the data to append to the file. + # config:: give :verbose => false to not log the status. + # + # ==== Examples + # + # create_file "lib/fun_party.rb" do + # hostname = ask("What is the virtual hostname I should use?") + # "vhost.name = #{hostname}" + # end + # + # create_file "config/apach.conf", "your apache config" + # + def create_file(destination, data=nil, config={}, &block) + action CreateFile.new(self, destination, block || data.to_s, config) + end + alias :add_file :create_file + + # AddFile is a subset of Template, which instead of rendering a file with + # ERB, it gets the content from the user. + # + class CreateFile < EmptyDirectory #:nodoc: + attr_reader :data + + def initialize(base, destination, data, config={}) + @data = data + super(base, destination, config) + end + + # Checks if the content of the file at the destination is identical to the rendered result. + # + # ==== Returns + # Boolean:: true if it is identical, false otherwise. + # + def identical? + exists? && File.read(destination) == render + end + + # Holds the content to be added to the file. + # + def render + @render ||= if data.is_a?(Proc) + data.call + else + data + end + end + + def invoke! + invoke_with_conflict_check do + FileUtils.mkdir_p(File.dirname(destination)) + File.open(destination, 'w'){ |f| f.write render } + end + given_destination + end + + protected + + # Now on conflict we check if the file is identical or not. + # + def on_conflict_behavior(&block) + if identical? + say_status :identical, :blue + else + options = base.options.merge(config) + force_or_skip_or_conflict(options[:force], options[:skip], &block) + end + end + + # If force is true, run the action, otherwise check if it's not being + # skipped. If both are false, show the file_collision menu, if the menu + # returns true, force it, otherwise skip. + # + def force_or_skip_or_conflict(force, skip, &block) + if force + say_status :force, :yellow + block.call unless pretend? + elsif skip + say_status :skip, :yellow + else + say_status :conflict, :red + force_or_skip_or_conflict(force_on_collision?, true, &block) + end + end + + # Shows the file collision menu to the user and gets the result. + # + def force_on_collision? + base.shell.file_collision(destination){ render } + end + + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb new file mode 100644 index 0000000000..467e63732a --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb @@ -0,0 +1,93 @@ +require 'thor/actions/empty_directory' + +class Thor + module Actions + + # Copies recursively the files from source directory to root directory. + # If any of the files finishes with .tt, it's considered to be a template + # and is placed in the destination without the extension .tt. If any + # empty directory is found, it's copied and all .empty_directory files are + # ignored. Remember that file paths can also be encoded, let's suppose a doc + # directory with the following files: + # + # doc/ + # components/.empty_directory + # README + # rdoc.rb.tt + # %app_name%.rb + # + # When invoked as: + # + # directory "doc" + # + # It will create a doc directory in the destination with the following + # files (assuming that the app_name is "blog"): + # + # doc/ + # components/ + # README + # rdoc.rb + # blog.rb + # + # ==== Parameters + # source:: the relative path to the source root. + # destination:: the relative path to the destination root. + # config:: give :verbose => false to not log the status. + # If :recursive => false, does not look for paths recursively. + # + # ==== Examples + # + # directory "doc" + # directory "doc", "docs", :recursive => false + # + def directory(source, destination=nil, config={}, &block) + action Directory.new(self, source, destination || source, config, &block) + end + + class Directory < EmptyDirectory #:nodoc: + attr_reader :source + + def initialize(base, source, destination=nil, config={}, &block) + @source = File.expand_path(base.find_in_source_paths(source.to_s)) + @block = block + super(base, destination, { :recursive => true }.merge(config)) + end + + def invoke! + base.empty_directory given_destination, config + execute! + end + + def revoke! + execute! + end + + protected + + def execute! + lookup = config[:recursive] ? File.join(source, '**') : source + lookup = File.join(lookup, '{*,.[a-z]*}') + + Dir[lookup].each do |file_source| + next if File.directory?(file_source) + file_destination = File.join(given_destination, file_source.gsub(source, '.')) + file_destination.gsub!('/./', '/') + + case file_source + when /\.empty_directory$/ + dirname = File.dirname(file_destination).gsub(/\/\.$/, '') + next if dirname == given_destination + base.empty_directory(dirname, config) + when /\.tt$/ + destination = base.template(file_source, file_destination[0..-4], config) + @block.call(destination) if @block + else + destination = base.copy_file(file_source, file_destination, config) + @block.call(destination) if @block + end + end + end + + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb new file mode 100644 index 0000000000..484cb820f8 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb @@ -0,0 +1,134 @@ +class Thor + module Actions + + # Creates an empty directory. + # + # ==== Parameters + # destination:: the relative path to the destination root. + # config:: give :verbose => false to not log the status. + # + # ==== Examples + # + # empty_directory "doc" + # + def empty_directory(destination, config={}) + action EmptyDirectory.new(self, destination, config) + end + + # Class which holds create directory logic. This is the base class for + # other actions like create_file and directory. + # + # This implementation is based in Templater actions, created by Jonas Nicklas + # and Michael S. Klishin under MIT LICENSE. + # + class EmptyDirectory #:nodoc: + attr_reader :base, :destination, :given_destination, :relative_destination, :config + + # Initializes given the source and destination. + # + # ==== Parameters + # base:: A Thor::Base instance + # source:: Relative path to the source of this file + # destination:: Relative path to the destination of this file + # config:: give :verbose => false to not log the status. + # + def initialize(base, destination, config={}) + @base, @config = base, { :verbose => true }.merge(config) + self.destination = destination + end + + # Checks if the destination file already exists. + # + # ==== Returns + # Boolean:: true if the file exists, false otherwise. + # + def exists? + ::File.exists?(destination) + end + + def invoke! + invoke_with_conflict_check do + ::FileUtils.mkdir_p(destination) + end + end + + def revoke! + say_status :remove, :red + ::FileUtils.rm_rf(destination) if !pretend? && exists? + given_destination + end + + protected + + # Shortcut for pretend. + # + def pretend? + base.options[:pretend] + end + + # Sets the absolute destination value from a relative destination value. + # It also stores the given and relative destination. Let's suppose our + # script is being executed on "dest", it sets the destination root to + # "dest". The destination, given_destination and relative_destination + # are related in the following way: + # + # inside "bar" do + # empty_directory "baz" + # end + # + # destination #=> dest/bar/baz + # relative_destination #=> bar/baz + # given_destination #=> baz + # + def destination=(destination) + if destination + @given_destination = convert_encoded_instructions(destination.to_s) + @destination = ::File.expand_path(@given_destination, base.destination_root) + @relative_destination = base.relative_to_original_destination_root(@destination) + end + end + + # Filenames in the encoded form are converted. If you have a file: + # + # %class_name%.rb + # + # It gets the class name from the base and replace it: + # + # user.rb + # + def convert_encoded_instructions(filename) + filename.gsub(/%(.*?)%/) do |string| + instruction = $1.strip + base.respond_to?(instruction) ? base.send(instruction) : string + end + end + + # Receives a hash of options and just execute the block if some + # conditions are met. + # + def invoke_with_conflict_check(&block) + if exists? + on_conflict_behavior(&block) + else + say_status :create, :green + block.call unless pretend? + end + + destination + end + + # What to do when the destination file already exists. + # + def on_conflict_behavior(&block) + say_status :exist, :blue + end + + # Shortcut to say_status shell method. + # + def say_status(status, color) + base.shell.say_status status, relative_destination, color if config[:verbose] + end + + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb new file mode 100644 index 0000000000..d77d90d448 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb @@ -0,0 +1,219 @@ +require 'erb' +require 'open-uri' + +class Thor + module Actions + + # Copies the file from the relative source to the relative destination. If + # the destination is not given it's assumed to be equal to the source. + # + # ==== Parameters + # source:: the relative path to the source root. + # destination:: the relative path to the destination root. + # config:: give :verbose => false to not log the status. + # + # ==== Examples + # + # copy_file "README", "doc/README" + # + # copy_file "doc/README" + # + def copy_file(source, destination=nil, config={}) + destination ||= source + source = File.expand_path(find_in_source_paths(source.to_s)) + + create_file destination, nil, config do + File.read(source) + end + end + + # Gets the content at the given address and places it at the given relative + # destination. If a block is given instead of destination, the content of + # the url is yielded and used as location. + # + # ==== Parameters + # source:: the address of the given content. + # destination:: the relative path to the destination root. + # config:: give :verbose => false to not log the status. + # + # ==== Examples + # + # get "http://gist.github.com/103208", "doc/README" + # + # get "http://gist.github.com/103208" do |content| + # content.split("\n").first + # end + # + def get(source, destination=nil, config={}, &block) + source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ /^http\:\/\// + render = open(source).read + + destination ||= if block_given? + block.arity == 1 ? block.call(render) : block.call + else + File.basename(source) + end + + create_file destination, render, config + end + + # Gets an ERB template at the relative source, executes it and makes a copy + # at the relative destination. If the destination is not given it's assumed + # to be equal to the source removing .tt from the filename. + # + # ==== Parameters + # source:: the relative path to the source root. + # destination:: the relative path to the destination root. + # config:: give :verbose => false to not log the status. + # + # ==== Examples + # + # template "README", "doc/README" + # + # template "doc/README" + # + def template(source, destination=nil, config={}) + destination ||= source + source = File.expand_path(find_in_source_paths(source.to_s)) + context = instance_eval('binding') + + create_file destination, nil, config do + ERB.new(::File.read(source), nil, '-').result(context) + end + end + + # Changes the mode of the given file or directory. + # + # ==== Parameters + # mode:: the file mode + # path:: the name of the file to change mode + # config:: give :verbose => false to not log the status. + # + # ==== Example + # + # chmod "script/*", 0755 + # + def chmod(path, mode, config={}) + return unless behavior == :invoke + path = File.expand_path(path, destination_root) + say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true) + FileUtils.chmod_R(mode, path) unless options[:pretend] + end + + # Prepend text to a file. Since it depends on inject_into_file, it's reversible. + # + # ==== Parameters + # path:: path of the file to be changed + # data:: the data to prepend to the file, can be also given as a block. + # config:: give :verbose => false to not log the status. + # + # ==== Example + # + # prepend_file 'config/environments/test.rb', 'config.gem "rspec"' + # + # prepend_file 'config/environments/test.rb' do + # 'config.gem "rspec"' + # end + # + def prepend_file(path, *args, &block) + config = args.last.is_a?(Hash) ? args.pop : {} + config.merge!(:after => /\A/) + inject_into_file(path, *(args << config), &block) + end + + # Append text to a file. Since it depends on inject_into_file, it's reversible. + # + # ==== Parameters + # path:: path of the file to be changed + # data:: the data to append to the file, can be also given as a block. + # config:: give :verbose => false to not log the status. + # + # ==== Example + # + # append_file 'config/environments/test.rb', 'config.gem "rspec"' + # + # append_file 'config/environments/test.rb' do + # 'config.gem "rspec"' + # end + # + def append_file(path, *args, &block) + config = args.last.is_a?(Hash) ? args.pop : {} + config.merge!(:before => /\z/) + inject_into_file(path, *(args << config), &block) + end + + # Injects text right after the class definition. Since it depends on + # inject_into_file, it's reversible. + # + # ==== Parameters + # path:: path of the file to be changed + # klass:: the class to be manipulated + # data:: the data to append to the class, can be also given as a block. + # config:: give :verbose => false to not log the status. + # + # ==== Examples + # + # inject_into_class "app/controllers/application_controller.rb", " filter_parameter :password\n" + # + # inject_into_class "app/controllers/application_controller.rb", ApplicationController do + # " filter_parameter :password\n" + # end + # + def inject_into_class(path, klass, *args, &block) + config = args.last.is_a?(Hash) ? args.pop : {} + config.merge!(:after => /class #{klass}\n|class #{klass} .*\n/) + inject_into_file(path, *(args << config), &block) + end + + # Run a regular expression replacement on a file. + # + # ==== Parameters + # path:: path of the file to be changed + # flag:: the regexp or string to be replaced + # replacement:: the replacement, can be also given as a block + # config:: give :verbose => false to not log the status. + # + # ==== Example + # + # gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1' + # + # gsub_file 'README', /rake/, :green do |match| + # match << " no more. Use thor!" + # end + # + def gsub_file(path, flag, *args, &block) + return unless behavior == :invoke + config = args.last.is_a?(Hash) ? args.pop : {} + + path = File.expand_path(path, destination_root) + say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true) + + unless options[:pretend] + content = File.read(path) + content.gsub!(flag, *args, &block) + File.open(path, 'wb') { |file| file.write(content) } + end + end + + # Removes a file at the given location. + # + # ==== Parameters + # path:: path of the file to be changed + # config:: give :verbose => false to not log the status. + # + # ==== Example + # + # remove_file 'README' + # remove_file 'app/controllers/application_controller.rb' + # + def remove_file(path, config={}) + return unless behavior == :invoke + path = File.expand_path(path, destination_root) + + say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true) + ::FileUtils.rm_rf(path) if !options[:pretend] && File.exists?(path) + end + alias :remove_dir :remove_file + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb new file mode 100644 index 0000000000..0636ec6591 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb @@ -0,0 +1,101 @@ +require 'thor/actions/empty_directory' + +class Thor + module Actions + + # Injects the given content into a file. Different from gsub_file, this + # method is reversible. + # + # ==== Parameters + # destination:: Relative path to the destination root + # data:: Data to add to the file. Can be given as a block. + # config:: give :verbose => false to not log the status and the flag + # for injection (:after or :before). + # + # ==== Examples + # + # inject_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n" + # + # inject_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do + # gems = ask "Which gems would you like to add?" + # gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n") + # end + # + def inject_into_file(destination, *args, &block) + if block_given? + data, config = block, args.shift + else + data, config = args.shift, args.shift + end + action InjectIntoFile.new(self, destination, data, config) + end + + class InjectIntoFile < EmptyDirectory #:nodoc: + attr_reader :replacement, :flag, :behavior + + def initialize(base, destination, data, config) + super(base, destination, { :verbose => true }.merge(config)) + + @behavior, @flag = if @config.key?(:after) + [:after, @config.delete(:after)] + else + [:before, @config.delete(:before)] + end + + @replacement = data.is_a?(Proc) ? data.call : data + @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp) + end + + def invoke! + say_status :invoke + + content = if @behavior == :after + '\0' + replacement + else + replacement + '\0' + end + + replace!(/#{flag}/, content) + end + + def revoke! + say_status :revoke + + regexp = if @behavior == :after + content = '\1\2' + /(#{flag})(.*)(#{Regexp.escape(replacement)})/m + else + content = '\2\3' + /(#{Regexp.escape(replacement)})(.*)(#{flag})/m + end + + replace!(regexp, content) + end + + protected + + def say_status(behavior) + status = if flag == /\A/ + behavior == :invoke ? :prepend : :unprepend + elsif flag == /\z/ + behavior == :invoke ? :append : :unappend + else + behavior == :invoke ? :inject : :deinject + end + + super(status, config[:verbose]) + end + + # Adds the content to the file. + # + def replace!(regexp, string) + unless base.options[:pretend] + content = File.read(destination) + content.gsub!(regexp, string) + File.open(destination, 'wb') { |file| file.write(content) } + end + end + + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb new file mode 100644 index 0000000000..700d794123 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb @@ -0,0 +1,517 @@ +require 'thor/core_ext/hash_with_indifferent_access' +require 'thor/core_ext/ordered_hash' +require 'thor/error' +require 'thor/shell' +require 'thor/invocation' +require 'thor/parser' +require 'thor/task' +require 'thor/util' + +class Thor + # Shortcuts for help. + HELP_MAPPINGS = %w(-h -? --help -D) + + # Thor methods that should not be overwritten by the user. + THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root + action add_file create_file in_root inside run run_ruby_script) + + module Base + attr_accessor :options + + # It receives arguments in an Array and two hashes, one for options and + # other for configuration. + # + # Notice that it does not check if all required arguments were supplied. + # It should be done by the parser. + # + # ==== Parameters + # args:: An array of objects. The objects are applied to their + # respective accessors declared with argument. + # + # options:: An options hash that will be available as self.options. + # The hash given is converted to a hash with indifferent + # access, magic predicates (options.skip?) and then frozen. + # + # config:: Configuration for this Thor class. + # + def initialize(args=[], options={}, config={}) + Thor::Arguments.parse(self.class.arguments, args).each do |key, value| + send("#{key}=", value) + end + + parse_options = self.class.class_options + + if options.is_a?(Array) + task_options = config.delete(:task_options) # hook for start + parse_options = parse_options.merge(task_options) if task_options + array_options, hash_options = options, {} + else + array_options, hash_options = [], options + end + + options = Thor::Options.parse(parse_options, array_options) + self.options = Thor::CoreExt::HashWithIndifferentAccess.new(options).merge!(hash_options) + self.options.freeze + end + + class << self + def included(base) #:nodoc: + base.send :extend, ClassMethods + base.send :include, Invocation + base.send :include, Shell + end + + # Returns the classes that inherits from Thor or Thor::Group. + # + # ==== Returns + # Array[Class] + # + def subclasses + @subclasses ||= [] + end + + # Returns the files where the subclasses are kept. + # + # ==== Returns + # Hash[path => Class] + # + def subclass_files + @subclass_files ||= Hash.new{ |h,k| h[k] = [] } + end + + # Whenever a class inherits from Thor or Thor::Group, we should track the + # class and the file on Thor::Base. This is the method responsable for it. + # + def register_klass_file(klass) #:nodoc: + file = caller[1].match(/(.*):\d+/)[1] + Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass) + + file_subclasses = Thor::Base.subclass_files[File.expand_path(file)] + file_subclasses << klass unless file_subclasses.include?(klass) + end + end + + module ClassMethods + # Adds an argument to the class and creates an attr_accessor for it. + # + # Arguments are different from options in several aspects. The first one + # is how they are parsed from the command line, arguments are retrieved + # from position: + # + # thor task NAME + # + # Instead of: + # + # thor task --name=NAME + # + # Besides, arguments are used inside your code as an accessor (self.argument), + # while options are all kept in a hash (self.options). + # + # Finally, arguments cannot have type :default or :boolean but can be + # optional (supplying :optional => :true or :required => false), although + # you cannot have a required argument after a non-required argument. If you + # try it, an error is raised. + # + # ==== Parameters + # name:: The name of the argument. + # options:: Described below. + # + # ==== Options + # :desc - Description for the argument. + # :required - If the argument is required or not. + # :optional - If the argument is optional or not. + # :type - The type of the argument, can be :string, :hash, :array, :numeric. + # :default - Default value for this argument. It cannot be required and have default values. + # :banner - String to show on usage notes. + # + # ==== Errors + # ArgumentError:: Raised if you supply a required argument after a non required one. + # + def argument(name, options={}) + is_thor_reserved_word?(name, :argument) + no_tasks { attr_accessor name } + + required = if options.key?(:optional) + !options[:optional] + elsif options.key?(:required) + options[:required] + else + options[:default].nil? + end + + remove_argument name + + arguments.each do |argument| + next if argument.required? + raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " << + "the non-required argument #{argument.human_name.inspect}." + end if required + + arguments << Thor::Argument.new(name, options[:desc], required, options[:type], + options[:default], options[:banner]) + end + + # Returns this class arguments, looking up in the ancestors chain. + # + # ==== Returns + # Array[Thor::Argument] + # + def arguments + @arguments ||= from_superclass(:arguments, []) + end + + # Adds a bunch of options to the set of class options. + # + # class_options :foo => false, :bar => :required, :baz => :string + # + # If you prefer more detailed declaration, check class_option. + # + # ==== Parameters + # Hash[Symbol => Object] + # + def class_options(options=nil) + @class_options ||= from_superclass(:class_options, {}) + build_options(options, @class_options) if options + @class_options + end + + # Adds an option to the set of class options + # + # ==== Parameters + # name:: The name of the argument. + # options:: Described below. + # + # ==== Options + # :desc - Description for the argument. + # :required - If the argument is required or not. + # :default - Default value for this argument. + # :group - The group for this options. Use by class options to output options in different levels. + # :aliases - Aliases for this option. + # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. + # :banner - String to show on usage notes. + # + def class_option(name, options={}) + build_option(name, options, class_options) + end + + # Removes a previous defined argument. If :undefine is given, undefine + # accessors as well. + # + # ==== Paremeters + # names:: Arguments to be removed + # + # ==== Examples + # + # remove_argument :foo + # remove_argument :foo, :bar, :baz, :undefine => true + # + def remove_argument(*names) + options = names.last.is_a?(Hash) ? names.pop : {} + + names.each do |name| + arguments.delete_if { |a| a.name == name.to_s } + undef_method name, "#{name}=" if options[:undefine] + end + end + + # Removes a previous defined class option. + # + # ==== Paremeters + # names:: Class options to be removed + # + # ==== Examples + # + # remove_class_option :foo + # remove_class_option :foo, :bar, :baz + # + def remove_class_option(*names) + names.each do |name| + class_options.delete(name) + end + end + + # Defines the group. This is used when thor list is invoked so you can specify + # that only tasks from a pre-defined group will be shown. Defaults to standard. + # + # ==== Parameters + # name + # + def group(name=nil) + case name + when nil + @group ||= from_superclass(:group, 'standard') + else + @group = name.to_s + end + end + + # Returns the tasks for this Thor class. + # + # ==== Returns + # OrderedHash:: An ordered hash with tasks names as keys and Thor::Task + # objects as values. + # + def tasks + @tasks ||= Thor::CoreExt::OrderedHash.new + end + + # Returns the tasks for this Thor class and all subclasses. + # + # ==== Returns + # OrderedHash:: An ordered hash with tasks names as keys and Thor::Task + # objects as values. + # + def all_tasks + @all_tasks ||= from_superclass(:all_tasks, Thor::CoreExt::OrderedHash.new) + @all_tasks.merge(tasks) + end + + # Removes a given task from this Thor class. This is usually done if you + # are inheriting from another class and don't want it to be available + # anymore. + # + # By default it only remove the mapping to the task. But you can supply + # :undefine => true to undefine the method from the class as well. + # + # ==== Parameters + # name:: The name of the task to be removed + # options:: You can give :undefine => true if you want tasks the method + # to be undefined from the class as well. + # + def remove_task(*names) + options = names.last.is_a?(Hash) ? names.pop : {} + + names.each do |name| + tasks.delete(name.to_s) + all_tasks.delete(name.to_s) + undef_method name if options[:undefine] + end + end + + # All methods defined inside the given block are not added as tasks. + # + # So you can do: + # + # class MyScript < Thor + # no_tasks do + # def this_is_not_a_task + # end + # end + # end + # + # You can also add the method and remove it from the task list: + # + # class MyScript < Thor + # def this_is_not_a_task + # end + # remove_task :this_is_not_a_task + # end + # + def no_tasks + @no_tasks = true + yield + @no_tasks = false + end + + # Sets the namespace for the Thor or Thor::Group class. By default the + # namespace is retrieved from the class name. If your Thor class is named + # Scripts::MyScript, the help method, for example, will be called as: + # + # thor scripts:my_script -h + # + # If you change the namespace: + # + # namespace :my_scripts + # + # You change how your tasks are invoked: + # + # thor my_scripts -h + # + # Finally, if you change your namespace to default: + # + # namespace :default + # + # Your tasks can be invoked with a shortcut. Instead of: + # + # thor :my_task + # + def namespace(name=nil) + case name + when nil + @namespace ||= Thor::Util.namespace_from_thor_class(self, false) + else + @namespace = name.to_s + end + end + + # Default way to start generators from the command line. + # + def start(given_args=ARGV, config={}) + config[:shell] ||= Thor::Base.shell.new + yield + rescue Thor::Error => e + if given_args.include?("--debug") + raise e + else + config[:shell].error e.message + end + exit(1) if exit_on_failure? + end + + protected + + # Prints the class options per group. If an option does not belong to + # any group, it uses the ungrouped name value. This method provide to + # hooks to add extra options, one of them if the third argument called + # extra_group that should be a hash in the format :group => Array[Options]. + # + # The second is by returning a lambda used to print values. The lambda + # requires two options: the group name and the array of options. + # + def class_options_help(shell, ungrouped_name=nil, extra_group=nil) #:nodoc: + groups = {} + + class_options.each do |_, value| + groups[value.group] ||= [] + groups[value.group] << value + end + + printer = proc do |group_name, options| + list = [] + padding = options.collect{ |o| o.aliases.size }.max.to_i * 4 + + options.each do |option| + item = [ option.usage(padding) ] + item.push(option.description ? "# #{option.description}" : "") + + list << item + list << [ "", "# Default: #{option.default}" ] if option.show_default? + end + + unless list.empty? + shell.say(group_name ? "#{group_name} options:" : "Options:") + shell.print_table(list, :ident => 2) + shell.say "" + end + end + + # Deal with default group + global_options = groups.delete(nil) || [] + printer.call(ungrouped_name, global_options) if global_options + + # Print all others + groups = extra_group.merge(groups) if extra_group + groups.each(&printer) + printer + end + + # Raises an error if the word given is a Thor reserved word. + # + def is_thor_reserved_word?(word, type) #:nodoc: + return false unless THOR_RESERVED_WORDS.include?(word.to_s) + raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}" + end + + # Build an option and adds it to the given scope. + # + # ==== Parameters + # name:: The name of the argument. + # options:: Described in both class_option and method_option. + # + def build_option(name, options, scope) #:nodoc: + scope[name] = Thor::Option.new(name, options[:desc], options[:required], + options[:type], options[:default], options[:banner], + options[:group], options[:aliases]) + end + + # Receives a hash of options, parse them and add to the scope. This is a + # fast way to set a bunch of options: + # + # build_options :foo => true, :bar => :required, :baz => :string + # + # ==== Parameters + # Hash[Symbol => Object] + # + def build_options(options, scope) #:nodoc: + options.each do |key, value| + scope[key] = Thor::Option.parse(key, value) + end + end + + # Finds a task with the given name. If the task belongs to the current + # class, just return it, otherwise dup it and add the fresh copy to the + # current task hash. + # + def find_and_refresh_task(name) #:nodoc: + task = if task = tasks[name.to_s] + task + elsif task = all_tasks[name.to_s] + tasks[name.to_s] = task.clone + else + raise ArgumentError, "You supplied :for => #{name.inspect}, but the task #{name.inspect} could not be found." + end + end + + # Everytime someone inherits from a Thor class, register the klass + # and file into baseclass. + # + def inherited(klass) + Thor::Base.register_klass_file(klass) + end + + # Fire this callback whenever a method is added. Added methods are + # tracked as tasks by invoking the create_task method. + # + def method_added(meth) + meth = meth.to_s + + if meth == "initialize" + initialize_added + return + end + + # Return if it's not a public instance method + return unless public_instance_methods.include?(meth) || + public_instance_methods.include?(meth.to_sym) + + return if @no_tasks || !create_task(meth) + + is_thor_reserved_word?(meth, :task) + Thor::Base.register_klass_file(self) + end + + # Retrieves a value from superclass. If it reaches the baseclass, + # returns default. + # + def from_superclass(method, default=nil) + if self == baseclass || !superclass.respond_to?(method, true) + default + else + value = superclass.send(method) + value.dup if value + end + end + + # A flag that makes the process exit with status 1 if any error happens. + # + def exit_on_failure? + false + end + + # SIGNATURE: Sets the baseclass. This is where the superclass lookup + # finishes. + def baseclass #:nodoc: + end + + # SIGNATURE: Creates a new task if valid_task? is true. This method is + # called when a new method is added to the class. + def create_task(meth) #:nodoc: + end + + # SIGNATURE: Defines behavior when the initialize method is added to the + # class. + def initialize_added #:nodoc: + end + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb new file mode 100644 index 0000000000..78bc5cf4bf --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb @@ -0,0 +1,75 @@ +class Thor + module CoreExt #:nodoc: + + # A hash with indifferent access and magic predicates. + # + # hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true + # + # hash[:foo] #=> 'bar' + # hash['foo'] #=> 'bar' + # hash.foo? #=> true + # + class HashWithIndifferentAccess < ::Hash #:nodoc: + + def initialize(hash={}) + super() + hash.each do |key, value| + self[convert_key(key)] = value + end + end + + def [](key) + super(convert_key(key)) + end + + def []=(key, value) + super(convert_key(key), value) + end + + def delete(key) + super(convert_key(key)) + end + + def values_at(*indices) + indices.collect { |key| self[convert_key(key)] } + end + + def merge(other) + dup.merge!(other) + end + + def merge!(other) + other.each do |key, value| + self[convert_key(key)] = value + end + self + end + + protected + + def convert_key(key) + key.is_a?(Symbol) ? key.to_s : key + end + + # Magic predicates. For instance: + # + # options.force? # => !!options['force'] + # options.shebang # => "/usr/lib/local/ruby" + # options.test_framework?(:rspec) # => options[:test_framework] == :rspec + # + def method_missing(method, *args, &block) + method = method.to_s + if method =~ /^(\w+)\?$/ + if args.empty? + !!self[$1] + else + self[$1] == args.first + end + else + self[method] + end + end + + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb new file mode 100644 index 0000000000..27fea5bb35 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb @@ -0,0 +1,100 @@ +class Thor + module CoreExt #:nodoc: + + if RUBY_VERSION >= '1.9' + class OrderedHash < ::Hash + end + else + # This class is based on the Ruby 1.9 ordered hashes. + # + # It keeps the semantics and most of the efficiency of normal hashes + # while also keeping track of the order in which elements were set. + # + class OrderedHash #:nodoc: + include Enumerable + + Node = Struct.new(:key, :value, :next, :prev) + + def initialize + @hash = {} + end + + def [](key) + @hash[key] && @hash[key].value + end + + def []=(key, value) + if node = @hash[key] + node.value = value + else + node = Node.new(key, value) + + if @first.nil? + @first = @last = node + else + node.prev = @last + @last.next = node + @last = node + end + end + + @hash[key] = node + value + end + + def delete(key) + if node = @hash[key] + prev_node = node.prev + next_node = node.next + + next_node.prev = prev_node if next_node + prev_node.next = next_node if prev_node + + @first = next_node if @first == node + @last = prev_node if @last == node + + value = node.value + end + + @hash.delete(key) + value + end + + def keys + self.map { |k, v| k } + end + + def values + self.map { |k, v| v } + end + + def each + return unless @first + yield [@first.key, @first.value] + node = @first + yield [node.key, node.value] while node = node.next + self + end + + def merge(other) + hash = self.class.new + + self.each do |key, value| + hash[key] = value + end + + other.each do |key, value| + hash[key] = value + end + + hash + end + + def empty? + @hash.empty? + end + end + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb new file mode 100644 index 0000000000..f9b31a35d1 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb @@ -0,0 +1,27 @@ +class Thor + # Thor::Error is raised when it's caused by wrong usage of thor classes. Those + # errors have their backtrace supressed and are nicely shown to the user. + # + # Errors that are caused by the developer, like declaring a method which + # overwrites a thor keyword, it SHOULD NOT raise a Thor::Error. This way, we + # ensure that developer errors are shown with full backtrace. + # + class Error < StandardError + end + + # Raised when a task was not found. + # + class UndefinedTaskError < Error + end + + # Raised when a task was found, but not invoked properly. + # + class InvocationError < Error + end + + class RequiredArgumentMissingError < InvocationError + end + + class MalformattedArgumentError < InvocationError + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb new file mode 100644 index 0000000000..0964a9667a --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb @@ -0,0 +1,263 @@ +# Thor has a special class called Thor::Group. The main difference to Thor class +# is that it invokes all tasks at once. It also include some methods that allows +# invocations to be done at the class method, which are not available to Thor +# tasks. +# +class Thor::Group + class << self + # The descrition for this Thor::Group. If none is provided, but a source root + # exists, tries to find the USAGE one folder above it, otherwise searches + # in the superclass. + # + # ==== Parameters + # description:: The description for this Thor::Group. + # + def desc(description=nil) + case description + when nil + @desc ||= from_superclass(:desc, nil) + else + @desc = description + end + end + + # Start works differently in Thor::Group, it simply invokes all tasks + # inside the class. + # + def start(given_args=ARGV, config={}) + super do + if Thor::HELP_MAPPINGS.include?(given_args.first) + help(config[:shell]) + return + end + + args, opts = Thor::Options.split(given_args) + new(args, opts, config).invoke + end + end + + # Prints help information. + # + # ==== Options + # short:: When true, shows only usage. + # + def help(shell, options={}) + if options[:short] + shell.say banner + else + shell.say "Usage:" + shell.say " #{banner}" + shell.say + class_options_help(shell) + shell.say self.desc if self.desc + end + end + + # Stores invocations for this class merging with superclass values. + # + def invocations #:nodoc: + @invocations ||= from_superclass(:invocations, {}) + end + + # Stores invocation blocks used on invoke_from_option. + # + def invocation_blocks #:nodoc: + @invocation_blocks ||= from_superclass(:invocation_blocks, {}) + end + + # Invoke the given namespace or class given. It adds an instance + # method that will invoke the klass and task. You can give a block to + # configure how it will be invoked. + # + # The namespace/class given will have its options showed on the help + # usage. Check invoke_from_option for more information. + # + def invoke(*names, &block) + options = names.last.is_a?(Hash) ? names.pop : {} + verbose = options.fetch(:verbose, true) + + names.each do |name| + invocations[name] = false + invocation_blocks[name] = block if block_given? + + class_eval <<-METHOD, __FILE__, __LINE__ + def _invoke_#{name.to_s.gsub(/\W/, '_')} + klass, task = self.class.prepare_for_invocation(nil, #{name.inspect}) + + if klass + say_status :invoke, #{name.inspect}, #{verbose.inspect} + block = self.class.invocation_blocks[#{name.inspect}] + _invoke_for_class_method klass, task, &block + else + say_status :error, %(#{name.inspect} [not found]), :red + end + end + METHOD + end + end + + # Invoke a thor class based on the value supplied by the user to the + # given option named "name". A class option must be created before this + # method is invoked for each name given. + # + # ==== Examples + # + # class GemGenerator < Thor::Group + # class_option :test_framework, :type => :string + # invoke_from_option :test_framework + # end + # + # ==== Boolean options + # + # In some cases, you want to invoke a thor class if some option is true or + # false. This is automatically handled by invoke_from_option. Then the + # option name is used to invoke the generator. + # + # ==== Preparing for invocation + # + # In some cases you want to customize how a specified hook is going to be + # invoked. You can do that by overwriting the class method + # prepare_for_invocation. The class method must necessarily return a klass + # and an optional task. + # + # ==== Custom invocations + # + # You can also supply a block to customize how the option is giong to be + # invoked. The block receives two parameters, an instance of the current + # class and the klass to be invoked. + # + def invoke_from_option(*names, &block) + options = names.last.is_a?(Hash) ? names.pop : {} + verbose = options.fetch(:verbose, :white) + + names.each do |name| + unless class_options.key?(name) + raise ArgumentError, "You have to define the option #{name.inspect} " << + "before setting invoke_from_option." + end + + invocations[name] = true + invocation_blocks[name] = block if block_given? + + class_eval <<-METHOD, __FILE__, __LINE__ + def _invoke_from_option_#{name.to_s.gsub(/\W/, '_')} + return unless options[#{name.inspect}] + + value = options[#{name.inspect}] + value = #{name.inspect} if TrueClass === value + klass, task = self.class.prepare_for_invocation(#{name.inspect}, value) + + if klass + say_status :invoke, value, #{verbose.inspect} + block = self.class.invocation_blocks[#{name.inspect}] + _invoke_for_class_method klass, task, &block + else + say_status :error, %(\#{value} [not found]), :red + end + end + METHOD + end + end + + # Remove a previously added invocation. + # + # ==== Examples + # + # remove_invocation :test_framework + # + def remove_invocation(*names) + names.each do |name| + remove_task(name) + remove_class_option(name) + invocations.delete(name) + invocation_blocks.delete(name) + end + end + + # Overwrite class options help to allow invoked generators options to be + # shown recursively when invoking a generator. + # + def class_options_help(shell, ungrouped_name=nil, extra_group=nil) #:nodoc: + group_options = {} + + get_options_from_invocations(group_options, class_options) do |klass| + klass.send(:get_options_from_invocations, group_options, class_options) + end + + group_options.merge!(extra_group) if extra_group + super(shell, ungrouped_name, group_options) + end + + # Get invocations array and merge options from invocations. Those + # options are added to group_options hash. Options that already exists + # in base_options are not added twice. + # + def get_options_from_invocations(group_options, base_options) #:nodoc: + invocations.each do |name, from_option| + value = if from_option + option = class_options[name] + option.type == :boolean ? name : option.default + else + name + end + next unless value + + klass, task = prepare_for_invocation(name, value) + next unless klass && klass.respond_to?(:class_options) + + value = value.to_s + human_name = value.respond_to?(:classify) ? value.classify : value + + group_options[human_name] ||= [] + group_options[human_name] += klass.class_options.values.select do |option| + base_options[option.name.to_sym].nil? && option.group.nil? && + !group_options.values.flatten.any? { |i| i.name == option.name } + end + + yield klass if block_given? + end + end + + protected + + # The banner for this class. You can customize it if you are invoking the + # thor class by another ways which is not the Thor::Runner. + # + def banner + "#{self.namespace} #{self.arguments.map {|a| a.usage }.join(' ')}" + end + + def baseclass #:nodoc: + Thor::Group + end + + def create_task(meth) #:nodoc: + tasks[meth.to_s] = Thor::Task.new(meth, nil, nil, nil) + true + end + end + + include Thor::Base + + protected + + # Shortcut to invoke with padding and block handling. Use internally by + # invoke and invoke_from_option class methods. + # + def _invoke_for_class_method(klass, task=nil, *args, &block) #:nodoc: + shell.padding += 1 + + result = if block_given? + if block.arity == 2 + block.call(self, klass) + else + block.call(self, klass, task) + end + else + invoke klass, task, *args + end + + shell.padding -= 1 + result + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb new file mode 100644 index 0000000000..32e6a72454 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb @@ -0,0 +1,178 @@ +class Thor + module Invocation + def self.included(base) #:nodoc: + base.extend ClassMethods + end + + module ClassMethods + # Prepare for class methods invocations. This method must return a klass to + # have the invoked class options showed in help messages in generators. + # + def prepare_for_invocation(key, name) #:nodoc: + case name + when Symbol, String + Thor::Util.namespace_to_thor_class_and_task(name.to_s, false) + else + name + end + end + end + + # Make initializer aware of invocations and the initializer proc. + # + def initialize(args=[], options={}, config={}, &block) #:nodoc: + @_invocations = config[:invocations] || Hash.new { |h,k| h[k] = [] } + @_initializer = [ args, options, config ] + super + end + + # Receives a name and invokes it. The name can be a string (either "task" or + # "namespace:task"), a Thor::Task, a Class or a Thor instance. If the task + # cannot be guessed by name, it can also be supplied as second argument. + # + # You can also supply the arguments, options and configuration values for + # the task to be invoked, if none is given, the same values used to + # initialize the invoker are used to initialize the invoked. + # + # ==== Examples + # + # class A < Thor + # def foo + # invoke :bar + # invoke "b:hello", ["José"] + # end + # + # def bar + # invoke "b:hello", ["José"] + # end + # end + # + # class B < Thor + # def hello(name) + # puts "hello #{name}" + # end + # end + # + # You can notice that the method "foo" above invokes two tasks: "bar", + # which belongs to the same class and "hello" which belongs to the class B. + # + # By using an invocation system you ensure that a task is invoked only once. + # In the example above, invoking "foo" will invoke "b:hello" just once, even + # if it's invoked later by "bar" method. + # + # When class A invokes class B, all arguments used on A initialization are + # supplied to B. This allows lazy parse of options. Let's suppose you have + # some rspec tasks: + # + # class Rspec < Thor::Group + # class_option :mock_framework, :type => :string, :default => :rr + # + # def invoke_mock_framework + # invoke "rspec:#{options[:mock_framework]}" + # end + # end + # + # As you noticed, it invokes the given mock framework, which might have its + # own options: + # + # class Rspec::RR < Thor::Group + # class_option :style, :type => :string, :default => :mock + # end + # + # Since it's not rspec concern to parse mock framework options, when RR + # is invoked all options are parsed again, so RR can extract only the options + # that it's going to use. + # + # If you want Rspec::RR to be initialized with its own set of options, you + # have to do that explicitely: + # + # invoke "rspec:rr", [], :style => :foo + # + # Besides giving an instance, you can also give a class to invoke: + # + # invoke Rspec::RR, [], :style => :foo + # + def invoke(name=nil, task=nil, args=nil, opts=nil, config=nil) + task, args, opts, config = nil, task, args, opts if task.nil? || task.is_a?(Array) + args, opts, config = nil, args, opts if args.is_a?(Hash) + + object, task = _prepare_for_invocation(name, task) + klass, instance = _initialize_klass_with_initializer(object, args, opts, config) + + method_args = [] + current = @_invocations[klass] + + iterator = proc do |_, task| + unless current.include?(task.name) + current << task.name + task.run(instance, method_args) + end + end + + if task + args ||= [] + method_args = args[Range.new(klass.arguments.size, -1)] || [] + iterator.call(nil, task) + else + klass.all_tasks.map(&iterator) + end + end + + protected + + # Configuration values that are shared between invocations. + # + def _shared_configuration #:nodoc: + { :invocations => @_invocations } + end + + # Prepare for invocation in the instance level. In this case, we have to + # take into account that a just a task name from the current class was + # given or even a Thor::Task object. + # + def _prepare_for_invocation(name, sent_task=nil) #:nodoc: + if name.is_a?(Thor::Task) + task = name + elsif task = self.class.all_tasks[name.to_s] + object = self + else + object, task = self.class.prepare_for_invocation(nil, name) + task ||= sent_task + end + + # If the object was not set, use self and use the name as task. + object, task = self, name unless object + return object, _validate_task(object, task) + end + + # Check if the object given is a Thor class object and get a task object + # for it. + # + def _validate_task(object, task) #:nodoc: + klass = object.is_a?(Class) ? object : object.class + raise "Expected Thor class, got #{klass}" unless klass <= Thor::Base + + task ||= klass.default_task if klass <= Thor + task = klass.all_tasks[task.to_s] || Thor::Task::Dynamic.new(task) if task && !task.is_a?(Thor::Task) + task + end + + # Initialize klass using values stored in the @_initializer. + # + def _initialize_klass_with_initializer(object, args, opts, config) #:nodoc: + if object.is_a?(Class) + klass = object + + stored_args, stored_opts, stored_config = @_initializer + args ||= stored_args.dup + opts ||= stored_opts.dup + + config ||= {} + config = stored_config.merge(_shared_configuration).merge!(config) + [ klass, klass.new(args, opts, config) ] + else + [ object.class, object ] + end + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb new file mode 100644 index 0000000000..57a3f6e1a5 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb @@ -0,0 +1,4 @@ +require 'thor/parser/argument' +require 'thor/parser/arguments' +require 'thor/parser/option' +require 'thor/parser/options' diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb new file mode 100644 index 0000000000..aa8ace4719 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb @@ -0,0 +1,67 @@ +class Thor + class Argument #:nodoc: + VALID_TYPES = [ :numeric, :hash, :array, :string ] + + attr_reader :name, :description, :required, :type, :default, :banner + alias :human_name :name + + def initialize(name, description=nil, required=true, type=:string, default=nil, banner=nil) + class_name = self.class.name.split("::").last + + raise ArgumentError, "#{class_name} name can't be nil." if name.nil? + raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type) + + @name = name.to_s + @description = description + @required = required || false + @type = (type || :string).to_sym + @default = default + @banner = banner || default_banner + + validate! # Trigger specific validations + end + + def usage + required? ? banner : "[#{banner}]" + end + + def required? + required + end + + def show_default? + case default + when Array, String, Hash + !default.empty? + else + default + end + end + + protected + + def validate! + raise ArgumentError, "An argument cannot be required and have default value." if required? && !default.nil? + end + + def valid_type?(type) + VALID_TYPES.include?(type.to_sym) + end + + def default_banner + case type + when :boolean + nil + when :string, :default + human_name.upcase + when :numeric + "N" + when :hash + "key:value" + when :array + "one two three" + end + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb new file mode 100644 index 0000000000..fb5d965e06 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb @@ -0,0 +1,145 @@ +class Thor + class Arguments #:nodoc: + NUMERIC = /(\d*\.\d+|\d+)/ + + # Receives an array of args and returns two arrays, one with arguments + # and one with switches. + # + def self.split(args) + arguments = [] + + args.each do |item| + break if item =~ /^-/ + arguments << item + end + + return arguments, args[Range.new(arguments.size, -1)] + end + + def self.parse(base, args) + new(base).parse(args) + end + + # Takes an array of Thor::Argument objects. + # + def initialize(arguments=[]) + @assigns, @non_assigned_required = {}, [] + @switches = arguments + + arguments.each do |argument| + if argument.default + @assigns[argument.human_name] = argument.default + elsif argument.required? + @non_assigned_required << argument + end + end + end + + def parse(args) + @pile = args.dup + + @switches.each do |argument| + break unless peek + @non_assigned_required.delete(argument) + @assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name) + end + + check_requirement! + @assigns + end + + private + + def peek + @pile.first + end + + def shift + @pile.shift + end + + def unshift(arg) + unless arg.kind_of?(Array) + @pile.unshift(arg) + else + @pile = arg + @pile + end + end + + def current_is_value? + peek && peek.to_s !~ /^-/ + end + + # Runs through the argument array getting strings that contains ":" and + # mark it as a hash: + # + # [ "name:string", "age:integer" ] + # + # Becomes: + # + # { "name" => "string", "age" => "integer" } + # + def parse_hash(name) + return shift if peek.is_a?(Hash) + hash = {} + + while current_is_value? && peek.include?(?:) + key, value = shift.split(':') + hash[key] = value + end + hash + end + + # Runs through the argument array getting all strings until no string is + # found or a switch is found. + # + # ["a", "b", "c"] + # + # And returns it as an array: + # + # ["a", "b", "c"] + # + def parse_array(name) + return shift if peek.is_a?(Array) + array = [] + + while current_is_value? + array << shift + end + array + end + + # Check if the peel is numeric ofrmat and return a Float or Integer. + # Otherwise raises an error. + # + def parse_numeric(name) + return shift if peek.is_a?(Numeric) + + unless peek =~ NUMERIC && $& == peek + raise MalformattedArgumentError, "expected numeric value for '#{name}'; got #{peek.inspect}" + end + + $&.index('.') ? shift.to_f : shift.to_i + end + + # Parse string, i.e., just return the current value in the pile. + # + def parse_string(name) + shift + end + + # Raises an error if @non_assigned_required array is not empty. + # + def check_requirement! + unless @non_assigned_required.empty? + names = @non_assigned_required.map do |o| + o.respond_to?(:switch_name) ? o.switch_name : o.human_name + end.join("', '") + + class_name = self.class.name.split('::').last.downcase + raise RequiredArgumentMissingError, "no value provided for required #{class_name} '#{names}'" + end + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb new file mode 100644 index 0000000000..9e40ec73fa --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb @@ -0,0 +1,132 @@ +class Thor + class Option < Argument #:nodoc: + attr_reader :aliases, :group + + VALID_TYPES = [:boolean, :numeric, :hash, :array, :string] + + def initialize(name, description=nil, required=nil, type=nil, default=nil, banner=nil, group=nil, aliases=nil) + super(name, description, required, type, default, banner) + @aliases = [*aliases].compact + @group = group.to_s.capitalize if group + end + + # This parse quick options given as method_options. It makes several + # assumptions, but you can be more specific using the option method. + # + # parse :foo => "bar" + # #=> Option foo with default value bar + # + # parse [:foo, :baz] => "bar" + # #=> Option foo with default value bar and alias :baz + # + # parse :foo => :required + # #=> Required option foo without default value + # + # parse :foo => 2 + # #=> Option foo with default value 2 and type numeric + # + # parse :foo => :numeric + # #=> Option foo without default value and type numeric + # + # parse :foo => true + # #=> Option foo with default value true and type boolean + # + # The valid types are :boolean, :numeric, :hash, :array and :string. If none + # is given a default type is assumed. This default type accepts arguments as + # string (--foo=value) or booleans (just --foo). + # + # By default all options are optional, unless :required is given. + # + def self.parse(key, value) + if key.is_a?(Array) + name, *aliases = key + else + name, aliases = key, [] + end + + name = name.to_s + default = value + + type = case value + when Symbol + default = nil + + if VALID_TYPES.include?(value) + value + elsif required = (value == :required) + :string + elsif value == :optional + # TODO Remove this warning in the future. + warn "Optional type is deprecated. Choose :boolean or :string instead. Assumed to be :boolean." + :boolean + end + when TrueClass, FalseClass + :boolean + when Numeric + :numeric + when Hash, Array, String + value.class.name.downcase.to_sym + end + + self.new(name.to_s, nil, required, type, default, nil, nil, aliases) + end + + def switch_name + @switch_name ||= dasherized? ? name : dasherize(name) + end + + def human_name + @human_name ||= dasherized? ? undasherize(name) : name + end + + def usage(padding=0) + sample = if banner && !banner.to_s.empty? + "#{switch_name}=#{banner}" + else + switch_name + end + + sample = "[#{sample}]" unless required? + + if aliases.empty? + (" " * padding) << sample + else + "#{aliases.join(', ')}, #{sample}" + end + end + + # Allow some type predicates as: boolean?, string? and etc. + # + def method_missing(method, *args, &block) + given = method.to_s.sub(/\?$/, '').to_sym + if valid_type?(given) + self.type == given + else + super + end + end + + protected + + def validate! + raise ArgumentError, "An option cannot be boolean and required." if boolean? && required? + end + + def valid_type?(type) + VALID_TYPES.include?(type.to_sym) + end + + def dasherized? + name.index('-') == 0 + end + + def undasherize(str) + str.sub(/^-{1,2}/, '') + end + + def dasherize(str) + (str.length > 1 ? "--" : "-") + str.gsub('_', '-') + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb new file mode 100644 index 0000000000..75092308b5 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb @@ -0,0 +1,142 @@ +class Thor + # This is a modified version of Daniel Berger's Getopt::Long class, licensed + # under Ruby's license. + # + class Options < Arguments #:nodoc: + LONG_RE = /^(--\w+[-\w+]*)$/ + SHORT_RE = /^(-[a-z])$/i + EQ_RE = /^(--\w+[-\w+]*|-[a-z])=(.*)$/i + SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args + SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i + + # Receives a hash and makes it switches. + # + def self.to_switches(options) + options.map do |key, value| + case value + when true + "--#{key}" + when Array + "--#{key} #{value.map{ |v| v.inspect }.join(' ')}" + when Hash + "--#{key} #{value.map{ |k,v| "#{k}:#{v}" }.join(' ')}" + when nil, false + "" + else + "--#{key} #{value.inspect}" + end + end.join(" ") + end + + # Takes a hash of Thor::Option objects. + # + def initialize(options={}) + options = options.values + super(options) + @shorts, @switches = {}, {} + + options.each do |option| + @switches[option.switch_name] = option + + option.aliases.each do |short| + @shorts[short.to_s] ||= option.switch_name + end + end + end + + def parse(args) + @pile = args.dup + + while peek + if current_is_switch? + case shift + when SHORT_SQ_RE + unshift($1.split('').map { |f| "-#{f}" }) + next + when EQ_RE, SHORT_NUM + unshift($2) + switch = $1 + when LONG_RE, SHORT_RE + switch = $1 + end + + switch = normalize_switch(switch) + next unless option = switch_option(switch) + + @assigns[option.human_name] = parse_peek(switch, option) + else + shift + end + end + + check_requirement! + @assigns + end + + protected + + # Returns true if the current value in peek is a registered switch. + # + def current_is_switch? + case peek + when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM + switch?($1) + when SHORT_SQ_RE + $1.split('').any? { |f| switch?("-#{f}") } + end + end + + def switch?(arg) + switch_option(arg) || @shorts.key?(arg) + end + + def switch_option(arg) + if match = no_or_skip?(arg) + @switches[arg] || @switches["--#{match}"] + else + @switches[arg] + end + end + + def no_or_skip?(arg) + arg =~ /^--(no|skip)-([-\w]+)$/ + $2 + end + + # Check if the given argument is actually a shortcut. + # + def normalize_switch(arg) + @shorts.key?(arg) ? @shorts[arg] : arg + end + + # Parse boolean values which can be given as --foo=true, --foo or --no-foo. + # + def parse_boolean(switch) + if current_is_value? + ["true", "TRUE", "t", "T", true].include?(shift) + else + @switches.key?(switch) || !no_or_skip?(switch) + end + end + + # Parse the value at the peek analyzing if it requires an input or not. + # + def parse_peek(switch, option) + unless current_is_value? + if option.boolean? + # No problem for boolean types + elsif no_or_skip?(switch) + return nil # User set value to nil + elsif option.string? && !option.required? + return option.human_name # Return the option name + else + raise MalformattedArgumentError, "no value provided for option '#{switch}'" + end + end + + @non_assigned_required.delete(option) + send(:"parse_#{option.type}", switch) + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb new file mode 100644 index 0000000000..0d0757fdda --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb @@ -0,0 +1,66 @@ +require 'rake' + +class Thor + # Adds a compatibility layer to your Thor classes which allows you to use + # rake package tasks. For example, to use rspec rake tasks, one can do: + # + # require 'thor/rake_compat' + # + # class Default < Thor + # include Thor::RakeCompat + # + # Spec::Rake::SpecTask.new(:spec) do |t| + # t.spec_opts = ['--options', "spec/spec.opts"] + # t.spec_files = FileList['spec/**/*_spec.rb'] + # end + # end + # + module RakeCompat + def self.rake_classes + @rake_classes ||= [] + end + + def self.included(base) + # Hack. Make rakefile point to invoker, so rdoc task is generated properly. + rakefile = File.basename(caller[0].match(/(.*):\d+/)[1]) + Rake.application.instance_variable_set(:@rakefile, rakefile) + self.rake_classes << base + end + end +end + +class Object #:nodoc: + alias :rake_task :task + alias :rake_namespace :namespace + + def task(*args, &block) + task = rake_task(*args, &block) + + if klass = Thor::RakeCompat.rake_classes.last + non_namespaced_name = task.name.split(':').last + + description = non_namespaced_name + description << task.arg_names.map{ |n| n.to_s.upcase }.join(' ') + description.strip! + + klass.desc description, task.comment || non_namespaced_name + klass.send :define_method, non_namespaced_name do |*args| + Rake::Task[task.name.to_sym].invoke(*args) + end + end + + task + end + + def namespace(name, &block) + if klass = Thor::RakeCompat.rake_classes.last + const_name = Thor::Util.camel_case(name.to_s).to_sym + klass.const_set(const_name, Class.new(Thor)) + new_klass = klass.const_get(const_name) + Thor::RakeCompat.rake_classes << new_klass + end + + rake_namespace(name, &block) + Thor::RakeCompat.rake_classes.pop + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb new file mode 100644 index 0000000000..9dc70ea069 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb @@ -0,0 +1,299 @@ +require 'fileutils' +require 'open-uri' +require 'yaml' +require 'digest/md5' +require 'pathname' + +class Thor::Runner < Thor #:nodoc: + map "-T" => :list, "-i" => :install, "-u" => :update + + # Override Thor#help so it can give information about any class and any method. + # + def help(meth=nil) + if meth && !self.respond_to?(meth) + initialize_thorfiles(meth) + klass, task = Thor::Util.namespace_to_thor_class_and_task(meth) + # Send mapping -h because it works with Thor::Group too + klass.start(["-h", task].compact, :shell => self.shell) + else + super + end + end + + # If a task is not found on Thor::Runner, method missing is invoked and + # Thor::Runner is then responsable for finding the task in all classes. + # + def method_missing(meth, *args) + meth = meth.to_s + initialize_thorfiles(meth) + klass, task = Thor::Util.namespace_to_thor_class_and_task(meth) + args.unshift(task) if task + klass.start(args, :shell => shell) + end + + desc "install NAME", "Install an optionally named Thor file into your system tasks" + method_options :as => :string, :relative => :boolean + def install(name) + initialize_thorfiles + + # If a directory name is provided as the argument, look for a 'main.thor' + # task in said directory. + begin + if File.directory?(File.expand_path(name)) + base, package = File.join(name, "main.thor"), :directory + contents = open(base).read + else + base, package = name, :file + contents = open(name).read + end + rescue OpenURI::HTTPError + raise Error, "Error opening URI '#{name}'" + rescue Errno::ENOENT + raise Error, "Error opening file '#{name}'" + end + + say "Your Thorfile contains:" + say contents + + return false if no?("Do you wish to continue [y/N]?") + + as = options["as"] || begin + first_line = contents.split("\n")[0] + (match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil + end + + unless as + basename = File.basename(name) + as = ask("Please specify a name for #{name} in the system repository [#{basename}]:") + as = basename if as.empty? + end + + location = if options[:relative] || name =~ /^http:\/\// + name + else + File.expand_path(name) + end + + thor_yaml[as] = { + :filename => Digest::MD5.hexdigest(name + as), + :location => location, + :namespaces => Thor::Util.namespaces_in_content(contents, base) + } + + save_yaml(thor_yaml) + say "Storing thor file in your system repository" + destination = File.join(thor_root, thor_yaml[as][:filename]) + + if package == :file + File.open(destination, "w") { |f| f.puts contents } + else + FileUtils.cp_r(name, destination) + end + + thor_yaml[as][:filename] # Indicate success + end + + desc "uninstall NAME", "Uninstall a named Thor module" + def uninstall(name) + raise Error, "Can't find module '#{name}'" unless thor_yaml[name] + say "Uninstalling #{name}." + FileUtils.rm_rf(File.join(thor_root, "#{thor_yaml[name][:filename]}")) + + thor_yaml.delete(name) + save_yaml(thor_yaml) + + puts "Done." + end + + desc "update NAME", "Update a Thor file from its original location" + def update(name) + raise Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location] + + say "Updating '#{name}' from #{thor_yaml[name][:location]}" + + old_filename = thor_yaml[name][:filename] + self.options = self.options.merge("as" => name) + filename = install(thor_yaml[name][:location]) + + unless filename == old_filename + File.delete(File.join(thor_root, old_filename)) + end + end + + desc "installed", "List the installed Thor modules and tasks" + method_options :internal => :boolean + def installed + initialize_thorfiles(nil, true) + + klasses = Thor::Base.subclasses + klasses -= [Thor, Thor::Runner] unless options["internal"] + + display_klasses(true, klasses) + end + + desc "list [SEARCH]", "List the available thor tasks (--substring means .*SEARCH)" + method_options :substring => :boolean, :group => :string, :all => :boolean + def list(search="") + initialize_thorfiles + + search = ".*#{search}" if options["substring"] + search = /^#{search}.*/i + group = options[:group] || "standard" + + klasses = Thor::Base.subclasses.select do |k| + (options[:all] || k.group == group) && k.namespace =~ search + end + + display_klasses(false, klasses) + end + + private + + def thor_root + Thor::Util.thor_root + end + + def thor_yaml + @thor_yaml ||= begin + yaml_file = File.join(thor_root, "thor.yml") + yaml = YAML.load_file(yaml_file) if File.exists?(yaml_file) + yaml || {} + end + end + + # Save the yaml file. If none exists in thor root, creates one. + # + def save_yaml(yaml) + yaml_file = File.join(thor_root, "thor.yml") + + unless File.exists?(yaml_file) + FileUtils.mkdir_p(thor_root) + yaml_file = File.join(thor_root, "thor.yml") + FileUtils.touch(yaml_file) + end + + File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml } + end + + def self.exit_on_failure? + true + end + + # Load the thorfiles. If relevant_to is supplied, looks for specific files + # in the thor_root instead of loading them all. + # + # By default, it also traverses the current path until find Thor files, as + # described in thorfiles. This look up can be skipped by suppliying + # skip_lookup true. + # + def initialize_thorfiles(relevant_to=nil, skip_lookup=false) + thorfiles(relevant_to, skip_lookup).each do |f| + Thor::Util.load_thorfile(f) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f)) + end + end + + # Finds Thorfiles by traversing from your current directory down to the root + # directory of your system. If at any time we find a Thor file, we stop. + # + # We also ensure that system-wide Thorfiles are loaded first, so local + # Thorfiles can override them. + # + # ==== Example + # + # If we start at /Users/wycats/dev/thor ... + # + # 1. /Users/wycats/dev/thor + # 2. /Users/wycats/dev + # 3. /Users/wycats <-- we find a Thorfile here, so we stop + # + # Suppose we start at c:\Documents and Settings\james\dev\thor ... + # + # 1. c:\Documents and Settings\james\dev\thor + # 2. c:\Documents and Settings\james\dev + # 3. c:\Documents and Settings\james + # 4. c:\Documents and Settings + # 5. c:\ <-- no Thorfiles found! + # + def thorfiles(relevant_to=nil, skip_lookup=false) + # TODO Remove this dealing with deprecated thor when :namespaces: is available as constants + save_yaml(thor_yaml) if Thor::Util.convert_constants_to_namespaces(thor_yaml) + + thorfiles = [] + + unless skip_lookup + Pathname.pwd.ascend do |path| + thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten + break unless thorfiles.empty? + end + end + + files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob) + files += thorfiles + files -= ["#{thor_root}/thor.yml"] + + files.map! do |file| + File.directory?(file) ? File.join(file, "main.thor") : file + end + end + + # Load thorfiles relevant to the given method. If you provide "foo:bar" it + # will load all thor files in the thor.yaml that has "foo" e "foo:bar" + # namespaces registered. + # + def thorfiles_relevant_to(meth) + lookup = [ meth, meth.split(":")[0...-1].join(":") ] + + files = thor_yaml.select do |k, v| + v[:namespaces] && !(v[:namespaces] & lookup).empty? + end + + files.map { |k, v| File.join(thor_root, "#{v[:filename]}") } + end + + # Display information about the given klasses. If with_module is given, + # it shows a table with information extracted from the yaml file. + # + def display_klasses(with_modules=false, klasses=Thor.subclasses) + klasses -= [Thor, Thor::Runner] unless with_modules + raise Error, "No Thor tasks available" if klasses.empty? + + if with_modules && !thor_yaml.empty? + info = [] + labels = ["Modules", "Namespaces"] + + info << labels + info << [ "-" * labels[0].size, "-" * labels[1].size ] + + thor_yaml.each do |name, hash| + info << [ name, hash[:namespaces].join(", ") ] + end + + print_table info + say "" + end + + unless klasses.empty? + klasses.dup.each do |klass| + klasses -= Thor::Util.thor_classes_in(klass) + end + + klasses.each { |k| display_tasks(k) } + else + say "\033[1;34mNo Thor tasks available\033[0m" + end + end + + # Display tasks from the given Thor class. + # + def display_tasks(klass) + unless klass.tasks.empty? + base = klass.namespace + + color = base == "default" ? :magenta : :blue + say shell.set_color(base, color, true) + say "-" * base.length + + klass.help(shell, :short => true, :ident => 0, :namespace => true) + end + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb new file mode 100644 index 0000000000..1dc8f0e5b4 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb @@ -0,0 +1,78 @@ +require 'rbconfig' +require 'thor/shell/color' + +class Thor + module Base + # Returns the shell used in all Thor classes. If you are in a Unix platform + # it will use a colored log, otherwise it will use a basic one without color. + # + def self.shell + @shell ||= if Config::CONFIG['host_os'] =~ /mswin|mingw/ + Thor::Shell::Basic + else + Thor::Shell::Color + end + end + + # Sets the shell used in all Thor classes. + # + def self.shell=(klass) + @shell = klass + end + end + + module Shell + SHELL_DELEGATED_METHODS = [:ask, :yes?, :no?, :say, :say_status, :print_list, :print_table] + + # Add shell to initialize config values. + # + # ==== Configuration + # shell:: An instance of the shell to be used. + # + # ==== Examples + # + # class MyScript < Thor + # argument :first, :type => :numeric + # end + # + # MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new + # + def initialize(args=[], options={}, config={}) + super + self.shell = config[:shell] + self.shell.base ||= self if self.shell.respond_to?(:base) + end + + # Holds the shell for the given Thor instance. If no shell is given, + # it gets a default shell from Thor::Base.shell. + # + def shell + @shell ||= Thor::Base.shell.new + end + + # Sets the shell for this thor class. + # + def shell=(shell) + @shell = shell + end + + # Common methods that are delegated to the shell. + # + SHELL_DELEGATED_METHODS.each do |method| + module_eval <<-METHOD, __FILE__, __LINE__ + def #{method}(*args) + shell.#{method}(*args) + end + METHOD + end + + protected + + # Allow shell to be shared between invocations. + # + def _shared_configuration #:nodoc: + super.merge!(:shell => self.shell) + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb new file mode 100644 index 0000000000..ea9665380b --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb @@ -0,0 +1,219 @@ +require 'tempfile' + +class Thor + module Shell + class Basic + attr_accessor :base, :padding + + # Initialize base and padding to nil. + # + def initialize #:nodoc: + @base, @padding = nil, 0 + end + + # Sets the output padding, not allowing less than zero values. + # + def padding=(value) + @padding = [0, value].max + end + + # Ask something to the user and receives a response. + # + # ==== Example + # ask("What is your name?") + # + def ask(statement, color=nil) + say("#{statement} ", color) + $stdin.gets.strip + end + + # Say (print) something to the user. If the sentence ends with a whitespace + # or tab character, a new line is not appended (print + flush). Otherwise + # are passed straight to puts (behavior got from Highline). + # + # ==== Example + # say("I know you knew that.") + # + def say(message="", color=nil, force_new_line=(message.to_s !~ /( |\t)$/)) + message = message.to_s + message = set_color(message, color) if color + + if force_new_line + $stdout.puts(message) + else + $stdout.print(message) + $stdout.flush + end + end + + # Say a status with the given color and appends the message. Since this + # method is used frequently by actions, it allows nil or false to be given + # in log_status, avoiding the message from being shown. If a Symbol is + # given in log_status, it's used as the color. + # + def say_status(status, message, log_status=true) + return if quiet? || log_status == false + spaces = " " * (padding + 1) + color = log_status.is_a?(Symbol) ? log_status : :green + + status = status.to_s.rjust(12) + status = set_color status, color, true if color + say "#{status}#{spaces}#{message}", nil, true + end + + # Make a question the to user and returns true if the user replies "y" or + # "yes". + # + def yes?(statement, color=nil) + ask(statement, color) =~ is?(:yes) + end + + # Make a question the to user and returns true if the user replies "n" or + # "no". + # + def no?(statement, color=nil) + !yes?(statement, color) + end + + # Prints a list of items. + # + # ==== Parameters + # list + # + # ==== Options + # mode:: Can be :rows or :inline. Defaults to :rows. + # ident:: Ident each item with the value given. + # + def print_list(list, options={}) + return if list.empty? + + ident = " " * (options[:ident] || 0) + content = case options[:mode] + when :inline + last = list.pop + "#{list.join(", ")}, and #{last}" + else # rows + ident + list.join("\n#{ident}") + end + + $stdout.puts content + end + + # Prints a table. + # + # ==== Parameters + # Array[Array[String, String, ...]] + # + # ==== Options + # ident:: Ident the first column by ident value. + # + def print_table(table, options={}) + return if table.empty? + + formats = [] + 0.upto(table.first.length - 2) do |i| + maxima = table.max{ |a,b| a[i].size <=> b[i].size }[i].size + formats << "%-#{maxima + 2}s" + end + + formats[0] = formats[0].insert(0, " " * options[:ident]) if options[:ident] + formats << "%s" + + table.each do |row| + row.each_with_index do |column, i| + $stdout.print formats[i] % column.to_s + end + $stdout.puts + end + end + + # Deals with file collision and returns true if the file should be + # overwriten and false otherwise. If a block is given, it uses the block + # response as the content for the diff. + # + # ==== Parameters + # destination:: the destination file to solve conflicts + # block:: an optional block that returns the value to be used in diff + # + def file_collision(destination) + return true if @always_force + options = block_given? ? "[Ynaqdh]" : "[Ynaqh]" + + while true + answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}] + + case answer + when is?(:yes), is?(:force) + return true + when is?(:no), is?(:skip) + return false + when is?(:always) + return @always_force = true + when is?(:quit) + say 'Aborting...' + raise SystemExit + when is?(:diff) + show_diff(destination, yield) if block_given? + say 'Retrying...' + else + say file_collision_help + end + end + end + + # Called if something goes wrong during the execution. This is used by Thor + # internally and should not be used inside your scripts. If someone went + # wrong, you can always raise an exception. If you raise a Thor::Error, it + # will be rescued and wrapped in the method below. + # + def error(statement) + $stderr.puts statement + end + + # Apply color to the given string with optional bold. Disabled in the + # Thor::Shell::Basic class. + # + def set_color(string, color, bold=false) #:nodoc: + string + end + + protected + + def is?(value) #:nodoc: + value = value.to_s + + if value.size == 1 + /\A#{value}\z/i + else + /\A(#{value}|#{value[0,1]})\z/i + end + end + + def file_collision_help #:nodoc: +< e + parse_argument_error(instance, e, caller) + rescue NoMethodError => e + parse_no_method_error(instance, e) + end + + # Returns the formatted usage. If a class is given, the class arguments are + # injected in the usage. + # + def formatted_usage(klass=nil, namespace=false, show_options=true) + formatted = if namespace.is_a?(String) + "#{namespace}:" + elsif klass && namespace + "#{klass.namespace.gsub(/^default/,'')}:" + else + "" + end + + formatted << formatted_arguments(klass) + formatted << " #{formatted_options}" if show_options + formatted.strip! + formatted + end + + # Injects the class arguments into the task usage. + # + def formatted_arguments(klass) + if klass && !klass.arguments.empty? + usage.to_s.gsub(/^#{name}/) do |match| + match << " " << klass.arguments.map{ |a| a.usage }.join(' ') + end + else + usage.to_s + end + end + + # Returns the options usage for this task. + # + def formatted_options + @formatted_options ||= options.map{ |_, o| o.usage }.sort.join(" ") + end + + protected + + # Given a target, checks if this class name is not a private/protected method. + # + def public_method?(instance) #:nodoc: + collection = instance.private_methods + instance.protected_methods + (collection & [name.to_s, name.to_sym]).empty? + end + + # Clean everything that comes from the Thor gempath and remove the caller. + # + def sans_backtrace(backtrace, caller) #:nodoc: + dirname = /^#{Regexp.escape(File.dirname(__FILE__))}/ + saned = backtrace.reject { |frame| frame =~ dirname } + saned -= caller + end + + def parse_argument_error(instance, e, caller) #:nodoc: + backtrace = sans_backtrace(e.backtrace, caller) + + if backtrace.empty? && e.message =~ /wrong number of arguments/ + if instance.is_a?(Thor::Group) + raise e, "'#{name}' was called incorrectly. Are you sure it has arity equals to 0?" + else + raise InvocationError, "'#{name}' was called incorrectly. Call as " << + "'#{formatted_usage(instance.class, true)}'" + end + else + raise e + end + end + + def parse_no_method_error(instance, e) #:nodoc: + if e.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/ + raise UndefinedTaskError, "The #{instance.class.namespace} namespace " << + "doesn't have a '#{name}' task" + else + raise e + end + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb new file mode 100644 index 0000000000..ebae0a3193 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb @@ -0,0 +1,251 @@ +require 'rbconfig' + +class Thor + module Sandbox #:nodoc: + end + + # This module holds several utilities: + # + # 1) Methods to convert thor namespaces to constants and vice-versa. + # + # Thor::Utils.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz" + # + # 2) Loading thor files and sandboxing: + # + # Thor::Utils.load_thorfile("~/.thor/foo") + # + module Util + + # Receives a namespace and search for it in the Thor::Base subclasses. + # + # ==== Parameters + # namespace:: The namespace to search for. + # + def self.find_by_namespace(namespace) + namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/ + + Thor::Base.subclasses.find do |klass| + klass.namespace == namespace + end + end + + # Receives a constant and converts it to a Thor namespace. Since Thor tasks + # can be added to a sandbox, this method is also responsable for removing + # the sandbox namespace. + # + # This method should not be used in general because it's used to deal with + # older versions of Thor. On current versions, if you need to get the + # namespace from a class, just call namespace on it. + # + # ==== Parameters + # constant:: The constant to be converted to the thor path. + # + # ==== Returns + # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz" + # + def self.namespace_from_thor_class(constant, remove_default=true) + constant = constant.to_s.gsub(/^Thor::Sandbox::/, "") + constant = snake_case(constant).squeeze(":") + constant.gsub!(/^default/, '') if remove_default + constant + end + + # Given the contents, evaluate it inside the sandbox and returns the + # namespaces defined in the sandbox. + # + # ==== Parameters + # contents + # + # ==== Returns + # Array[Object] + # + def self.namespaces_in_content(contents, file=__FILE__) + old_constants = Thor::Base.subclasses.dup + Thor::Base.subclasses.clear + + load_thorfile(file, contents) + + new_constants = Thor::Base.subclasses.dup + Thor::Base.subclasses.replace(old_constants) + + new_constants.map!{ |c| c.namespace } + new_constants.compact! + new_constants + end + + # Returns the thor classes declared inside the given class. + # + def self.thor_classes_in(klass) + Thor::Base.subclasses.select do |subclass| + klass.constants.include?(subclass.name.gsub("#{klass.name}::", '')) + end + end + + # Receives a string and convert it to snake case. SnakeCase returns snake_case. + # + # ==== Parameters + # String + # + # ==== Returns + # String + # + def self.snake_case(str) + return str.downcase if str =~ /^[A-Z_]+$/ + str.gsub(/\B[A-Z]/, '_\&').squeeze('_') =~ /_*(.*)/ + return $+.downcase + end + + # Receives a string and convert it to camel case. camel_case returns CamelCase. + # + # ==== Parameters + # String + # + # ==== Returns + # String + # + def self.camel_case(str) + return str if str !~ /_/ && str =~ /[A-Z]+.*/ + str.split('_').map { |i| i.capitalize }.join + end + + # Receives a namespace and tries to retrieve a Thor or Thor::Group class + # from it. It first searches for a class using the all the given namespace, + # if it's not found, removes the highest entry and searches for the class + # again. If found, returns the highest entry as the class name. + # + # ==== Examples + # + # class Foo::Bar < Thor + # def baz + # end + # end + # + # class Baz::Foo < Thor::Group + # end + # + # Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default task + # Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil + # Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz" + # + # ==== Parameters + # namespace + # + # ==== Errors + # Thor::Error:: raised if the namespace cannot be found. + # + # Thor::Error:: raised if the namespace evals to a class which does not + # inherit from Thor or Thor::Group. + # + def self.namespace_to_thor_class_and_task(namespace, raise_if_nil=true) + if namespace.include?(?:) + pieces = namespace.split(":") + task = pieces.pop + klass = Thor::Util.find_by_namespace(pieces.join(":")) + end + + unless klass + klass, task = Thor::Util.find_by_namespace(namespace), nil + end + + raise Error, "could not find Thor class or task '#{namespace}'" if raise_if_nil && klass.nil? + return klass, task + end + + # Receives a path and load the thor file in the path. The file is evaluated + # inside the sandbox to avoid namespacing conflicts. + # + def self.load_thorfile(path, content=nil) + content ||= File.read(path) + + begin + Thor::Sandbox.class_eval(content, path) + rescue Exception => e + $stderr.puts "WARNING: unable to load thorfile #{path.inspect}: #{e.message}" + end + end + + # Receives a yaml (hash) and updates all constants entries to namespace. + # This was added to deal with deprecated versions of Thor. + # + # TODO Deprecate this method in the future. + # + # ==== Returns + # TrueClass|FalseClass:: Returns true if any change to the yaml file was made. + # + def self.convert_constants_to_namespaces(yaml) + yaml_changed = false + + yaml.each do |k, v| + next unless v[:constants] && v[:namespaces].nil? + yaml_changed = true + yaml[k][:namespaces] = v[:constants].map{|c| Thor::Util.namespace_from_thor_class(c)} + end + + yaml_changed + end + + def self.user_home + @@user_home ||= if ENV["HOME"] + ENV["HOME"] + elsif ENV["USERPROFILE"] + ENV["USERPROFILE"] + elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"] + File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"]) + elsif ENV["APPDATA"] + ENV["APPDATA"] + else + begin + File.expand_path("~") + rescue + if File::ALT_SEPARATOR + "C:/" + else + "/" + end + end + end + end + + # Returns the root where thor files are located, dependending on the OS. + # + def self.thor_root + File.join(user_home, ".thor").gsub(/\\/, '/') + end + + # Returns the files in the thor root. On Windows thor_root will be something + # like this: + # + # C:\Documents and Settings\james\.thor + # + # If we don't #gsub the \ character, Dir.glob will fail. + # + def self.thor_root_glob + files = Dir["#{thor_root}/*"] + + files.map! do |file| + File.directory?(file) ? File.join(file, "main.thor") : file + end + end + + # Where to look for Thor files. + # + def self.globs_for(path) + ["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"] + end + + # Return the path to the ruby interpreter taking into account multiple + # installations and windows extensions. + # + def self.ruby_command + @ruby_command ||= begin + ruby = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']) + ruby << Config::CONFIG['EXEEXT'] + + # escape string in case path to ruby executable contain spaces. + ruby.sub!(/.*\s.*/m, '"\&"') + ruby + end + end + + end +end diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb new file mode 100644 index 0000000000..885230fac4 --- /dev/null +++ b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb @@ -0,0 +1,3 @@ +class Thor + VERSION = "0.11.8".freeze +end -- cgit v1.2.3 From 51fe6d05e73a4e0f8481f4e441f4ca886d65a69c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 6 Nov 2009 23:40:18 -0200 Subject: Refactor generators a little bit. Signed-off-by: Yehuda Katz --- railties/lib/rails/commands/destroy.rb | 3 +++ railties/lib/rails/commands/generate.rb | 3 +++ railties/lib/rails/generators/rails/app/app_generator.rb | 6 ++++-- railties/lib/rails/generators/rails/app/templates/script/about | 3 +++ railties/lib/rails/generators/rails/app/templates/script/about.tt | 4 ---- railties/lib/rails/generators/rails/app/templates/script/console | 2 ++ railties/lib/rails/generators/rails/app/templates/script/console.tt | 3 --- railties/lib/rails/generators/rails/app/templates/script/dbconsole | 2 ++ .../lib/rails/generators/rails/app/templates/script/dbconsole.tt | 3 --- railties/lib/rails/generators/rails/app/templates/script/destroy | 2 ++ railties/lib/rails/generators/rails/app/templates/script/destroy.tt | 5 ----- railties/lib/rails/generators/rails/app/templates/script/generate | 2 ++ .../lib/rails/generators/rails/app/templates/script/generate.tt | 5 ----- .../generators/rails/app/templates/script/performance/benchmarker | 2 ++ .../rails/app/templates/script/performance/benchmarker.tt | 3 --- .../generators/rails/app/templates/script/performance/profiler | 2 ++ .../generators/rails/app/templates/script/performance/profiler.tt | 3 --- railties/lib/rails/generators/rails/app/templates/script/plugin | 2 ++ railties/lib/rails/generators/rails/app/templates/script/plugin.tt | 3 --- railties/lib/rails/generators/rails/app/templates/script/runner | 2 ++ railties/lib/rails/generators/rails/app/templates/script/runner.tt | 3 --- railties/lib/rails/generators/rails/app/templates/script/server | 2 ++ railties/lib/rails/generators/rails/app/templates/script/server.tt | 3 --- 23 files changed, 31 insertions(+), 37 deletions(-) create mode 100755 railties/lib/rails/generators/rails/app/templates/script/about delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/about.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/console delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/console.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/dbconsole delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/destroy delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/destroy.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/generate delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/generate.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/performance/profiler delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/performance/profiler.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/plugin delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/plugin.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/runner delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/runner.tt create mode 100755 railties/lib/rails/generators/rails/app/templates/script/server delete mode 100755 railties/lib/rails/generators/rails/app/templates/script/server.tt diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb index 15ff90f78a..f85c17bb94 100644 --- a/railties/lib/rails/commands/destroy.rb +++ b/railties/lib/rails/commands/destroy.rb @@ -1,3 +1,6 @@ +require 'rails/generators' +Rails::Generators.configure! + if ARGV.size == 0 Rails::Generators.help exit diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb index 82a658e2ed..c5e3ae3529 100755 --- a/railties/lib/rails/commands/generate.rb +++ b/railties/lib/rails/commands/generate.rb @@ -1,3 +1,6 @@ +require 'rails/generators' +Rails::Generators.configure! + if ARGV.size == 0 Rails::Generators.help exit diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index e552cc4520..2bcea4bc8f 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -123,8 +123,10 @@ module Rails::Generators end def create_script_files - directory "script" - chmod "script", 0755, :verbose => false + directory "script" do |file| + prepend_file file, "#{shebang}\n", :verbose => false + chmod file, 0755, :verbose => false + end end def create_test_files diff --git a/railties/lib/rails/generators/rails/app/templates/script/about b/railties/lib/rails/generators/rails/app/templates/script/about new file mode 100755 index 0000000000..93fd007649 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/about @@ -0,0 +1,3 @@ +require File.expand_path('../../config/environment', __FILE__) +$LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info" +require 'rails/commands/about' diff --git a/railties/lib/rails/generators/rails/app/templates/script/about.tt b/railties/lib/rails/generators/rails/app/templates/script/about.tt deleted file mode 100755 index 7639d4040f..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/about.tt +++ /dev/null @@ -1,4 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/environment', __FILE__) -$LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info" -require 'rails/commands/about' diff --git a/railties/lib/rails/generators/rails/app/templates/script/console b/railties/lib/rails/generators/rails/app/templates/script/console new file mode 100755 index 0000000000..20aa799d2f --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/console @@ -0,0 +1,2 @@ +require File.expand_path('../../config/application', __FILE__) +require 'rails/commands/console' diff --git a/railties/lib/rails/generators/rails/app/templates/script/console.tt b/railties/lib/rails/generators/rails/app/templates/script/console.tt deleted file mode 100755 index 1cd2eb8b53..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/console.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/application', __FILE__) -require 'rails/commands/console' diff --git a/railties/lib/rails/generators/rails/app/templates/script/dbconsole b/railties/lib/rails/generators/rails/app/templates/script/dbconsole new file mode 100755 index 0000000000..e6a1c59394 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/dbconsole @@ -0,0 +1,2 @@ +require File.expand_path('../../config/application', __FILE__) +require 'rails/commands/dbconsole' diff --git a/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt b/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt deleted file mode 100755 index 94beb13715..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/application', __FILE__) -require 'rails/commands/dbconsole' diff --git a/railties/lib/rails/generators/rails/app/templates/script/destroy b/railties/lib/rails/generators/rails/app/templates/script/destroy new file mode 100755 index 0000000000..adfa8e8426 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/destroy @@ -0,0 +1,2 @@ +require File.expand_path('../../config/environment', __FILE__) +require 'rails/commands/destroy' diff --git a/railties/lib/rails/generators/rails/app/templates/script/destroy.tt b/railties/lib/rails/generators/rails/app/templates/script/destroy.tt deleted file mode 100755 index 6adc90b2c3..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/destroy.tt +++ /dev/null @@ -1,5 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/environment', __FILE__) -require 'rails/generators' -Rails::Generators.configure! -require 'rails/commands/destroy' diff --git a/railties/lib/rails/generators/rails/app/templates/script/generate b/railties/lib/rails/generators/rails/app/templates/script/generate new file mode 100755 index 0000000000..6fb8ad0395 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/generate @@ -0,0 +1,2 @@ +require File.expand_path('../../config/environment', __FILE__) +require 'rails/commands/generate' diff --git a/railties/lib/rails/generators/rails/app/templates/script/generate.tt b/railties/lib/rails/generators/rails/app/templates/script/generate.tt deleted file mode 100755 index 71d47dec92..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/generate.tt +++ /dev/null @@ -1,5 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/environment', __FILE__) -require 'rails/generators' -Rails::Generators.configure! -require 'rails/commands/generate' diff --git a/railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker b/railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker new file mode 100755 index 0000000000..9647d8f10a --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker @@ -0,0 +1,2 @@ +require File.expand_path('../../../config/environment', __FILE__) +require 'rails/commands/performance/benchmarker' diff --git a/railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker.tt b/railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker.tt deleted file mode 100755 index 9ebc4c92fc..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/performance/benchmarker.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../../config/environment', __FILE__) -require 'rails/commands/performance/benchmarker' diff --git a/railties/lib/rails/generators/rails/app/templates/script/performance/profiler b/railties/lib/rails/generators/rails/app/templates/script/performance/profiler new file mode 100755 index 0000000000..a5822042d2 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/performance/profiler @@ -0,0 +1,2 @@ +require File.expand_path('../../../config/environment', __FILE__) +require 'rails/commands/performance/profiler' diff --git a/railties/lib/rails/generators/rails/app/templates/script/performance/profiler.tt b/railties/lib/rails/generators/rails/app/templates/script/performance/profiler.tt deleted file mode 100755 index 5f4c763f9d..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/performance/profiler.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../../config/environment', __FILE__) -require 'rails/commands/performance/profiler' diff --git a/railties/lib/rails/generators/rails/app/templates/script/plugin b/railties/lib/rails/generators/rails/app/templates/script/plugin new file mode 100755 index 0000000000..1f1af6c880 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/plugin @@ -0,0 +1,2 @@ +require File.expand_path('../../config/application', __FILE__) +require 'rails/commands/plugin' diff --git a/railties/lib/rails/generators/rails/app/templates/script/plugin.tt b/railties/lib/rails/generators/rails/app/templates/script/plugin.tt deleted file mode 100755 index 4a335ee33c..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/plugin.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/application', __FILE__) -require 'rails/commands/plugin' diff --git a/railties/lib/rails/generators/rails/app/templates/script/runner b/railties/lib/rails/generators/rails/app/templates/script/runner new file mode 100755 index 0000000000..7a70828e90 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/runner @@ -0,0 +1,2 @@ +require File.expand_path('../../config/environment', __FILE__) +require 'rails/commands/runner' diff --git a/railties/lib/rails/generators/rails/app/templates/script/runner.tt b/railties/lib/rails/generators/rails/app/templates/script/runner.tt deleted file mode 100755 index 34ad7c18eb..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/runner.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/environment', __FILE__) -require 'rails/commands/runner' diff --git a/railties/lib/rails/generators/rails/app/templates/script/server b/railties/lib/rails/generators/rails/app/templates/script/server new file mode 100755 index 0000000000..a7aaee2953 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/script/server @@ -0,0 +1,2 @@ +require File.expand_path('../../config/application', __FILE__) +require 'rails/commands/server' diff --git a/railties/lib/rails/generators/rails/app/templates/script/server.tt b/railties/lib/rails/generators/rails/app/templates/script/server.tt deleted file mode 100755 index 932e72ea58..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/script/server.tt +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang %> -require File.expand_path('../../config/application', __FILE__) -require 'rails/commands/server' -- cgit v1.2.3 From c44fb4ced5cbe61adb12f3431db05afa492bd176 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 21:30:34 -0800 Subject: Ruby 1.9: use method_name to work around miniunit API changes --- activesupport/lib/active_support/testing/setup_and_teardown.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb index 7952eb50c3..0e998d2dbe 100644 --- a/activesupport/lib/active_support/testing/setup_and_teardown.rb +++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb @@ -21,12 +21,12 @@ module ActiveSupport run_callbacks :setup result = super rescue Exception => e - result = runner.puke(self.class, self.name, e) + result = runner.puke(self.class, method_name, e) ensure begin run_callbacks :teardown, :enumerator => :reverse_each rescue Exception => e - result = runner.puke(self.class, self.name, e) + result = runner.puke(self.class, method_name, e) end end result -- cgit v1.2.3 From 7ad461b44dabb586fbad190493ac4ecd96104597 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 21:31:06 -0800 Subject: Ruby 1.9.2: avoid Array#to_s and Array(nil) --- .../lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb index 1b49debc05..7487b96b8c 100755 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb @@ -195,10 +195,19 @@ module I18n # Merges the given locale, key and scope into a single array of keys. # Splits keys that contain dots into multiple keys. Makes sure all # keys are Symbols. - def normalize_translation_keys(locale, key, scope) - keys = [locale] + Array(scope) + [key] - keys = keys.map { |k| k.to_s.split(/\./) } - keys.flatten.map { |k| k.to_sym } + def normalize_translation_keys(*keys) + normalized = [] + keys.each do |key| + case key + when Array + normalized.concat normalize_translation_keys(*key) + when nil + # skip + else + normalized.concat key.to_s.split('.').map { |sub| sub.to_sym } + end + end + normalized end end end -- cgit v1.2.3 From 20cdaddfd27dfeef5c853e85fafa4e13b6da05f3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 21:55:43 -0800 Subject: Ruby 1.9.2: work around changes to flatten and nil.to_str --- activesupport/lib/active_support/cache.rb | 3 ++- .../lib/active_support/core_ext/hash/conversions.rb | 3 ++- activesupport/lib/active_support/dependencies.rb | 2 +- .../lib/active_support/deprecated_callbacks.rb | 5 +++-- .../lib/active_support/json/backends/jsongem.rb | 21 ++++++++++++--------- activesupport/test/multibyte_chars_test.rb | 6 +++--- 6 files changed, 23 insertions(+), 17 deletions(-) diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index b91ae65e9f..2f714c62ee 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -43,7 +43,8 @@ module ActiveSupport # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new) # # => returns MyOwnCacheStore.new def self.lookup_store(*store_option) - store, *parameters = *([ store_option ].flatten) + store = store_option.shift + parameters = store_option case store when Symbol diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index 190173f8a0..35ccec5df4 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -1,4 +1,5 @@ require 'active_support/time' +require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/hash/reverse_merge' class Hash @@ -138,7 +139,7 @@ class Hash case value.class.to_s when 'Hash' if value['type'] == 'array' - child_key, entries = value.detect { |k,v| k != 'type' } # child_key is throwaway + child_key, entries = Array.wrap(value.detect { |k,v| k != 'type' }) # child_key is throwaway if entries.nil? || (c = value['__content__'] && c.blank?) [] else diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 7f6f012721..e858bcdc80 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -339,7 +339,7 @@ module ActiveSupport #:nodoc: next end [ nesting_camel ] - end.flatten.compact.uniq + end.compact.flatten.compact.uniq end # Search for a file in load_paths matching the provided suffix. diff --git a/activesupport/lib/active_support/deprecated_callbacks.rb b/activesupport/lib/active_support/deprecated_callbacks.rb index 20fb03cbeb..f56fef0b6d 100644 --- a/activesupport/lib/active_support/deprecated_callbacks.rb +++ b/activesupport/lib/active_support/deprecated_callbacks.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/array/extract_options' +require 'active_support/core_ext/array/wrap' module ActiveSupport # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic @@ -194,8 +195,8 @@ module ActiveSupport end def should_run_callback?(*args) - [options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } && - ![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) } + Array.wrap(options[:if]).flatten.compact.all? { |a| evaluate_method(a, *args) } && + !Array.wrap(options[:unless]).flatten.compact.any? { |a| evaluate_method(a, *args) } end end diff --git a/activesupport/lib/active_support/json/backends/jsongem.rb b/activesupport/lib/active_support/json/backends/jsongem.rb index c6c17a3c4e..cfe28d7bb9 100644 --- a/activesupport/lib/active_support/json/backends/jsongem.rb +++ b/activesupport/lib/active_support/json/backends/jsongem.rb @@ -23,15 +23,18 @@ module ActiveSupport 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 + when nil + nil + 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 diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 4ff74abf61..9245263270 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -228,8 +228,8 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase assert !@chars.include?('a') end - def test_include_raises_type_error_when_nil_is_passed - assert_raise(TypeError) do + def test_include_raises_when_nil_is_passed + assert_raise(RUBY_VERSION >= '1.9.2' ? NoMethodError : TypeError) do @chars.include?(nil) end end @@ -659,4 +659,4 @@ class MultibyteInternalsTest < ActiveSupport::TestCase "Expected byte offset #{byte_offset} to translate to #{character_offset}" end end -end \ No newline at end of file +end -- cgit v1.2.3 From deddd55086ad3e9ae43bb0fa44911a77c8ee4495 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 22:01:50 -0800 Subject: Work around assert_raise limitation --- activesupport/test/multibyte_chars_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 9245263270..0e489c10e1 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -229,9 +229,9 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase end def test_include_raises_when_nil_is_passed - assert_raise(RUBY_VERSION >= '1.9.2' ? NoMethodError : TypeError) do - @chars.include?(nil) - end + @chars.include?(nil) + flunk "Expected chars.include?(nil) to raise TypeError or NoMethodError" + rescue Exception => e end def test_index_should_return_character_offset -- cgit v1.2.3 From 8e32830412c051d97613ea4b84c0d8b64e612538 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 22:31:54 -0800 Subject: Fix unresolved string extension dependencies --- activesupport/lib/active_support/multibyte/chars.rb | 5 +++-- activesupport/lib/active_support/values/time_zone.rb | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index d372b0ab1f..c7225fec06 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/access' require 'active_support/core_ext/string/behavior' module ActiveSupport #:nodoc: @@ -197,7 +198,7 @@ module ActiveSupport #:nodoc: # 'Café périferôl'.mb_chars.index('ô') #=> 12 # 'Café périferôl'.mb_chars.index(/\w/u) #=> 0 def index(needle, offset=0) - wrapped_offset = self.first(offset).wrapped_string.length + wrapped_offset = first(offset).wrapped_string.length index = @wrapped_string.index(needle, wrapped_offset) index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil end @@ -211,7 +212,7 @@ module ActiveSupport #:nodoc: # 'Café périferôl'.mb_chars.rindex(/\w/u) #=> 13 def rindex(needle, offset=nil) offset ||= length - wrapped_offset = self.first(offset).wrapped_string.length + wrapped_offset = first(offset).wrapped_string.length index = @wrapped_string.rindex(needle, wrapped_offset) index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil end diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index 53a4c7acf5..e7583bef1b 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -1,3 +1,4 @@ +require 'active_support/core_ext/object/blank' require 'active_support/core_ext/time' require 'active_support/core_ext/date' require 'active_support/core_ext/date_time' -- cgit v1.2.3 From b1164adda12268b38bba9b0d81c0d26b7251b8bb Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 8 Nov 2009 23:29:33 -0800 Subject: Fix arg destructure --- activesupport/lib/active_support/cache.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 2f714c62ee..f2d957f154 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -1,4 +1,5 @@ require 'benchmark' +require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/benchmark' require 'active_support/core_ext/exception' require 'active_support/core_ext/class/attribute_accessors' @@ -43,8 +44,7 @@ module ActiveSupport # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new) # # => returns MyOwnCacheStore.new def self.lookup_store(*store_option) - store = store_option.shift - parameters = store_option + store, *parameters = *Array.wrap(store_option).flatten case store when Symbol -- cgit v1.2.3 From ee0d41c38d06802bec420d4e0948249146c92cd9 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 03:18:54 -0800 Subject: Remove string access core extension dependency --- activesupport/lib/active_support/inflector/inflections.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb index 24ce58e5c2..785e245ea4 100644 --- a/activesupport/lib/active_support/inflector/inflections.rb +++ b/activesupport/lib/active_support/inflector/inflections.rb @@ -1,5 +1,3 @@ -# require "active_support/core_ext/string/access" - module ActiveSupport module Inflector # A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional @@ -210,4 +208,4 @@ module ActiveSupport camelize(singularize(table_name.to_s.sub(/.*\./, ''))) end end -end \ No newline at end of file +end -- cgit v1.2.3 From a038b3d1bc20ba225bf8a7672478300f60a41e77 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 03:31:59 -0800 Subject: Make Rakefile usable outside of base dir --- activemodel/Rakefile | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/activemodel/Rakefile b/activemodel/Rakefile index 8897987518..a63e1982b9 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -1,4 +1,5 @@ -require File.join(File.dirname(__FILE__), 'lib', 'active_model', 'version') +dir = File.dirname(__FILE__) +require "#{dir}/lib/active_model/version" PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' PKG_NAME = 'activemodel' @@ -12,16 +13,16 @@ require 'rake/testtask' task :default => :test Rake::TestTask.new do |t| - t.libs << "test" - t.test_files = Dir.glob("test/cases/**/*_test.rb").sort + t.libs << "#{dir}/test" + t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort t.verbose = true t.warning = true end task :isolated_test do ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - Dir.glob("test/**/*_test.rb").all? do |file| - system(ruby, '-w', '-Ilib:test', file) + Dir.glob("#{dir}/test/**/*_test.rb").all? do |file| + system(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file) end or raise "Failures" end @@ -30,20 +31,20 @@ require 'rake/rdoctask' # Generate the RDoc documentation Rake::RDocTask.new do |rdoc| - rdoc.rdoc_dir = 'doc' + rdoc.rdoc_dir = "#{dir}/doc" rdoc.title = "Active Model" rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' rdoc.options << '--charset' << 'utf-8' rdoc.template = ENV['template'] ? "#{ENV['template']}.rb" : '../doc/template/horo' - rdoc.rdoc_files.include('README', 'CHANGES') - rdoc.rdoc_files.include('lib/**/*.rb') + rdoc.rdoc_files.include("#{dir}/README", "#{dir}/CHANGES") + rdoc.rdoc_files.include("#{dir}/lib/**/*.rb") end require 'rake/packagetask' require 'rake/gempackagetask' -spec = eval(File.read('activemodel.gemspec')) +spec = eval(File.read("#{dir}/activemodel.gemspec")) Rake::GemPackageTask.new(spec) do |p| p.gem_spec = spec -- cgit v1.2.3 From 7f0fcadd3650eaee5bd6a8ab8032ed3c5627385b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 04:05:22 -0800 Subject: Revert "Ruby 1.9.2: avoid Array#to_s and Array(nil)" This reverts commit 7ad461b44dabb586fbad190493ac4ecd96104597. --- .../lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb index 7487b96b8c..1b49debc05 100755 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb @@ -195,19 +195,10 @@ module I18n # Merges the given locale, key and scope into a single array of keys. # Splits keys that contain dots into multiple keys. Makes sure all # keys are Symbols. - def normalize_translation_keys(*keys) - normalized = [] - keys.each do |key| - case key - when Array - normalized.concat normalize_translation_keys(*key) - when nil - # skip - else - normalized.concat key.to_s.split('.').map { |sub| sub.to_sym } - end - end - normalized + def normalize_translation_keys(locale, key, scope) + keys = [locale] + Array(scope) + [key] + keys = keys.map { |k| k.to_s.split(/\./) } + keys.flatten.map { |k| k.to_sym } end end end -- cgit v1.2.3 From 6d808cf494e0434c814c0be9594020ad6f00ef18 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 04:59:26 -0800 Subject: Remove reliance on string access core extension --- activeresource/lib/active_resource/base.rb | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index bd2abdd38e..bfe4208d98 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -1152,15 +1152,16 @@ module ActiveResource def respond_to?(method, include_priv = false) method_name = method.to_s if attributes.nil? - return super + super elsif attributes.has_key?(method_name) - return true - elsif ['?','='].include?(method_name.last) && attributes.has_key?(method_name.first(-1)) - return true + true + elsif method_name =~ /(?:=|\?)$/ && attributes.include?($`) + true + else + # super must be called at the end of the method, because the inherited respond_to? + # would return true for generated readers, even if the attribute wasn't present + super end - # super must be called at the end of the method, because the inherited respond_to? - # would return true for generated readers, even if the attribute wasn't present - super end protected @@ -1249,13 +1250,15 @@ module ActiveResource def method_missing(method_symbol, *arguments) #:nodoc: method_name = method_symbol.to_s - case method_name.last + if method_name =~ /(=|\?)$/ + case $1 when "=" - attributes[method_name.first(-1)] = arguments.first + attributes[$`] = arguments.first when "?" - attributes[method_name.first(-1)] - else - attributes.has_key?(method_name) ? attributes[method_name] : super + attributes[$`] + end + else + attributes.include?(method_name) ? attributes[method_name] : super end end end -- cgit v1.2.3 From 76b2d3e33730fce9680d0b6e97df12b1744fb23d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 05:07:58 -0800 Subject: Ruby 1.9.2: URI.parse and .decode are deprecated --- activeresource/lib/active_resource/base.rb | 12 ++++++++---- activeresource/lib/active_resource/connection.rb | 9 +++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index bfe4208d98..18105e8887 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -274,8 +274,8 @@ module ActiveResource @site = nil else @site = create_site_uri_from(site) - @user = URI.decode(@site.user) if @site.user - @password = URI.decode(@site.password) if @site.password + @user = uri_parser.unescape(@site.user) if @site.user + @password = uri_parser.unescape(@site.password) if @site.password end end @@ -737,12 +737,12 @@ module ActiveResource # Accepts a URI and creates the site URI from that. def create_site_uri_from(site) - site.is_a?(URI) ? site.dup : URI.parse(site) + site.is_a?(URI) ? site.dup : uri_parser.parse(site) end # Accepts a URI and creates the proxy URI from that. def create_proxy_uri_from(proxy) - proxy.is_a?(URI) ? proxy.dup : URI.parse(proxy) + proxy.is_a?(URI) ? proxy.dup : uri_parser.parse(proxy) end # contains a set of the current prefix parameters. @@ -767,6 +767,10 @@ module ActiveResource [ prefix_options, query_options ] end + + def uri_parser + @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI + end end attr_accessor :attributes #:nodoc: diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index 98cb1a932b..193be89a82 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -31,20 +31,21 @@ module ActiveResource def initialize(site, format = ActiveResource::Formats::XmlFormat) raise ArgumentError, 'Missing site URI' unless site @user = @password = nil + @uri_parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI self.site = site self.format = format end # Set URI for remote service. def site=(site) - @site = site.is_a?(URI) ? site : URI.parse(site) - @user = URI.decode(@site.user) if @site.user - @password = URI.decode(@site.password) if @site.password + @site = site.is_a?(URI) ? site : @uri_parser.parse(site) + @user = @uri_parser.unescape(@site.user) if @site.user + @password = @uri_parser.unescape(@site.password) if @site.password end # Set the proxy for remote service. def proxy=(proxy) - @proxy = proxy.is_a?(URI) ? proxy : URI.parse(proxy) + @proxy = proxy.is_a?(URI) ? proxy : @uri_parser.parse(proxy) end # Sets the user for remote service. -- cgit v1.2.3 From 303991288633effea5a1d1774dbd861951303fe5 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 05:09:04 -0800 Subject: Silence spurious warning --- activesupport/lib/active_support/notifications.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 9eae3bebe2..6304f496f5 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -111,7 +111,7 @@ module ActiveSupport def subscribe @queue.subscribe(@pattern) do |*args| - yield *args + yield(*args) end end end -- cgit v1.2.3 From 83f329f5f30567a10bc96410da230bf986db8ad4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 9 Nov 2009 16:19:47 -0200 Subject: Bundle I18n 0.2.0. --- Gemfile | 5 +- .../core_ext/string/interpolation.rb | 2 +- activesupport/lib/active_support/vendor.rb | 2 +- .../active_support/vendor/i18n-0.1.3/MIT-LICENSE | 20 - .../vendor/i18n-0.1.3/README.textile | 20 - .../lib/active_support/vendor/i18n-0.1.3/Rakefile | 5 - .../active_support/vendor/i18n-0.1.3/i18n.gemspec | 27 - .../active_support/vendor/i18n-0.1.3/lib/i18n.rb | 204 -------- .../vendor/i18n-0.1.3/lib/i18n/backend/simple.rb | 215 -------- .../vendor/i18n-0.1.3/lib/i18n/exceptions.rb | 53 -- .../active_support/vendor/i18n-0.1.3/test/all.rb | 5 - .../vendor/i18n-0.1.3/test/i18n_exceptions_test.rb | 99 ---- .../vendor/i18n-0.1.3/test/i18n_test.rb | 124 ----- .../vendor/i18n-0.1.3/test/locale/en.rb | 1 - .../vendor/i18n-0.1.3/test/locale/en.yml | 3 - .../vendor/i18n-0.1.3/test/simple_backend_test.rb | 567 --------------------- 16 files changed, 5 insertions(+), 1347 deletions(-) delete mode 100755 activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec delete mode 100755 activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml delete mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb diff --git a/Gemfile b/Gemfile index a60c1010d9..85a1ee0fef 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,7 @@ clear_sources source 'http://gemcutter.org' -gem "rails", "3.0.pre", :vendored_at => "railties" +gem "rails", "3.0.pre", :path => "railties" %w( activesupport activemodel @@ -10,8 +10,9 @@ gem "rails", "3.0.pre", :vendored_at => "railties" activerecord activeresource ).each do |lib| - gem lib, '3.0.pre', :vendored_at => lib + gem lib, '3.0.pre', :path => lib end +gem "i18n", "0.2.0" gem "rack", "1.0.1" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", "~> 0.5.0" diff --git a/activesupport/lib/active_support/core_ext/string/interpolation.rb b/activesupport/lib/active_support/core_ext/string/interpolation.rb index d9159b690a..c4a5c0ca35 100644 --- a/activesupport/lib/active_support/core_ext/string/interpolation.rb +++ b/activesupport/lib/active_support/core_ext/string/interpolation.rb @@ -5,7 +5,7 @@ You may redistribute it and/or modify it under the same license terms as Ruby. =end -if RUBY_VERSION < '1.9' +if RUBY_VERSION < '1.9' && !"".respond_to?(:interpolate_without_ruby_19_syntax) require 'active_support/core_ext/string/bytesize' # KeyError is raised by String#% when the string contains a named placeholder diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb index 4a711b7e25..15898d153c 100644 --- a/activesupport/lib/active_support/vendor.rb +++ b/activesupport/lib/active_support/vendor.rb @@ -4,7 +4,7 @@ def ActiveSupport.requirable?(file) $LOAD_PATH.any? { |p| Dir.glob("#{p}/#{file}.*").any? } end -[%w(builder 2.1.2), %w(i18n 0.1.3), %w(memcache-client 1.7.5), %w(tzinfo 0.3.15)].each do |lib, version| +[%w(builder 2.1.2), %w(memcache-client 1.7.5), %w(tzinfo 0.3.15)].each do |lib, version| # If the lib is not already requirable unless ActiveSupport.requirable? lib # Try to activate a gem ~> satisfying the requested version first. diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE b/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE deleted file mode 100755 index ed8e9ee66d..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008 The Ruby I18n team - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile b/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile deleted file mode 100644 index a07fc8426d..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile +++ /dev/null @@ -1,20 +0,0 @@ -h1. Ruby I18n gem - -I18n and localization solution for Ruby. - -For information please refer to http://rails-i18n.org - -h2. Authors - -* "Matt Aimonetti":http://railsontherun.com -* "Sven Fuchs":http://www.artweb-design.de -* "Joshua Harvey":http://www.workingwithrails.com/person/759-joshua-harvey -* "Saimon Moore":http://saimonmoore.net -* "Stephan Soller":http://www.arkanis-development.de - -h2. License - -MIT License. See the included MIT-LICENCE file. - - - diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile b/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile deleted file mode 100644 index 2164e13e69..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile +++ /dev/null @@ -1,5 +0,0 @@ -task :default => [:test] - -task :test do - ruby "test/all.rb" -end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec b/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec deleted file mode 100644 index f102689a6f..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec +++ /dev/null @@ -1,27 +0,0 @@ -Gem::Specification.new do |s| - s.name = "i18n" - s.version = "0.1.3" - s.date = "2009-01-09" - s.summary = "Internationalization support for Ruby" - s.email = "rails-i18n@googlegroups.com" - s.homepage = "http://rails-i18n.org" - s.description = "Add Internationalization support to your Ruby application." - s.has_rdoc = false - s.authors = ['Sven Fuchs', 'Joshua Harvey', 'Matt Aimonetti', 'Stephan Soller', 'Saimon Moore'] - s.files = [ - 'i18n.gemspec', - 'lib/i18n/backend/simple.rb', - 'lib/i18n/exceptions.rb', - 'lib/i18n.rb', - 'MIT-LICENSE', - 'README.textile' - ] - s.test_files = [ - 'test/all.rb', - 'test/i18n_exceptions_test.rb', - 'test/i18n_test.rb', - 'test/locale/en.rb', - 'test/locale/en.yml', - 'test/simple_backend_test.rb' - ] -end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb deleted file mode 100755 index 1b49debc05..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb +++ /dev/null @@ -1,204 +0,0 @@ -#-- -# Authors:: Matt Aimonetti (http://railsontherun.com/), -# Sven Fuchs (http://www.artweb-design.de), -# Joshua Harvey (http://www.workingwithrails.com/person/759-joshua-harvey), -# Saimon Moore (http://saimonmoore.net), -# Stephan Soller (http://www.arkanis-development.de/) -# Copyright:: Copyright (c) 2008 The Ruby i18n Team -# License:: MIT -#++ - -module I18n - autoload :ArgumentError, 'i18n/exceptions' - module Backend - autoload :Simple, 'i18n/backend/simple' - end - - @@backend = nil - @@load_path = nil - @@default_locale = :'en' - @@exception_handler = :default_exception_handler - - class << self - # Returns the current backend. Defaults to +Backend::Simple+. - def backend - @@backend ||= Backend::Simple.new - end - - # Sets the current backend. Used to set a custom backend. - def backend=(backend) - @@backend = backend - end - - # Returns the current default locale. Defaults to :'en' - def default_locale - @@default_locale - end - - # Sets the current default locale. Used to set a custom default locale. - def default_locale=(locale) - @@default_locale = locale - end - - # Returns the current locale. Defaults to I18n.default_locale. - def locale - Thread.current[:locale] ||= default_locale - end - - # Sets the current locale pseudo-globally, i.e. in the Thread.current hash. - def locale=(locale) - Thread.current[:locale] = locale - end - - # Returns an array of locales for which translations are available - def available_locales - backend.available_locales - end - - # Sets the exception handler. - def exception_handler=(exception_handler) - @@exception_handler = exception_handler - end - - # Allow clients to register paths providing translation data sources. The - # backend defines acceptable sources. - # - # E.g. the provided SimpleBackend accepts a list of paths to translation - # files which are either named *.rb and contain plain Ruby Hashes or are - # named *.yml and contain YAML data. So for the SimpleBackend clients may - # register translation files like this: - # I18n.load_path << 'path/to/locale/en.yml' - def load_path - @@load_path ||= [] - end - - # Sets the load path instance. Custom implementations are expected to - # behave like a Ruby Array. - def load_path=(load_path) - @@load_path = load_path - end - - # Tells the backend to reload translations. Used in situations like the - # Rails development environment. Backends can implement whatever strategy - # is useful. - def reload! - backend.reload! - end - - # Translates, pluralizes and interpolates a given key using a given locale, - # scope, and default, as well as interpolation values. - # - # *LOOKUP* - # - # Translation data is organized as a nested hash using the upper-level keys - # as namespaces. E.g., ActionView ships with the translation: - # :date => {:formats => {:short => "%b %d"}}. - # - # Translations can be looked up at any level of this hash using the key argument - # and the scope option. E.g., in this example I18n.t :date - # returns the whole translations hash {:formats => {:short => "%b %d"}}. - # - # Key can be either a single key or a dot-separated key (both Strings and Symbols - # work). E.g., the short format can be looked up using both: - # I18n.t 'date.formats.short' - # I18n.t :'date.formats.short' - # - # Scope can be either a single key, a dot-separated key or an array of keys - # or dot-separated keys. Keys and scopes can be combined freely. So these - # examples will all look up the same short date format: - # I18n.t 'date.formats.short' - # I18n.t 'formats.short', :scope => 'date' - # I18n.t 'short', :scope => 'date.formats' - # I18n.t 'short', :scope => %w(date formats) - # - # *INTERPOLATION* - # - # Translations can contain interpolation variables which will be replaced by - # values passed to #translate as part of the options hash, with the keys matching - # the interpolation variable names. - # - # E.g., with a translation :foo => "foo {{bar}}" the option - # value for the key +bar+ will be interpolated into the translation: - # I18n.t :foo, :bar => 'baz' # => 'foo baz' - # - # *PLURALIZATION* - # - # Translation data can contain pluralized translations. Pluralized translations - # are arrays of singluar/plural versions of translations like ['Foo', 'Foos']. - # - # Note that I18n::Backend::Simple only supports an algorithm for English - # pluralization rules. Other algorithms can be supported by custom backends. - # - # This returns the singular version of a pluralized translation: - # I18n.t :foo, :count => 1 # => 'Foo' - # - # These both return the plural version of a pluralized translation: - # I18n.t :foo, :count => 0 # => 'Foos' - # I18n.t :foo, :count => 2 # => 'Foos' - # - # The :count option can be used both for pluralization and interpolation. - # E.g., with the translation - # :foo => ['{{count}} foo', '{{count}} foos'], count will - # be interpolated to the pluralized translation: - # I18n.t :foo, :count => 1 # => '1 foo' - # - # *DEFAULTS* - # - # This returns the translation for :foo or default if no translation was found: - # I18n.t :foo, :default => 'default' - # - # This returns the translation for :foo or the translation for :bar if no - # translation for :foo was found: - # I18n.t :foo, :default => :bar - # - # Returns the translation for :foo or the translation for :bar - # or default if no translations for :foo and :bar were found. - # I18n.t :foo, :default => [:bar, 'default'] - # - # BULK LOOKUP - # - # This returns an array with the translations for :foo and :bar. - # I18n.t [:foo, :bar] - # - # Can be used with dot-separated nested keys: - # I18n.t [:'baz.foo', :'baz.bar'] - # - # Which is the same as using a scope option: - # I18n.t [:foo, :bar], :scope => :baz - def translate(key, options = {}) - locale = options.delete(:locale) || I18n.locale - backend.translate(locale, key, options) - rescue I18n::ArgumentError => e - raise e if options[:raise] - send(@@exception_handler, e, locale, key, options) - end - alias :t :translate - - # Localizes certain objects, such as dates and numbers to local formatting. - def localize(object, options = {}) - locale = options[:locale] || I18n.locale - format = options[:format] || :default - backend.localize(locale, object, format) - end - alias :l :localize - - protected - # Handles exceptions raised in the backend. All exceptions except for - # MissingTranslationData exceptions are re-raised. When a MissingTranslationData - # was caught and the option :raise is not set the handler returns an error - # message string containing the key/scope. - def default_exception_handler(exception, locale, key, options) - return exception.message if MissingTranslationData === exception - raise exception - end - - # Merges the given locale, key and scope into a single array of keys. - # Splits keys that contain dots into multiple keys. Makes sure all - # keys are Symbols. - def normalize_translation_keys(locale, key, scope) - keys = [locale] + Array(scope) + [key] - keys = keys.map { |k| k.to_s.split(/\./) } - keys.flatten.map { |k| k.to_sym } - end - end -end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb deleted file mode 100644 index c32cc76f34..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb +++ /dev/null @@ -1,215 +0,0 @@ -require 'i18n/exceptions' - -module I18n - module Backend - class Simple - INTERPOLATION_RESERVED_KEYS = %w(scope default) - MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ - - # Accepts a list of paths to translation files. Loads translations from - # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml - # for details. - def load_translations(*filenames) - filenames.each { |filename| load_file(filename) } - end - - # Stores translations for the given locale in memory. - # This uses a deep merge for the translations hash, so existing - # translations will be overwritten by new ones only at the deepest - # level of the hash. - def store_translations(locale, data) - merge_translations(locale, data) - end - - def translate(locale, key, options = {}) - raise InvalidLocale.new(locale) if locale.nil? - return key.map { |k| translate(locale, k, options) } if key.is_a? Array - - reserved = :scope, :default - count, scope, default = options.values_at(:count, *reserved) - options.delete(:default) - values = options.reject { |name, value| reserved.include?(name) } - - entry = lookup(locale, key, scope) - if entry.nil? - entry = default(locale, default, options) - if entry.nil? - raise(I18n::MissingTranslationData.new(locale, key, options)) - end - end - entry = pluralize(locale, entry, count) - entry = interpolate(locale, entry, values) - entry - end - - # Acts the same as +strftime+, but returns a localized version of the - # formatted date string. Takes a key from the date/time formats - # translations as a format argument (e.g., :short in :'date.formats'). - def localize(locale, object, format = :default) - raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) - - type = object.respond_to?(:sec) ? 'time' : 'date' - # TODO only translate these if format is a String? - formats = translate(locale, :"#{type}.formats") - format = formats[format.to_sym] if formats && formats[format.to_sym] - # TODO raise exception unless format found? - format = format.to_s.dup - - # TODO only translate these if the format string is actually present - # TODO check which format strings are present, then bulk translate then, then replace them - format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday]) - format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday]) - format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon]) - format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon]) - format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour - object.strftime(format) - end - - def initialized? - @initialized ||= false - end - - # Returns an array of locales for which translations are available - def available_locales - init_translations unless initialized? - translations.keys - end - - def reload! - @initialized = false - @translations = nil - end - - protected - def init_translations - load_translations(*I18n.load_path.flatten) - @initialized = true - end - - def translations - @translations ||= {} - end - - # Looks up a translation from the translations hash. Returns nil if - # eiher key is nil, or locale, scope or key do not exist as a key in the - # nested translations hash. Splits keys or scopes containing dots - # into multiple keys, i.e. currency.format is regarded the same as - # %w(currency format). - def lookup(locale, key, scope = []) - return unless key - init_translations unless initialized? - keys = I18n.send(:normalize_translation_keys, locale, key, scope) - keys.inject(translations) do |result, k| - if (x = result[k.to_sym]).nil? - return nil - else - x - end - end - end - - # Evaluates a default translation. - # If the given default is a String it is used literally. If it is a Symbol - # it will be translated with the given options. If it is an Array the first - # translation yielded will be returned. - # - # I.e., default(locale, [:foo, 'default']) will return +default+ if - # translate(locale, :foo) does not yield a result. - def default(locale, default, options = {}) - case default - when String then default - when Symbol then translate locale, default, options - when Array then default.each do |obj| - result = default(locale, obj, options.dup) and return result - end and nil - end - rescue MissingTranslationData - nil - end - - # Picks a translation from an array according to English pluralization - # rules. It will pick the first translation if count is not equal to 1 - # and the second translation if it is equal to 1. Other backends can - # implement more flexible or complex pluralization rules. - def pluralize(locale, entry, count) - return entry unless entry.is_a?(Hash) and count - # raise InvalidPluralizationData.new(entry, count) unless entry.is_a?(Hash) - key = :zero if count == 0 && entry.has_key?(:zero) - key ||= count == 1 ? :one : :other - raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key) - entry[key] - end - - # Interpolates values into a given string. - # - # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X' - # # => "file test.txt opened by {{user}}" - # - # Note that you have to double escape the \\ when you want to escape - # the {{...}} key in a string (once for the string and once for the - # interpolation). - def interpolate(locale, string, values = {}) - return string unless string.is_a?(String) - - string.gsub(MATCH) do - escaped, pattern, key = $1, $2, $2.to_sym - - if escaped - pattern - elsif INTERPOLATION_RESERVED_KEYS.include?(pattern) - raise ReservedInterpolationKey.new(pattern, string) - elsif !values.include?(key) - raise MissingInterpolationArgument.new(pattern, string) - else - values[key].to_s - end - end - end - - # Loads a single translations file by delegating to #load_rb or - # #load_yml depending on the file extension and directly merges the - # data to the existing translations. Raises I18n::UnknownFileType - # for all other file extensions. - def load_file(filename) - type = File.extname(filename).tr('.', '').downcase - raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}") - data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash - data.each { |locale, d| merge_translations(locale, d) } - end - - # Loads a plain Ruby translations file. eval'ing the file must yield - # a Hash containing translation data with locales as toplevel keys. - def load_rb(filename) - eval(IO.read(filename), binding, filename) - end - - # Loads a YAML translations file. The data must have locales as - # toplevel keys. - def load_yml(filename) - require 'yaml' unless defined? :YAML - YAML::load(IO.read(filename)) - end - - # Deep merges the given translations hash with the existing translations - # for the given locale - def merge_translations(locale, data) - locale = locale.to_sym - translations[locale] ||= {} - data = deep_symbolize_keys(data) - - # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 - merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } - translations[locale].merge!(data, &merger) - end - - # Return a new hash with all keys and nested keys converted to symbols. - def deep_symbolize_keys(hash) - hash.inject({}) { |result, (key, value)| - value = deep_symbolize_keys(value) if value.is_a? Hash - result[(key.to_sym rescue key) || key] = value - result - } - end - end - end -end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb deleted file mode 100644 index 6897055d6d..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb +++ /dev/null @@ -1,53 +0,0 @@ -module I18n - class ArgumentError < ::ArgumentError; end - - class InvalidLocale < ArgumentError - attr_reader :locale - def initialize(locale) - @locale = locale - super "#{locale.inspect} is not a valid locale" - end - end - - class MissingTranslationData < ArgumentError - attr_reader :locale, :key, :options - def initialize(locale, key, options) - @key, @locale, @options = key, locale, options - keys = I18n.send(:normalize_translation_keys, locale, key, options[:scope]) - keys << 'no key' if keys.size < 2 - super "translation missing: #{keys.join(', ')}" - end - end - - class InvalidPluralizationData < ArgumentError - attr_reader :entry, :count - def initialize(entry, count) - @entry, @count = entry, count - super "translation data #{entry.inspect} can not be used with :count => #{count}" - end - end - - class MissingInterpolationArgument < ArgumentError - attr_reader :key, :string - def initialize(key, string) - @key, @string = key, string - super "interpolation argument #{key} missing in #{string.inspect}" - end - end - - class ReservedInterpolationKey < ArgumentError - attr_reader :key, :string - def initialize(key, string) - @key, @string = key, string - super "reserved key #{key.inspect} used in #{string.inspect}" - end - end - - class UnknownFileType < ArgumentError - attr_reader :type, :filename - def initialize(type, filename) - @type, @filename = type, filename - super "can not load translations from #{filename}, the file type #{type} is not known" - end - end -end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb deleted file mode 100644 index 353712da49..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb +++ /dev/null @@ -1,5 +0,0 @@ -dir = File.dirname(__FILE__) -require dir + '/i18n_test.rb' -require dir + '/simple_backend_test.rb' -require dir + '/i18n_exceptions_test.rb' -# *require* dir + '/custom_backend_test.rb' \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb deleted file mode 100644 index 4e78e71b34..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb +++ /dev/null @@ -1,99 +0,0 @@ -$:.unshift "lib" - -require 'rubygems' -require 'test/unit' -require 'i18n' -require 'active_support' - -class I18nExceptionsTest < Test::Unit::TestCase - def test_invalid_locale_stores_locale - force_invalid_locale - rescue I18n::ArgumentError => e - assert_nil e.locale - end - - def test_invalid_locale_message - force_invalid_locale - rescue I18n::ArgumentError => e - assert_equal 'nil is not a valid locale', e.message - end - - def test_missing_translation_data_stores_locale_key_and_options - force_missing_translation_data - rescue I18n::ArgumentError => e - options = {:scope => :bar} - assert_equal 'de', e.locale - assert_equal :foo, e.key - assert_equal options, e.options - end - - def test_missing_translation_data_message - force_missing_translation_data - rescue I18n::ArgumentError => e - assert_equal 'translation missing: de, bar, foo', e.message - end - - def test_invalid_pluralization_data_stores_entry_and_count - force_invalid_pluralization_data - rescue I18n::ArgumentError => e - assert_equal [:bar], e.entry - assert_equal 1, e.count - end - - def test_invalid_pluralization_data_message - force_invalid_pluralization_data - rescue I18n::ArgumentError => e - assert_equal 'translation data [:bar] can not be used with :count => 1', e.message - end - - def test_missing_interpolation_argument_stores_key_and_string - force_missing_interpolation_argument - rescue I18n::ArgumentError => e - assert_equal 'bar', e.key - assert_equal "{{bar}}", e.string - end - - def test_missing_interpolation_argument_message - force_missing_interpolation_argument - rescue I18n::ArgumentError => e - assert_equal 'interpolation argument bar missing in "{{bar}}"', e.message - end - - def test_reserved_interpolation_key_stores_key_and_string - force_reserved_interpolation_key - rescue I18n::ArgumentError => e - assert_equal 'scope', e.key - assert_equal "{{scope}}", e.string - end - - def test_reserved_interpolation_key_message - force_reserved_interpolation_key - rescue I18n::ArgumentError => e - assert_equal 'reserved key "scope" used in "{{scope}}"', e.message - end - - private - def force_invalid_locale - I18n.backend.translate nil, :foo - end - - def force_missing_translation_data - I18n.backend.store_translations 'de', :bar => nil - I18n.backend.translate 'de', :foo, :scope => :bar - end - - def force_invalid_pluralization_data - I18n.backend.store_translations 'de', :foo => [:bar] - I18n.backend.translate 'de', :foo, :count => 1 - end - - def force_missing_interpolation_argument - I18n.backend.store_translations 'de', :foo => "{{bar}}" - I18n.backend.translate 'de', :foo, :baz => 'baz' - end - - def force_reserved_interpolation_key - I18n.backend.store_translations 'de', :foo => "{{scope}}" - I18n.backend.translate 'de', :foo, :baz => 'baz' - end -end \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb deleted file mode 100644 index 2835ec4eab..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb +++ /dev/null @@ -1,124 +0,0 @@ -$:.unshift "lib" - -require 'rubygems' -require 'test/unit' -require 'i18n' -require 'active_support' - -class I18nTest < Test::Unit::TestCase - def setup - I18n.backend.store_translations :'en', { - :currency => { - :format => { - :separator => '.', - :delimiter => ',', - } - } - } - end - - def test_uses_simple_backend_set_by_default - assert I18n.backend.is_a?(I18n::Backend::Simple) - end - - def test_can_set_backend - assert_nothing_raised{ I18n.backend = self } - assert_equal self, I18n.backend - I18n.backend = I18n::Backend::Simple.new - end - - def test_uses_en_us_as_default_locale_by_default - assert_equal 'en', I18n.default_locale - end - - def test_can_set_default_locale - assert_nothing_raised{ I18n.default_locale = 'de' } - assert_equal 'de', I18n.default_locale - I18n.default_locale = 'en' - end - - def test_uses_default_locale_as_locale_by_default - assert_equal I18n.default_locale, I18n.locale - end - - def test_can_set_locale_to_thread_current - assert_nothing_raised{ I18n.locale = 'de' } - assert_equal 'de', I18n.locale - assert_equal 'de', Thread.current[:locale] - I18n.locale = 'en' - end - - def test_can_set_exception_handler - assert_nothing_raised{ I18n.exception_handler = :custom_exception_handler } - I18n.exception_handler = :default_exception_handler # revert it - end - - def test_uses_custom_exception_handler - I18n.exception_handler = :custom_exception_handler - I18n.expects(:custom_exception_handler) - I18n.translate :bogus - I18n.exception_handler = :default_exception_handler # revert it - end - - def test_delegates_translate_to_backend - I18n.backend.expects(:translate).with 'de', :foo, {} - I18n.translate :foo, :locale => 'de' - end - - def test_delegates_localize_to_backend - I18n.backend.expects(:localize).with 'de', :whatever, :default - I18n.localize :whatever, :locale => 'de' - end - - def test_translate_given_no_locale_uses_i18n_locale - I18n.backend.expects(:translate).with 'en', :foo, {} - I18n.translate :foo - end - - def test_translate_on_nested_symbol_keys_works - assert_equal ".", I18n.t(:'currency.format.separator') - end - - def test_translate_with_nested_string_keys_works - assert_equal ".", I18n.t('currency.format.separator') - end - - def test_translate_with_array_as_scope_works - assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) - end - - def test_translate_with_array_containing_dot_separated_strings_as_scope_works - assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) - end - - def test_translate_with_key_array_and_dot_separated_scope_works - assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format') - end - - def test_translate_with_dot_separated_key_array_and_scope_works - assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency') - end - - def test_translate_with_options_using_scope_works - I18n.backend.expects(:translate).with('de', :precision, :scope => :"currency.format") - I18n.with_options :locale => 'de', :scope => :'currency.format' do |locale| - locale.t :precision - end - end - - # def test_translate_given_no_args_raises_missing_translation_data - # assert_equal "translation missing: en, no key", I18n.t - # end - - def test_translate_given_a_bogus_key_raises_missing_translation_data - assert_equal "translation missing: en, bogus", I18n.t(:bogus) - end - - def test_localize_nil_raises_argument_error - assert_raise(I18n::ArgumentError) { I18n.l nil } - end - - def test_localize_object_raises_argument_error - assert_raise(I18n::ArgumentError) { I18n.l Object.new } - end -end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb deleted file mode 100644 index 6044ce10d9..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb +++ /dev/null @@ -1 +0,0 @@ -{:'en-Ruby' => {:foo => {:bar => "baz"}}} \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml deleted file mode 100644 index 0b298c9c0e..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml +++ /dev/null @@ -1,3 +0,0 @@ -en-Yaml: - foo: - bar: baz \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb deleted file mode 100644 index a1696c77f6..0000000000 --- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb +++ /dev/null @@ -1,567 +0,0 @@ -# encoding: utf-8 -$:.unshift "lib" - -require 'rubygems' -require 'test/unit' -require 'i18n' -require 'time' -require 'yaml' - -module I18nSimpleBackendTestSetup - def setup_backend - # backend_reset_translations! - @backend = I18n::Backend::Simple.new - @backend.store_translations 'en', :foo => {:bar => 'bar', :baz => 'baz'} - @locale_dir = File.dirname(__FILE__) + '/locale' - end - alias :setup :setup_backend - - # def backend_reset_translations! - # I18n::Backend::Simple::ClassMethods.send :class_variable_set, :@@translations, {} - # end - - def backend_get_translations - # I18n::Backend::Simple::ClassMethods.send :class_variable_get, :@@translations - @backend.instance_variable_get :@translations - end - - def add_datetime_translations - @backend.store_translations :'de', { - :date => { - :formats => { - :default => "%d.%m.%Y", - :short => "%d. %b", - :long => "%d. %B %Y", - }, - :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag), - :abbr_day_names => %w(So Mo Di Mi Do Fr Sa), - :month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil), - :abbr_month_names => %w(Jan Feb Mar Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil), - :order => [:day, :month, :year] - }, - :time => { - :formats => { - :default => "%a, %d. %b %Y %H:%M:%S %z", - :short => "%d. %b %H:%M", - :long => "%d. %B %Y %H:%M", - }, - :am => 'am', - :pm => 'pm' - }, - :datetime => { - :distance_in_words => { - :half_a_minute => 'half a minute', - :less_than_x_seconds => { - :one => 'less than 1 second', - :other => 'less than {{count}} seconds' - }, - :x_seconds => { - :one => '1 second', - :other => '{{count}} seconds' - }, - :less_than_x_minutes => { - :one => 'less than a minute', - :other => 'less than {{count}} minutes' - }, - :x_minutes => { - :one => '1 minute', - :other => '{{count}} minutes' - }, - :about_x_hours => { - :one => 'about 1 hour', - :other => 'about {{count}} hours' - }, - :x_days => { - :one => '1 day', - :other => '{{count}} days' - }, - :about_x_months => { - :one => 'about 1 month', - :other => 'about {{count}} months' - }, - :x_months => { - :one => '1 month', - :other => '{{count}} months' - }, - :about_x_years => { - :one => 'about 1 year', - :other => 'about {{count}} year' - }, - :over_x_years => { - :one => 'over 1 year', - :other => 'over {{count}} years' - } - } - } - } - end -end - -class I18nSimpleBackendTranslationsTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_store_translations_adds_translations # no, really :-) - @backend.store_translations :'en', :foo => 'bar' - assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations - end - - def test_store_translations_deep_merges_translations - @backend.store_translations :'en', :foo => {:bar => 'bar'} - @backend.store_translations :'en', :foo => {:baz => 'baz'} - assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations - end - - def test_store_translations_forces_locale_to_sym - @backend.store_translations 'en', :foo => 'bar' - assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations - end - - def test_store_translations_converts_keys_to_symbols - # backend_reset_translations! - @backend.store_translations 'en', 'foo' => {'bar' => 'bar', 'baz' => 'baz'} - assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations - end -end - -class I18nSimpleBackendAvailableLocalesTest < Test::Unit::TestCase - def test_available_locales - @backend = I18n::Backend::Simple.new - @backend.store_translations 'de', :foo => 'bar' - @backend.store_translations 'en', :foo => 'foo' - - assert_equal ['de', 'en'], @backend.available_locales.map{|locale| locale.to_s }.sort - end -end - -class I18nSimpleBackendTranslateTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_translate_calls_lookup_with_locale_given - @backend.expects(:lookup).with('de', :bar, [:foo]).returns 'bar' - @backend.translate 'de', :bar, :scope => [:foo] - end - - def test_given_no_keys_it_returns_the_default - assert_equal 'default', @backend.translate('en', nil, :default => 'default') - end - - def test_translate_given_a_symbol_as_a_default_translates_the_symbol - assert_equal 'bar', @backend.translate('en', nil, :scope => [:foo], :default => :bar) - end - - def test_translate_given_an_array_as_default_uses_the_first_match - assert_equal 'bar', @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :bar]) - end - - def test_translate_given_an_array_of_inexistent_keys_it_raises_missing_translation_data - assert_raise I18n::MissingTranslationData do - @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :does_not_exist_3]) - end - end - - def test_translate_an_array_of_keys_translates_all_of_them - assert_equal %w(bar baz), @backend.translate('en', [:bar, :baz], :scope => [:foo]) - end - - def test_translate_calls_pluralize - @backend.expects(:pluralize).with 'en', 'bar', 1 - @backend.translate 'en', :bar, :scope => [:foo], :count => 1 - end - - def test_translate_calls_interpolate - @backend.expects(:interpolate).with 'en', 'bar', {} - @backend.translate 'en', :bar, :scope => [:foo] - end - - def test_translate_calls_interpolate_including_count_as_a_value - @backend.expects(:interpolate).with 'en', 'bar', {:count => 1} - @backend.translate 'en', :bar, :scope => [:foo], :count => 1 - end - - def test_translate_given_nil_as_a_locale_raises_an_argument_error - assert_raise(I18n::InvalidLocale){ @backend.translate nil, :bar } - end - - def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_data - assert_raise(I18n::MissingTranslationData){ @backend.translate 'de', :bogus } - end -end - -class I18nSimpleBackendLookupTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - # useful because this way we can use the backend with no key for interpolation/pluralization - def test_lookup_given_nil_as_a_key_returns_nil - assert_nil @backend.send(:lookup, 'en', nil) - end - - def test_lookup_given_nested_keys_looks_up_a_nested_hash_value - assert_equal 'bar', @backend.send(:lookup, 'en', :bar, [:foo]) - end -end - -class I18nSimpleBackendPluralizeTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_pluralize_given_nil_returns_the_given_entry - entry = {:one => 'bar', :other => 'bars'} - assert_equal entry, @backend.send(:pluralize, nil, entry, nil) - end - - def test_pluralize_given_0_returns_zero_string_if_zero_key_given - assert_equal 'zero', @backend.send(:pluralize, nil, {:zero => 'zero', :one => 'bar', :other => 'bars'}, 0) - end - - def test_pluralize_given_0_returns_plural_string_if_no_zero_key_given - assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 0) - end - - def test_pluralize_given_1_returns_singular_string - assert_equal 'bar', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 1) - end - - def test_pluralize_given_2_returns_plural_string - assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 2) - end - - def test_pluralize_given_3_returns_plural_string - assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 3) - end - - def test_interpolate_given_incomplete_pluralization_data_raises_invalid_pluralization_data - assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, {:one => 'bar'}, 2) } - end - - # def test_interpolate_given_a_string_raises_invalid_pluralization_data - # assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, 'bar', 2) } - # end - # - # def test_interpolate_given_an_array_raises_invalid_pluralization_data - # assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, ['bar'], 2) } - # end -end - -class I18nSimpleBackendInterpolateTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_interpolate_given_a_value_hash_interpolates_the_values_to_the_string - assert_equal 'Hi David!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'David') - end - - def test_interpolate_given_a_value_hash_interpolates_into_unicode_string - assert_equal 'Häi David!', @backend.send(:interpolate, nil, 'Häi {{name}}!', :name => 'David') - end - - def test_interpolate_given_an_unicode_value_hash_interpolates_to_the_string - assert_equal 'Hi ゆきひろ!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'ゆきひろ') - end - - def test_interpolate_given_an_unicode_value_hash_interpolates_into_unicode_string - assert_equal 'こんにちは、ゆきひろさん!', @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => 'ゆきひろ') - end - - if Kernel.const_defined?(:Encoding) - def test_interpolate_given_a_non_unicode_multibyte_value_hash_interpolates_into_a_string_with_the_same_encoding - assert_equal euc_jp('Hi ゆきひろ!'), @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => euc_jp('ゆきひろ')) - end - - def test_interpolate_given_an_unicode_value_hash_into_a_non_unicode_multibyte_string_raises_encoding_compatibility_error - assert_raise(Encoding::CompatibilityError) do - @backend.send(:interpolate, nil, euc_jp('こんにちは、{{name}}さん!'), :name => 'ゆきひろ') - end - end - - def test_interpolate_given_a_non_unicode_multibyte_value_hash_into_an_unicode_string_raises_encoding_compatibility_error - assert_raise(Encoding::CompatibilityError) do - @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => euc_jp('ゆきひろ')) - end - end - end - - def test_interpolate_given_nil_as_a_string_returns_nil - assert_nil @backend.send(:interpolate, nil, nil, :name => 'David') - end - - def test_interpolate_given_an_non_string_as_a_string_returns_nil - assert_equal [], @backend.send(:interpolate, nil, [], :name => 'David') - end - - def test_interpolate_given_a_values_hash_with_nil_values_interpolates_the_string - assert_equal 'Hi !', @backend.send(:interpolate, nil, 'Hi {{name}}!', {:name => nil}) - end - - def test_interpolate_given_an_empty_values_hash_raises_missing_interpolation_argument - assert_raise(I18n::MissingInterpolationArgument) { @backend.send(:interpolate, nil, 'Hi {{name}}!', {}) } - end - - def test_interpolate_given_a_string_containing_a_reserved_key_raises_reserved_interpolation_key - assert_raise(I18n::ReservedInterpolationKey) { @backend.send(:interpolate, nil, '{{default}}', {:default => nil}) } - end - - private - - def euc_jp(string) - string.encode!(Encoding::EUC_JP) - end -end - -class I18nSimpleBackendLocalizeDateTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @backend = I18n::Backend::Simple.new - add_datetime_translations - @date = Date.new 2008, 1, 1 - end - - def test_translate_given_the_short_format_it_uses_it - assert_equal '01. Jan', @backend.localize('de', @date, :short) - end - - def test_translate_given_the_long_format_it_uses_it - assert_equal '01. Januar 2008', @backend.localize('de', @date, :long) - end - - def test_translate_given_the_default_format_it_uses_it - assert_equal '01.01.2008', @backend.localize('de', @date, :default) - end - - def test_translate_given_a_day_name_format_it_returns_a_day_name - assert_equal 'Dienstag', @backend.localize('de', @date, '%A') - end - - def test_translate_given_an_abbr_day_name_format_it_returns_an_abbrevated_day_name - assert_equal 'Di', @backend.localize('de', @date, '%a') - end - - def test_translate_given_a_month_name_format_it_returns_a_month_name - assert_equal 'Januar', @backend.localize('de', @date, '%B') - end - - def test_translate_given_an_abbr_month_name_format_it_returns_an_abbrevated_month_name - assert_equal 'Jan', @backend.localize('de', @date, '%b') - end - - def test_translate_given_no_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @date } - end - - def test_translate_given_an_unknown_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @date, '%x' } - end - - def test_localize_nil_raises_argument_error - assert_raise(I18n::ArgumentError) { @backend.localize 'de', nil } - end - - def test_localize_object_raises_argument_error - assert_raise(I18n::ArgumentError) { @backend.localize 'de', Object.new } - end -end - -class I18nSimpleBackendLocalizeDateTimeTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @backend = I18n::Backend::Simple.new - add_datetime_translations - @morning = DateTime.new 2008, 1, 1, 6 - @evening = DateTime.new 2008, 1, 1, 18 - end - - def test_translate_given_the_short_format_it_uses_it - assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short) - end - - def test_translate_given_the_long_format_it_uses_it - assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long) - end - - def test_translate_given_the_default_format_it_uses_it - assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default) - end - - def test_translate_given_a_day_name_format_it_returns_the_correct_day_name - assert_equal 'Dienstag', @backend.localize('de', @morning, '%A') - end - - def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name - assert_equal 'Di', @backend.localize('de', @morning, '%a') - end - - def test_translate_given_a_month_name_format_it_returns_the_correct_month_name - assert_equal 'Januar', @backend.localize('de', @morning, '%B') - end - - def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name - assert_equal 'Jan', @backend.localize('de', @morning, '%b') - end - - def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator - assert_equal 'am', @backend.localize('de', @morning, '%p') - assert_equal 'pm', @backend.localize('de', @evening, '%p') - end - - def test_translate_given_no_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning } - end - - def test_translate_given_an_unknown_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning, '%x' } - end -end - -class I18nSimpleBackendLocalizeTimeTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @old_timezone, ENV['TZ'] = ENV['TZ'], 'UTC' - @backend = I18n::Backend::Simple.new - add_datetime_translations - @morning = Time.parse '2008-01-01 6:00 UTC' - @evening = Time.parse '2008-01-01 18:00 UTC' - end - - def teardown - @old_timezone ? ENV['TZ'] = @old_timezone : ENV.delete('TZ') - end - - def test_translate_given_the_short_format_it_uses_it - assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short) - end - - def test_translate_given_the_long_format_it_uses_it - assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long) - end - - # TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this? - # def test_translate_given_the_default_format_it_uses_it - # assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default) - # end - - def test_translate_given_a_day_name_format_it_returns_the_correct_day_name - assert_equal 'Dienstag', @backend.localize('de', @morning, '%A') - end - - def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name - assert_equal 'Di', @backend.localize('de', @morning, '%a') - end - - def test_translate_given_a_month_name_format_it_returns_the_correct_month_name - assert_equal 'Januar', @backend.localize('de', @morning, '%B') - end - - def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name - assert_equal 'Jan', @backend.localize('de', @morning, '%b') - end - - def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator - assert_equal 'am', @backend.localize('de', @morning, '%p') - assert_equal 'pm', @backend.localize('de', @evening, '%p') - end - - def test_translate_given_no_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning } - end - - def test_translate_given_an_unknown_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning, '%x' } - end -end - -class I18nSimpleBackendHelperMethodsTest < Test::Unit::TestCase - def setup - @backend = I18n::Backend::Simple.new - end - - def test_deep_symbolize_keys_works - result = @backend.send :deep_symbolize_keys, 'foo' => {'bar' => {'baz' => 'bar'}} - expected = {:foo => {:bar => {:baz => 'bar'}}} - assert_equal expected, result - end -end - -class I18nSimpleBackendLoadTranslationsTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_load_translations_with_unknown_file_type_raises_exception - assert_raise(I18n::UnknownFileType) { @backend.load_translations "#{@locale_dir}/en.xml" } - end - - def test_load_translations_with_ruby_file_type_does_not_raise_exception - assert_nothing_raised { @backend.load_translations "#{@locale_dir}/en.rb" } - end - - def test_load_rb_loads_data_from_ruby_file - data = @backend.send :load_rb, "#{@locale_dir}/en.rb" - assert_equal({:'en-Ruby' => {:foo => {:bar => "baz"}}}, data) - end - - def test_load_rb_loads_data_from_yaml_file - data = @backend.send :load_yml, "#{@locale_dir}/en.yml" - assert_equal({'en-Yaml' => {'foo' => {'bar' => 'baz'}}}, data) - end - - def test_load_translations_loads_from_different_file_formats - @backend = I18n::Backend::Simple.new - @backend.load_translations "#{@locale_dir}/en.rb", "#{@locale_dir}/en.yml" - expected = { - :'en-Ruby' => {:foo => {:bar => "baz"}}, - :'en-Yaml' => {:foo => {:bar => "baz"}} - } - assert_equal expected, backend_get_translations - end -end - -class I18nSimpleBackendLoadPathTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def teardown - I18n.load_path = [] - end - - def test_nested_load_paths_do_not_break_locale_loading - @backend = I18n::Backend::Simple.new - I18n.load_path = [[File.dirname(__FILE__) + '/locale/en.yml']] - assert_nil backend_get_translations - assert_nothing_raised { @backend.send :init_translations } - assert_not_nil backend_get_translations - end - - def test_adding_arrays_of_filenames_to_load_path_do_not_break_locale_loading - @backend = I18n::Backend::Simple.new - I18n.load_path << Dir[File.dirname(__FILE__) + '/locale/*.{rb,yml}'] - assert_nil backend_get_translations - assert_nothing_raised { @backend.send :init_translations } - assert_not_nil backend_get_translations - end -end - -class I18nSimpleBackendReloadTranslationsTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @backend = I18n::Backend::Simple.new - I18n.load_path = [File.dirname(__FILE__) + '/locale/en.yml'] - assert_nil backend_get_translations - @backend.send :init_translations - end - - def teardown - I18n.load_path = [] - end - - def test_setup - assert_not_nil backend_get_translations - end - - def test_reload_translations_unloads_translations - @backend.reload! - assert_nil backend_get_translations - end - - def test_reload_translations_uninitializes_translations - @backend.reload! - assert_equal @backend.initialized?, false - end -end -- cgit v1.2.3 From 4a1f43878105d701fd2dd769ec3cf7e81d133c09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 9 Nov 2009 16:35:31 -0200 Subject: Change mailer subjects lookup. --- actionmailer/lib/action_mailer/base.rb | 4 ++-- actionmailer/test/mail_service_test.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 293af01bbf..6a5a598f94 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -465,8 +465,8 @@ module ActionMailer #:nodoc: create_parts # Set the subject if not set yet - @subject ||= I18n.t(method_name, :scope => [:actionmailer, :subjects, mailer_name], - :default => method_name.humanize) + @subject ||= I18n.t(:subject, :scope => [:actionmailer, mailer_name, method_name], + :default => method_name.humanize) # build the mail object itself @mail = create_mail diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index f9365ea90c..c98f0a7601 100644 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -402,7 +402,7 @@ class ActionMailerTest < Test::Unit::TestCase assert_nothing_raised { TestMailer.deliver_subject_with_i18n(@recipient) } assert_equal "Subject with i18n", ActionMailer::Base.deliveries.first.subject - I18n.backend.store_translations('en', :actionmailer => {:subjects => {:test_mailer => {:subject_with_i18n => "New Subject!"}}}) + I18n.backend.store_translations('en', :actionmailer => {:test_mailer => {:subject_with_i18n => {:subject => "New Subject!"}}}) assert_nothing_raised { TestMailer.deliver_subject_with_i18n(@recipient) } assert_equal "New Subject!", ActionMailer::Base.deliveries.last.subject end -- cgit v1.2.3 From 0f1da1cb5cfac1343958daef4c5e7c37a9ce0da3 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Mon, 9 Nov 2009 11:33:47 -0800 Subject: Revert "Bundle I18n 0.2.0." This reverts commit 83f329f5f30567a10bc96410da230bf986db8ad4. --- Gemfile | 5 +- .../core_ext/string/interpolation.rb | 2 +- activesupport/lib/active_support/vendor.rb | 2 +- .../active_support/vendor/i18n-0.1.3/MIT-LICENSE | 20 + .../vendor/i18n-0.1.3/README.textile | 20 + .../lib/active_support/vendor/i18n-0.1.3/Rakefile | 5 + .../active_support/vendor/i18n-0.1.3/i18n.gemspec | 27 + .../active_support/vendor/i18n-0.1.3/lib/i18n.rb | 204 ++++++++ .../vendor/i18n-0.1.3/lib/i18n/backend/simple.rb | 215 ++++++++ .../vendor/i18n-0.1.3/lib/i18n/exceptions.rb | 53 ++ .../active_support/vendor/i18n-0.1.3/test/all.rb | 5 + .../vendor/i18n-0.1.3/test/i18n_exceptions_test.rb | 99 ++++ .../vendor/i18n-0.1.3/test/i18n_test.rb | 124 +++++ .../vendor/i18n-0.1.3/test/locale/en.rb | 1 + .../vendor/i18n-0.1.3/test/locale/en.yml | 3 + .../vendor/i18n-0.1.3/test/simple_backend_test.rb | 567 +++++++++++++++++++++ 16 files changed, 1347 insertions(+), 5 deletions(-) create mode 100755 activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec create mode 100755 activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml create mode 100644 activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb diff --git a/Gemfile b/Gemfile index 85a1ee0fef..a60c1010d9 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,7 @@ clear_sources source 'http://gemcutter.org' -gem "rails", "3.0.pre", :path => "railties" +gem "rails", "3.0.pre", :vendored_at => "railties" %w( activesupport activemodel @@ -10,9 +10,8 @@ gem "rails", "3.0.pre", :path => "railties" activerecord activeresource ).each do |lib| - gem lib, '3.0.pre', :path => lib + gem lib, '3.0.pre', :vendored_at => lib end -gem "i18n", "0.2.0" gem "rack", "1.0.1" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", "~> 0.5.0" diff --git a/activesupport/lib/active_support/core_ext/string/interpolation.rb b/activesupport/lib/active_support/core_ext/string/interpolation.rb index c4a5c0ca35..d9159b690a 100644 --- a/activesupport/lib/active_support/core_ext/string/interpolation.rb +++ b/activesupport/lib/active_support/core_ext/string/interpolation.rb @@ -5,7 +5,7 @@ You may redistribute it and/or modify it under the same license terms as Ruby. =end -if RUBY_VERSION < '1.9' && !"".respond_to?(:interpolate_without_ruby_19_syntax) +if RUBY_VERSION < '1.9' require 'active_support/core_ext/string/bytesize' # KeyError is raised by String#% when the string contains a named placeholder diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb index 15898d153c..4a711b7e25 100644 --- a/activesupport/lib/active_support/vendor.rb +++ b/activesupport/lib/active_support/vendor.rb @@ -4,7 +4,7 @@ def ActiveSupport.requirable?(file) $LOAD_PATH.any? { |p| Dir.glob("#{p}/#{file}.*").any? } end -[%w(builder 2.1.2), %w(memcache-client 1.7.5), %w(tzinfo 0.3.15)].each do |lib, version| +[%w(builder 2.1.2), %w(i18n 0.1.3), %w(memcache-client 1.7.5), %w(tzinfo 0.3.15)].each do |lib, version| # If the lib is not already requirable unless ActiveSupport.requirable? lib # Try to activate a gem ~> satisfying the requested version first. diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE b/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE new file mode 100755 index 0000000000..ed8e9ee66d --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008 The Ruby I18n team + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile b/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile new file mode 100644 index 0000000000..a07fc8426d --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile @@ -0,0 +1,20 @@ +h1. Ruby I18n gem + +I18n and localization solution for Ruby. + +For information please refer to http://rails-i18n.org + +h2. Authors + +* "Matt Aimonetti":http://railsontherun.com +* "Sven Fuchs":http://www.artweb-design.de +* "Joshua Harvey":http://www.workingwithrails.com/person/759-joshua-harvey +* "Saimon Moore":http://saimonmoore.net +* "Stephan Soller":http://www.arkanis-development.de + +h2. License + +MIT License. See the included MIT-LICENCE file. + + + diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile b/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile new file mode 100644 index 0000000000..2164e13e69 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile @@ -0,0 +1,5 @@ +task :default => [:test] + +task :test do + ruby "test/all.rb" +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec b/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec new file mode 100644 index 0000000000..f102689a6f --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec @@ -0,0 +1,27 @@ +Gem::Specification.new do |s| + s.name = "i18n" + s.version = "0.1.3" + s.date = "2009-01-09" + s.summary = "Internationalization support for Ruby" + s.email = "rails-i18n@googlegroups.com" + s.homepage = "http://rails-i18n.org" + s.description = "Add Internationalization support to your Ruby application." + s.has_rdoc = false + s.authors = ['Sven Fuchs', 'Joshua Harvey', 'Matt Aimonetti', 'Stephan Soller', 'Saimon Moore'] + s.files = [ + 'i18n.gemspec', + 'lib/i18n/backend/simple.rb', + 'lib/i18n/exceptions.rb', + 'lib/i18n.rb', + 'MIT-LICENSE', + 'README.textile' + ] + s.test_files = [ + 'test/all.rb', + 'test/i18n_exceptions_test.rb', + 'test/i18n_test.rb', + 'test/locale/en.rb', + 'test/locale/en.yml', + 'test/simple_backend_test.rb' + ] +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb new file mode 100755 index 0000000000..1b49debc05 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb @@ -0,0 +1,204 @@ +#-- +# Authors:: Matt Aimonetti (http://railsontherun.com/), +# Sven Fuchs (http://www.artweb-design.de), +# Joshua Harvey (http://www.workingwithrails.com/person/759-joshua-harvey), +# Saimon Moore (http://saimonmoore.net), +# Stephan Soller (http://www.arkanis-development.de/) +# Copyright:: Copyright (c) 2008 The Ruby i18n Team +# License:: MIT +#++ + +module I18n + autoload :ArgumentError, 'i18n/exceptions' + module Backend + autoload :Simple, 'i18n/backend/simple' + end + + @@backend = nil + @@load_path = nil + @@default_locale = :'en' + @@exception_handler = :default_exception_handler + + class << self + # Returns the current backend. Defaults to +Backend::Simple+. + def backend + @@backend ||= Backend::Simple.new + end + + # Sets the current backend. Used to set a custom backend. + def backend=(backend) + @@backend = backend + end + + # Returns the current default locale. Defaults to :'en' + def default_locale + @@default_locale + end + + # Sets the current default locale. Used to set a custom default locale. + def default_locale=(locale) + @@default_locale = locale + end + + # Returns the current locale. Defaults to I18n.default_locale. + def locale + Thread.current[:locale] ||= default_locale + end + + # Sets the current locale pseudo-globally, i.e. in the Thread.current hash. + def locale=(locale) + Thread.current[:locale] = locale + end + + # Returns an array of locales for which translations are available + def available_locales + backend.available_locales + end + + # Sets the exception handler. + def exception_handler=(exception_handler) + @@exception_handler = exception_handler + end + + # Allow clients to register paths providing translation data sources. The + # backend defines acceptable sources. + # + # E.g. the provided SimpleBackend accepts a list of paths to translation + # files which are either named *.rb and contain plain Ruby Hashes or are + # named *.yml and contain YAML data. So for the SimpleBackend clients may + # register translation files like this: + # I18n.load_path << 'path/to/locale/en.yml' + def load_path + @@load_path ||= [] + end + + # Sets the load path instance. Custom implementations are expected to + # behave like a Ruby Array. + def load_path=(load_path) + @@load_path = load_path + end + + # Tells the backend to reload translations. Used in situations like the + # Rails development environment. Backends can implement whatever strategy + # is useful. + def reload! + backend.reload! + end + + # Translates, pluralizes and interpolates a given key using a given locale, + # scope, and default, as well as interpolation values. + # + # *LOOKUP* + # + # Translation data is organized as a nested hash using the upper-level keys + # as namespaces. E.g., ActionView ships with the translation: + # :date => {:formats => {:short => "%b %d"}}. + # + # Translations can be looked up at any level of this hash using the key argument + # and the scope option. E.g., in this example I18n.t :date + # returns the whole translations hash {:formats => {:short => "%b %d"}}. + # + # Key can be either a single key or a dot-separated key (both Strings and Symbols + # work). E.g., the short format can be looked up using both: + # I18n.t 'date.formats.short' + # I18n.t :'date.formats.short' + # + # Scope can be either a single key, a dot-separated key or an array of keys + # or dot-separated keys. Keys and scopes can be combined freely. So these + # examples will all look up the same short date format: + # I18n.t 'date.formats.short' + # I18n.t 'formats.short', :scope => 'date' + # I18n.t 'short', :scope => 'date.formats' + # I18n.t 'short', :scope => %w(date formats) + # + # *INTERPOLATION* + # + # Translations can contain interpolation variables which will be replaced by + # values passed to #translate as part of the options hash, with the keys matching + # the interpolation variable names. + # + # E.g., with a translation :foo => "foo {{bar}}" the option + # value for the key +bar+ will be interpolated into the translation: + # I18n.t :foo, :bar => 'baz' # => 'foo baz' + # + # *PLURALIZATION* + # + # Translation data can contain pluralized translations. Pluralized translations + # are arrays of singluar/plural versions of translations like ['Foo', 'Foos']. + # + # Note that I18n::Backend::Simple only supports an algorithm for English + # pluralization rules. Other algorithms can be supported by custom backends. + # + # This returns the singular version of a pluralized translation: + # I18n.t :foo, :count => 1 # => 'Foo' + # + # These both return the plural version of a pluralized translation: + # I18n.t :foo, :count => 0 # => 'Foos' + # I18n.t :foo, :count => 2 # => 'Foos' + # + # The :count option can be used both for pluralization and interpolation. + # E.g., with the translation + # :foo => ['{{count}} foo', '{{count}} foos'], count will + # be interpolated to the pluralized translation: + # I18n.t :foo, :count => 1 # => '1 foo' + # + # *DEFAULTS* + # + # This returns the translation for :foo or default if no translation was found: + # I18n.t :foo, :default => 'default' + # + # This returns the translation for :foo or the translation for :bar if no + # translation for :foo was found: + # I18n.t :foo, :default => :bar + # + # Returns the translation for :foo or the translation for :bar + # or default if no translations for :foo and :bar were found. + # I18n.t :foo, :default => [:bar, 'default'] + # + # BULK LOOKUP + # + # This returns an array with the translations for :foo and :bar. + # I18n.t [:foo, :bar] + # + # Can be used with dot-separated nested keys: + # I18n.t [:'baz.foo', :'baz.bar'] + # + # Which is the same as using a scope option: + # I18n.t [:foo, :bar], :scope => :baz + def translate(key, options = {}) + locale = options.delete(:locale) || I18n.locale + backend.translate(locale, key, options) + rescue I18n::ArgumentError => e + raise e if options[:raise] + send(@@exception_handler, e, locale, key, options) + end + alias :t :translate + + # Localizes certain objects, such as dates and numbers to local formatting. + def localize(object, options = {}) + locale = options[:locale] || I18n.locale + format = options[:format] || :default + backend.localize(locale, object, format) + end + alias :l :localize + + protected + # Handles exceptions raised in the backend. All exceptions except for + # MissingTranslationData exceptions are re-raised. When a MissingTranslationData + # was caught and the option :raise is not set the handler returns an error + # message string containing the key/scope. + def default_exception_handler(exception, locale, key, options) + return exception.message if MissingTranslationData === exception + raise exception + end + + # Merges the given locale, key and scope into a single array of keys. + # Splits keys that contain dots into multiple keys. Makes sure all + # keys are Symbols. + def normalize_translation_keys(locale, key, scope) + keys = [locale] + Array(scope) + [key] + keys = keys.map { |k| k.to_s.split(/\./) } + keys.flatten.map { |k| k.to_sym } + end + end +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb new file mode 100644 index 0000000000..c32cc76f34 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb @@ -0,0 +1,215 @@ +require 'i18n/exceptions' + +module I18n + module Backend + class Simple + INTERPOLATION_RESERVED_KEYS = %w(scope default) + MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ + + # Accepts a list of paths to translation files. Loads translations from + # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml + # for details. + def load_translations(*filenames) + filenames.each { |filename| load_file(filename) } + end + + # Stores translations for the given locale in memory. + # This uses a deep merge for the translations hash, so existing + # translations will be overwritten by new ones only at the deepest + # level of the hash. + def store_translations(locale, data) + merge_translations(locale, data) + end + + def translate(locale, key, options = {}) + raise InvalidLocale.new(locale) if locale.nil? + return key.map { |k| translate(locale, k, options) } if key.is_a? Array + + reserved = :scope, :default + count, scope, default = options.values_at(:count, *reserved) + options.delete(:default) + values = options.reject { |name, value| reserved.include?(name) } + + entry = lookup(locale, key, scope) + if entry.nil? + entry = default(locale, default, options) + if entry.nil? + raise(I18n::MissingTranslationData.new(locale, key, options)) + end + end + entry = pluralize(locale, entry, count) + entry = interpolate(locale, entry, values) + entry + end + + # Acts the same as +strftime+, but returns a localized version of the + # formatted date string. Takes a key from the date/time formats + # translations as a format argument (e.g., :short in :'date.formats'). + def localize(locale, object, format = :default) + raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) + + type = object.respond_to?(:sec) ? 'time' : 'date' + # TODO only translate these if format is a String? + formats = translate(locale, :"#{type}.formats") + format = formats[format.to_sym] if formats && formats[format.to_sym] + # TODO raise exception unless format found? + format = format.to_s.dup + + # TODO only translate these if the format string is actually present + # TODO check which format strings are present, then bulk translate then, then replace them + format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday]) + format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday]) + format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon]) + format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon]) + format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour + object.strftime(format) + end + + def initialized? + @initialized ||= false + end + + # Returns an array of locales for which translations are available + def available_locales + init_translations unless initialized? + translations.keys + end + + def reload! + @initialized = false + @translations = nil + end + + protected + def init_translations + load_translations(*I18n.load_path.flatten) + @initialized = true + end + + def translations + @translations ||= {} + end + + # Looks up a translation from the translations hash. Returns nil if + # eiher key is nil, or locale, scope or key do not exist as a key in the + # nested translations hash. Splits keys or scopes containing dots + # into multiple keys, i.e. currency.format is regarded the same as + # %w(currency format). + def lookup(locale, key, scope = []) + return unless key + init_translations unless initialized? + keys = I18n.send(:normalize_translation_keys, locale, key, scope) + keys.inject(translations) do |result, k| + if (x = result[k.to_sym]).nil? + return nil + else + x + end + end + end + + # Evaluates a default translation. + # If the given default is a String it is used literally. If it is a Symbol + # it will be translated with the given options. If it is an Array the first + # translation yielded will be returned. + # + # I.e., default(locale, [:foo, 'default']) will return +default+ if + # translate(locale, :foo) does not yield a result. + def default(locale, default, options = {}) + case default + when String then default + when Symbol then translate locale, default, options + when Array then default.each do |obj| + result = default(locale, obj, options.dup) and return result + end and nil + end + rescue MissingTranslationData + nil + end + + # Picks a translation from an array according to English pluralization + # rules. It will pick the first translation if count is not equal to 1 + # and the second translation if it is equal to 1. Other backends can + # implement more flexible or complex pluralization rules. + def pluralize(locale, entry, count) + return entry unless entry.is_a?(Hash) and count + # raise InvalidPluralizationData.new(entry, count) unless entry.is_a?(Hash) + key = :zero if count == 0 && entry.has_key?(:zero) + key ||= count == 1 ? :one : :other + raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key) + entry[key] + end + + # Interpolates values into a given string. + # + # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X' + # # => "file test.txt opened by {{user}}" + # + # Note that you have to double escape the \\ when you want to escape + # the {{...}} key in a string (once for the string and once for the + # interpolation). + def interpolate(locale, string, values = {}) + return string unless string.is_a?(String) + + string.gsub(MATCH) do + escaped, pattern, key = $1, $2, $2.to_sym + + if escaped + pattern + elsif INTERPOLATION_RESERVED_KEYS.include?(pattern) + raise ReservedInterpolationKey.new(pattern, string) + elsif !values.include?(key) + raise MissingInterpolationArgument.new(pattern, string) + else + values[key].to_s + end + end + end + + # Loads a single translations file by delegating to #load_rb or + # #load_yml depending on the file extension and directly merges the + # data to the existing translations. Raises I18n::UnknownFileType + # for all other file extensions. + def load_file(filename) + type = File.extname(filename).tr('.', '').downcase + raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}") + data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash + data.each { |locale, d| merge_translations(locale, d) } + end + + # Loads a plain Ruby translations file. eval'ing the file must yield + # a Hash containing translation data with locales as toplevel keys. + def load_rb(filename) + eval(IO.read(filename), binding, filename) + end + + # Loads a YAML translations file. The data must have locales as + # toplevel keys. + def load_yml(filename) + require 'yaml' unless defined? :YAML + YAML::load(IO.read(filename)) + end + + # Deep merges the given translations hash with the existing translations + # for the given locale + def merge_translations(locale, data) + locale = locale.to_sym + translations[locale] ||= {} + data = deep_symbolize_keys(data) + + # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 + merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } + translations[locale].merge!(data, &merger) + end + + # Return a new hash with all keys and nested keys converted to symbols. + def deep_symbolize_keys(hash) + hash.inject({}) { |result, (key, value)| + value = deep_symbolize_keys(value) if value.is_a? Hash + result[(key.to_sym rescue key) || key] = value + result + } + end + end + end +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb new file mode 100644 index 0000000000..6897055d6d --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb @@ -0,0 +1,53 @@ +module I18n + class ArgumentError < ::ArgumentError; end + + class InvalidLocale < ArgumentError + attr_reader :locale + def initialize(locale) + @locale = locale + super "#{locale.inspect} is not a valid locale" + end + end + + class MissingTranslationData < ArgumentError + attr_reader :locale, :key, :options + def initialize(locale, key, options) + @key, @locale, @options = key, locale, options + keys = I18n.send(:normalize_translation_keys, locale, key, options[:scope]) + keys << 'no key' if keys.size < 2 + super "translation missing: #{keys.join(', ')}" + end + end + + class InvalidPluralizationData < ArgumentError + attr_reader :entry, :count + def initialize(entry, count) + @entry, @count = entry, count + super "translation data #{entry.inspect} can not be used with :count => #{count}" + end + end + + class MissingInterpolationArgument < ArgumentError + attr_reader :key, :string + def initialize(key, string) + @key, @string = key, string + super "interpolation argument #{key} missing in #{string.inspect}" + end + end + + class ReservedInterpolationKey < ArgumentError + attr_reader :key, :string + def initialize(key, string) + @key, @string = key, string + super "reserved key #{key.inspect} used in #{string.inspect}" + end + end + + class UnknownFileType < ArgumentError + attr_reader :type, :filename + def initialize(type, filename) + @type, @filename = type, filename + super "can not load translations from #{filename}, the file type #{type} is not known" + end + end +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb new file mode 100644 index 0000000000..353712da49 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb @@ -0,0 +1,5 @@ +dir = File.dirname(__FILE__) +require dir + '/i18n_test.rb' +require dir + '/simple_backend_test.rb' +require dir + '/i18n_exceptions_test.rb' +# *require* dir + '/custom_backend_test.rb' \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb new file mode 100644 index 0000000000..4e78e71b34 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb @@ -0,0 +1,99 @@ +$:.unshift "lib" + +require 'rubygems' +require 'test/unit' +require 'i18n' +require 'active_support' + +class I18nExceptionsTest < Test::Unit::TestCase + def test_invalid_locale_stores_locale + force_invalid_locale + rescue I18n::ArgumentError => e + assert_nil e.locale + end + + def test_invalid_locale_message + force_invalid_locale + rescue I18n::ArgumentError => e + assert_equal 'nil is not a valid locale', e.message + end + + def test_missing_translation_data_stores_locale_key_and_options + force_missing_translation_data + rescue I18n::ArgumentError => e + options = {:scope => :bar} + assert_equal 'de', e.locale + assert_equal :foo, e.key + assert_equal options, e.options + end + + def test_missing_translation_data_message + force_missing_translation_data + rescue I18n::ArgumentError => e + assert_equal 'translation missing: de, bar, foo', e.message + end + + def test_invalid_pluralization_data_stores_entry_and_count + force_invalid_pluralization_data + rescue I18n::ArgumentError => e + assert_equal [:bar], e.entry + assert_equal 1, e.count + end + + def test_invalid_pluralization_data_message + force_invalid_pluralization_data + rescue I18n::ArgumentError => e + assert_equal 'translation data [:bar] can not be used with :count => 1', e.message + end + + def test_missing_interpolation_argument_stores_key_and_string + force_missing_interpolation_argument + rescue I18n::ArgumentError => e + assert_equal 'bar', e.key + assert_equal "{{bar}}", e.string + end + + def test_missing_interpolation_argument_message + force_missing_interpolation_argument + rescue I18n::ArgumentError => e + assert_equal 'interpolation argument bar missing in "{{bar}}"', e.message + end + + def test_reserved_interpolation_key_stores_key_and_string + force_reserved_interpolation_key + rescue I18n::ArgumentError => e + assert_equal 'scope', e.key + assert_equal "{{scope}}", e.string + end + + def test_reserved_interpolation_key_message + force_reserved_interpolation_key + rescue I18n::ArgumentError => e + assert_equal 'reserved key "scope" used in "{{scope}}"', e.message + end + + private + def force_invalid_locale + I18n.backend.translate nil, :foo + end + + def force_missing_translation_data + I18n.backend.store_translations 'de', :bar => nil + I18n.backend.translate 'de', :foo, :scope => :bar + end + + def force_invalid_pluralization_data + I18n.backend.store_translations 'de', :foo => [:bar] + I18n.backend.translate 'de', :foo, :count => 1 + end + + def force_missing_interpolation_argument + I18n.backend.store_translations 'de', :foo => "{{bar}}" + I18n.backend.translate 'de', :foo, :baz => 'baz' + end + + def force_reserved_interpolation_key + I18n.backend.store_translations 'de', :foo => "{{scope}}" + I18n.backend.translate 'de', :foo, :baz => 'baz' + end +end \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb new file mode 100644 index 0000000000..2835ec4eab --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb @@ -0,0 +1,124 @@ +$:.unshift "lib" + +require 'rubygems' +require 'test/unit' +require 'i18n' +require 'active_support' + +class I18nTest < Test::Unit::TestCase + def setup + I18n.backend.store_translations :'en', { + :currency => { + :format => { + :separator => '.', + :delimiter => ',', + } + } + } + end + + def test_uses_simple_backend_set_by_default + assert I18n.backend.is_a?(I18n::Backend::Simple) + end + + def test_can_set_backend + assert_nothing_raised{ I18n.backend = self } + assert_equal self, I18n.backend + I18n.backend = I18n::Backend::Simple.new + end + + def test_uses_en_us_as_default_locale_by_default + assert_equal 'en', I18n.default_locale + end + + def test_can_set_default_locale + assert_nothing_raised{ I18n.default_locale = 'de' } + assert_equal 'de', I18n.default_locale + I18n.default_locale = 'en' + end + + def test_uses_default_locale_as_locale_by_default + assert_equal I18n.default_locale, I18n.locale + end + + def test_can_set_locale_to_thread_current + assert_nothing_raised{ I18n.locale = 'de' } + assert_equal 'de', I18n.locale + assert_equal 'de', Thread.current[:locale] + I18n.locale = 'en' + end + + def test_can_set_exception_handler + assert_nothing_raised{ I18n.exception_handler = :custom_exception_handler } + I18n.exception_handler = :default_exception_handler # revert it + end + + def test_uses_custom_exception_handler + I18n.exception_handler = :custom_exception_handler + I18n.expects(:custom_exception_handler) + I18n.translate :bogus + I18n.exception_handler = :default_exception_handler # revert it + end + + def test_delegates_translate_to_backend + I18n.backend.expects(:translate).with 'de', :foo, {} + I18n.translate :foo, :locale => 'de' + end + + def test_delegates_localize_to_backend + I18n.backend.expects(:localize).with 'de', :whatever, :default + I18n.localize :whatever, :locale => 'de' + end + + def test_translate_given_no_locale_uses_i18n_locale + I18n.backend.expects(:translate).with 'en', :foo, {} + I18n.translate :foo + end + + def test_translate_on_nested_symbol_keys_works + assert_equal ".", I18n.t(:'currency.format.separator') + end + + def test_translate_with_nested_string_keys_works + assert_equal ".", I18n.t('currency.format.separator') + end + + def test_translate_with_array_as_scope_works + assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) + end + + def test_translate_with_array_containing_dot_separated_strings_as_scope_works + assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) + end + + def test_translate_with_key_array_and_dot_separated_scope_works + assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format') + end + + def test_translate_with_dot_separated_key_array_and_scope_works + assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency') + end + + def test_translate_with_options_using_scope_works + I18n.backend.expects(:translate).with('de', :precision, :scope => :"currency.format") + I18n.with_options :locale => 'de', :scope => :'currency.format' do |locale| + locale.t :precision + end + end + + # def test_translate_given_no_args_raises_missing_translation_data + # assert_equal "translation missing: en, no key", I18n.t + # end + + def test_translate_given_a_bogus_key_raises_missing_translation_data + assert_equal "translation missing: en, bogus", I18n.t(:bogus) + end + + def test_localize_nil_raises_argument_error + assert_raise(I18n::ArgumentError) { I18n.l nil } + end + + def test_localize_object_raises_argument_error + assert_raise(I18n::ArgumentError) { I18n.l Object.new } + end +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb new file mode 100644 index 0000000000..6044ce10d9 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb @@ -0,0 +1 @@ +{:'en-Ruby' => {:foo => {:bar => "baz"}}} \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml new file mode 100644 index 0000000000..0b298c9c0e --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml @@ -0,0 +1,3 @@ +en-Yaml: + foo: + bar: baz \ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb new file mode 100644 index 0000000000..a1696c77f6 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb @@ -0,0 +1,567 @@ +# encoding: utf-8 +$:.unshift "lib" + +require 'rubygems' +require 'test/unit' +require 'i18n' +require 'time' +require 'yaml' + +module I18nSimpleBackendTestSetup + def setup_backend + # backend_reset_translations! + @backend = I18n::Backend::Simple.new + @backend.store_translations 'en', :foo => {:bar => 'bar', :baz => 'baz'} + @locale_dir = File.dirname(__FILE__) + '/locale' + end + alias :setup :setup_backend + + # def backend_reset_translations! + # I18n::Backend::Simple::ClassMethods.send :class_variable_set, :@@translations, {} + # end + + def backend_get_translations + # I18n::Backend::Simple::ClassMethods.send :class_variable_get, :@@translations + @backend.instance_variable_get :@translations + end + + def add_datetime_translations + @backend.store_translations :'de', { + :date => { + :formats => { + :default => "%d.%m.%Y", + :short => "%d. %b", + :long => "%d. %B %Y", + }, + :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag), + :abbr_day_names => %w(So Mo Di Mi Do Fr Sa), + :month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil), + :abbr_month_names => %w(Jan Feb Mar Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil), + :order => [:day, :month, :year] + }, + :time => { + :formats => { + :default => "%a, %d. %b %Y %H:%M:%S %z", + :short => "%d. %b %H:%M", + :long => "%d. %B %Y %H:%M", + }, + :am => 'am', + :pm => 'pm' + }, + :datetime => { + :distance_in_words => { + :half_a_minute => 'half a minute', + :less_than_x_seconds => { + :one => 'less than 1 second', + :other => 'less than {{count}} seconds' + }, + :x_seconds => { + :one => '1 second', + :other => '{{count}} seconds' + }, + :less_than_x_minutes => { + :one => 'less than a minute', + :other => 'less than {{count}} minutes' + }, + :x_minutes => { + :one => '1 minute', + :other => '{{count}} minutes' + }, + :about_x_hours => { + :one => 'about 1 hour', + :other => 'about {{count}} hours' + }, + :x_days => { + :one => '1 day', + :other => '{{count}} days' + }, + :about_x_months => { + :one => 'about 1 month', + :other => 'about {{count}} months' + }, + :x_months => { + :one => '1 month', + :other => '{{count}} months' + }, + :about_x_years => { + :one => 'about 1 year', + :other => 'about {{count}} year' + }, + :over_x_years => { + :one => 'over 1 year', + :other => 'over {{count}} years' + } + } + } + } + end +end + +class I18nSimpleBackendTranslationsTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def test_store_translations_adds_translations # no, really :-) + @backend.store_translations :'en', :foo => 'bar' + assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations + end + + def test_store_translations_deep_merges_translations + @backend.store_translations :'en', :foo => {:bar => 'bar'} + @backend.store_translations :'en', :foo => {:baz => 'baz'} + assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations + end + + def test_store_translations_forces_locale_to_sym + @backend.store_translations 'en', :foo => 'bar' + assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations + end + + def test_store_translations_converts_keys_to_symbols + # backend_reset_translations! + @backend.store_translations 'en', 'foo' => {'bar' => 'bar', 'baz' => 'baz'} + assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations + end +end + +class I18nSimpleBackendAvailableLocalesTest < Test::Unit::TestCase + def test_available_locales + @backend = I18n::Backend::Simple.new + @backend.store_translations 'de', :foo => 'bar' + @backend.store_translations 'en', :foo => 'foo' + + assert_equal ['de', 'en'], @backend.available_locales.map{|locale| locale.to_s }.sort + end +end + +class I18nSimpleBackendTranslateTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def test_translate_calls_lookup_with_locale_given + @backend.expects(:lookup).with('de', :bar, [:foo]).returns 'bar' + @backend.translate 'de', :bar, :scope => [:foo] + end + + def test_given_no_keys_it_returns_the_default + assert_equal 'default', @backend.translate('en', nil, :default => 'default') + end + + def test_translate_given_a_symbol_as_a_default_translates_the_symbol + assert_equal 'bar', @backend.translate('en', nil, :scope => [:foo], :default => :bar) + end + + def test_translate_given_an_array_as_default_uses_the_first_match + assert_equal 'bar', @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :bar]) + end + + def test_translate_given_an_array_of_inexistent_keys_it_raises_missing_translation_data + assert_raise I18n::MissingTranslationData do + @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :does_not_exist_3]) + end + end + + def test_translate_an_array_of_keys_translates_all_of_them + assert_equal %w(bar baz), @backend.translate('en', [:bar, :baz], :scope => [:foo]) + end + + def test_translate_calls_pluralize + @backend.expects(:pluralize).with 'en', 'bar', 1 + @backend.translate 'en', :bar, :scope => [:foo], :count => 1 + end + + def test_translate_calls_interpolate + @backend.expects(:interpolate).with 'en', 'bar', {} + @backend.translate 'en', :bar, :scope => [:foo] + end + + def test_translate_calls_interpolate_including_count_as_a_value + @backend.expects(:interpolate).with 'en', 'bar', {:count => 1} + @backend.translate 'en', :bar, :scope => [:foo], :count => 1 + end + + def test_translate_given_nil_as_a_locale_raises_an_argument_error + assert_raise(I18n::InvalidLocale){ @backend.translate nil, :bar } + end + + def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_data + assert_raise(I18n::MissingTranslationData){ @backend.translate 'de', :bogus } + end +end + +class I18nSimpleBackendLookupTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + # useful because this way we can use the backend with no key for interpolation/pluralization + def test_lookup_given_nil_as_a_key_returns_nil + assert_nil @backend.send(:lookup, 'en', nil) + end + + def test_lookup_given_nested_keys_looks_up_a_nested_hash_value + assert_equal 'bar', @backend.send(:lookup, 'en', :bar, [:foo]) + end +end + +class I18nSimpleBackendPluralizeTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def test_pluralize_given_nil_returns_the_given_entry + entry = {:one => 'bar', :other => 'bars'} + assert_equal entry, @backend.send(:pluralize, nil, entry, nil) + end + + def test_pluralize_given_0_returns_zero_string_if_zero_key_given + assert_equal 'zero', @backend.send(:pluralize, nil, {:zero => 'zero', :one => 'bar', :other => 'bars'}, 0) + end + + def test_pluralize_given_0_returns_plural_string_if_no_zero_key_given + assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 0) + end + + def test_pluralize_given_1_returns_singular_string + assert_equal 'bar', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 1) + end + + def test_pluralize_given_2_returns_plural_string + assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 2) + end + + def test_pluralize_given_3_returns_plural_string + assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 3) + end + + def test_interpolate_given_incomplete_pluralization_data_raises_invalid_pluralization_data + assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, {:one => 'bar'}, 2) } + end + + # def test_interpolate_given_a_string_raises_invalid_pluralization_data + # assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, 'bar', 2) } + # end + # + # def test_interpolate_given_an_array_raises_invalid_pluralization_data + # assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, ['bar'], 2) } + # end +end + +class I18nSimpleBackendInterpolateTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def test_interpolate_given_a_value_hash_interpolates_the_values_to_the_string + assert_equal 'Hi David!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'David') + end + + def test_interpolate_given_a_value_hash_interpolates_into_unicode_string + assert_equal 'Häi David!', @backend.send(:interpolate, nil, 'Häi {{name}}!', :name => 'David') + end + + def test_interpolate_given_an_unicode_value_hash_interpolates_to_the_string + assert_equal 'Hi ゆきひろ!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'ゆきひろ') + end + + def test_interpolate_given_an_unicode_value_hash_interpolates_into_unicode_string + assert_equal 'こんにちは、ゆきひろさん!', @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => 'ゆきひろ') + end + + if Kernel.const_defined?(:Encoding) + def test_interpolate_given_a_non_unicode_multibyte_value_hash_interpolates_into_a_string_with_the_same_encoding + assert_equal euc_jp('Hi ゆきひろ!'), @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => euc_jp('ゆきひろ')) + end + + def test_interpolate_given_an_unicode_value_hash_into_a_non_unicode_multibyte_string_raises_encoding_compatibility_error + assert_raise(Encoding::CompatibilityError) do + @backend.send(:interpolate, nil, euc_jp('こんにちは、{{name}}さん!'), :name => 'ゆきひろ') + end + end + + def test_interpolate_given_a_non_unicode_multibyte_value_hash_into_an_unicode_string_raises_encoding_compatibility_error + assert_raise(Encoding::CompatibilityError) do + @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => euc_jp('ゆきひろ')) + end + end + end + + def test_interpolate_given_nil_as_a_string_returns_nil + assert_nil @backend.send(:interpolate, nil, nil, :name => 'David') + end + + def test_interpolate_given_an_non_string_as_a_string_returns_nil + assert_equal [], @backend.send(:interpolate, nil, [], :name => 'David') + end + + def test_interpolate_given_a_values_hash_with_nil_values_interpolates_the_string + assert_equal 'Hi !', @backend.send(:interpolate, nil, 'Hi {{name}}!', {:name => nil}) + end + + def test_interpolate_given_an_empty_values_hash_raises_missing_interpolation_argument + assert_raise(I18n::MissingInterpolationArgument) { @backend.send(:interpolate, nil, 'Hi {{name}}!', {}) } + end + + def test_interpolate_given_a_string_containing_a_reserved_key_raises_reserved_interpolation_key + assert_raise(I18n::ReservedInterpolationKey) { @backend.send(:interpolate, nil, '{{default}}', {:default => nil}) } + end + + private + + def euc_jp(string) + string.encode!(Encoding::EUC_JP) + end +end + +class I18nSimpleBackendLocalizeDateTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def setup + @backend = I18n::Backend::Simple.new + add_datetime_translations + @date = Date.new 2008, 1, 1 + end + + def test_translate_given_the_short_format_it_uses_it + assert_equal '01. Jan', @backend.localize('de', @date, :short) + end + + def test_translate_given_the_long_format_it_uses_it + assert_equal '01. Januar 2008', @backend.localize('de', @date, :long) + end + + def test_translate_given_the_default_format_it_uses_it + assert_equal '01.01.2008', @backend.localize('de', @date, :default) + end + + def test_translate_given_a_day_name_format_it_returns_a_day_name + assert_equal 'Dienstag', @backend.localize('de', @date, '%A') + end + + def test_translate_given_an_abbr_day_name_format_it_returns_an_abbrevated_day_name + assert_equal 'Di', @backend.localize('de', @date, '%a') + end + + def test_translate_given_a_month_name_format_it_returns_a_month_name + assert_equal 'Januar', @backend.localize('de', @date, '%B') + end + + def test_translate_given_an_abbr_month_name_format_it_returns_an_abbrevated_month_name + assert_equal 'Jan', @backend.localize('de', @date, '%b') + end + + def test_translate_given_no_format_it_does_not_fail + assert_nothing_raised{ @backend.localize 'de', @date } + end + + def test_translate_given_an_unknown_format_it_does_not_fail + assert_nothing_raised{ @backend.localize 'de', @date, '%x' } + end + + def test_localize_nil_raises_argument_error + assert_raise(I18n::ArgumentError) { @backend.localize 'de', nil } + end + + def test_localize_object_raises_argument_error + assert_raise(I18n::ArgumentError) { @backend.localize 'de', Object.new } + end +end + +class I18nSimpleBackendLocalizeDateTimeTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def setup + @backend = I18n::Backend::Simple.new + add_datetime_translations + @morning = DateTime.new 2008, 1, 1, 6 + @evening = DateTime.new 2008, 1, 1, 18 + end + + def test_translate_given_the_short_format_it_uses_it + assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short) + end + + def test_translate_given_the_long_format_it_uses_it + assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long) + end + + def test_translate_given_the_default_format_it_uses_it + assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default) + end + + def test_translate_given_a_day_name_format_it_returns_the_correct_day_name + assert_equal 'Dienstag', @backend.localize('de', @morning, '%A') + end + + def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name + assert_equal 'Di', @backend.localize('de', @morning, '%a') + end + + def test_translate_given_a_month_name_format_it_returns_the_correct_month_name + assert_equal 'Januar', @backend.localize('de', @morning, '%B') + end + + def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name + assert_equal 'Jan', @backend.localize('de', @morning, '%b') + end + + def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator + assert_equal 'am', @backend.localize('de', @morning, '%p') + assert_equal 'pm', @backend.localize('de', @evening, '%p') + end + + def test_translate_given_no_format_it_does_not_fail + assert_nothing_raised{ @backend.localize 'de', @morning } + end + + def test_translate_given_an_unknown_format_it_does_not_fail + assert_nothing_raised{ @backend.localize 'de', @morning, '%x' } + end +end + +class I18nSimpleBackendLocalizeTimeTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def setup + @old_timezone, ENV['TZ'] = ENV['TZ'], 'UTC' + @backend = I18n::Backend::Simple.new + add_datetime_translations + @morning = Time.parse '2008-01-01 6:00 UTC' + @evening = Time.parse '2008-01-01 18:00 UTC' + end + + def teardown + @old_timezone ? ENV['TZ'] = @old_timezone : ENV.delete('TZ') + end + + def test_translate_given_the_short_format_it_uses_it + assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short) + end + + def test_translate_given_the_long_format_it_uses_it + assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long) + end + + # TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this? + # def test_translate_given_the_default_format_it_uses_it + # assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default) + # end + + def test_translate_given_a_day_name_format_it_returns_the_correct_day_name + assert_equal 'Dienstag', @backend.localize('de', @morning, '%A') + end + + def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name + assert_equal 'Di', @backend.localize('de', @morning, '%a') + end + + def test_translate_given_a_month_name_format_it_returns_the_correct_month_name + assert_equal 'Januar', @backend.localize('de', @morning, '%B') + end + + def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name + assert_equal 'Jan', @backend.localize('de', @morning, '%b') + end + + def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator + assert_equal 'am', @backend.localize('de', @morning, '%p') + assert_equal 'pm', @backend.localize('de', @evening, '%p') + end + + def test_translate_given_no_format_it_does_not_fail + assert_nothing_raised{ @backend.localize 'de', @morning } + end + + def test_translate_given_an_unknown_format_it_does_not_fail + assert_nothing_raised{ @backend.localize 'de', @morning, '%x' } + end +end + +class I18nSimpleBackendHelperMethodsTest < Test::Unit::TestCase + def setup + @backend = I18n::Backend::Simple.new + end + + def test_deep_symbolize_keys_works + result = @backend.send :deep_symbolize_keys, 'foo' => {'bar' => {'baz' => 'bar'}} + expected = {:foo => {:bar => {:baz => 'bar'}}} + assert_equal expected, result + end +end + +class I18nSimpleBackendLoadTranslationsTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def test_load_translations_with_unknown_file_type_raises_exception + assert_raise(I18n::UnknownFileType) { @backend.load_translations "#{@locale_dir}/en.xml" } + end + + def test_load_translations_with_ruby_file_type_does_not_raise_exception + assert_nothing_raised { @backend.load_translations "#{@locale_dir}/en.rb" } + end + + def test_load_rb_loads_data_from_ruby_file + data = @backend.send :load_rb, "#{@locale_dir}/en.rb" + assert_equal({:'en-Ruby' => {:foo => {:bar => "baz"}}}, data) + end + + def test_load_rb_loads_data_from_yaml_file + data = @backend.send :load_yml, "#{@locale_dir}/en.yml" + assert_equal({'en-Yaml' => {'foo' => {'bar' => 'baz'}}}, data) + end + + def test_load_translations_loads_from_different_file_formats + @backend = I18n::Backend::Simple.new + @backend.load_translations "#{@locale_dir}/en.rb", "#{@locale_dir}/en.yml" + expected = { + :'en-Ruby' => {:foo => {:bar => "baz"}}, + :'en-Yaml' => {:foo => {:bar => "baz"}} + } + assert_equal expected, backend_get_translations + end +end + +class I18nSimpleBackendLoadPathTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def teardown + I18n.load_path = [] + end + + def test_nested_load_paths_do_not_break_locale_loading + @backend = I18n::Backend::Simple.new + I18n.load_path = [[File.dirname(__FILE__) + '/locale/en.yml']] + assert_nil backend_get_translations + assert_nothing_raised { @backend.send :init_translations } + assert_not_nil backend_get_translations + end + + def test_adding_arrays_of_filenames_to_load_path_do_not_break_locale_loading + @backend = I18n::Backend::Simple.new + I18n.load_path << Dir[File.dirname(__FILE__) + '/locale/*.{rb,yml}'] + assert_nil backend_get_translations + assert_nothing_raised { @backend.send :init_translations } + assert_not_nil backend_get_translations + end +end + +class I18nSimpleBackendReloadTranslationsTest < Test::Unit::TestCase + include I18nSimpleBackendTestSetup + + def setup + @backend = I18n::Backend::Simple.new + I18n.load_path = [File.dirname(__FILE__) + '/locale/en.yml'] + assert_nil backend_get_translations + @backend.send :init_translations + end + + def teardown + I18n.load_path = [] + end + + def test_setup + assert_not_nil backend_get_translations + end + + def test_reload_translations_unloads_translations + @backend.reload! + assert_nil backend_get_translations + end + + def test_reload_translations_uninitializes_translations + @backend.reload! + assert_equal @backend.initialized?, false + end +end -- cgit v1.2.3 From afc129e2707daa0de1dd85c0796a1f9d73e7107f Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Thu, 29 Oct 2009 14:39:59 -0400 Subject: Fix some Ruby warnings: `*' interpreted as argument prefix --- actionpack/lib/action_controller/translation.rb | 4 ++-- actionpack/lib/action_view/helpers/translation_helper.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_controller/translation.rb b/actionpack/lib/action_controller/translation.rb index 9bb63cdb15..65e9eddb0a 100644 --- a/actionpack/lib/action_controller/translation.rb +++ b/actionpack/lib/action_controller/translation.rb @@ -1,12 +1,12 @@ module ActionController module Translation def translate(*args) - I18n.translate *args + I18n.translate(*args) end alias :t :translate def localize(*args) - I18n.localize *args + I18n.localize(*args) end alias :l :localize end diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb index 4aed10f640..564f12c955 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -21,7 +21,7 @@ module ActionView # Delegates to I18n.localize with no additional functionality. def localize(*args) - I18n.localize *args + I18n.localize(*args) end alias :l :localize -- cgit v1.2.3 From 17dee01b6f2186888629859fe2e99232225ae5ea Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Thu, 29 Oct 2009 14:43:25 -0400 Subject: Fix Ruby warning: method redefined; discarding old breakpoint --- activesupport/lib/active_support/core_ext/kernel/debugger.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/lib/active_support/core_ext/kernel/debugger.rb b/activesupport/lib/active_support/core_ext/kernel/debugger.rb index 0813a51383..59e03e3df7 100644 --- a/activesupport/lib/active_support/core_ext/kernel/debugger.rb +++ b/activesupport/lib/active_support/core_ext/kernel/debugger.rb @@ -7,6 +7,7 @@ module Kernel end end + undef :breakpoint if respond_to?(:breakpoint) def breakpoint message = "\n***** The 'breakpoint' command has been renamed 'debugger' -- please change *****\n" defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message) -- cgit v1.2.3 From 047007fa9ddff03e1979f16a54cf059f4f592d46 Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Mon, 9 Nov 2009 15:12:33 -0500 Subject: Silence warning: discarding old h --- actionpack/lib/action_view/erb/util.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/actionpack/lib/action_view/erb/util.rb b/actionpack/lib/action_view/erb/util.rb index f767a5e27e..aef859b3ac 100644 --- a/actionpack/lib/action_view/erb/util.rb +++ b/actionpack/lib/action_view/erb/util.rb @@ -23,6 +23,7 @@ class ERB end end + undef :h alias h html_escape module_function :html_escape -- cgit v1.2.3 From d4513ac69958063de3cad9aa655fe9d63e82ec76 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 20:26:46 +0100 Subject: Object#instance_variable_defined? is not needed for Ruby >= 1.8.7 --- .../lib/active_support/core_ext/object/instance_variables.rb | 7 ------- activesupport/test/core_ext/object_and_class_ext_test.rb | 7 ------- 2 files changed, 14 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb index 4ecaab3bbb..866317b17a 100644 --- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb +++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb @@ -1,11 +1,4 @@ class Object - # Available in 1.8.6 and later. - unless respond_to?(:instance_variable_defined?) - def instance_variable_defined?(variable) - instance_variables.include?(variable.to_s) - end - end - # Returns a hash that maps instance variable names without "@" to their # corresponding values. Keys are strings both in Ruby 1.8 and 1.9. # 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 f0121b862d..e6fbdb637b 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -182,13 +182,6 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase assert_equal %w(@bar @baz), @source.instance_variable_names.sort end - def test_instance_variable_defined - assert @source.instance_variable_defined?('@bar') - assert @source.instance_variable_defined?(:@bar) - assert !@source.instance_variable_defined?(:@foo) - assert !@source.instance_variable_defined?('@foo') - end - def test_copy_instance_variables_from_without_explicit_excludes assert_equal [], @dest.instance_variables @dest.copy_instance_variables_from(@source) -- cgit v1.2.3 From 1979e9c8553f4d7905822fdcc99e52d179e78c3c Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 21:11:26 +0100 Subject: Symbol#to_proc is not needed for Ruby >= 1.8.7 --- actionpack/test/controller/filters_test.rb | 1 - activerecord/lib/active_record/base.rb | 1 - activeresource/test/cases/base/load_test.rb | 1 - activesupport/lib/active_support/core_ext/symbol.rb | 1 - .../lib/active_support/core_ext/symbol/to_proc.rb | 14 -------------- activesupport/lib/active_support/ruby/shim.rb | 2 -- activesupport/test/core_ext/enumerable_test.rb | 1 - activesupport/test/core_ext/symbol_test.rb | 9 --------- activesupport/test/dependencies_test.rb | 1 - 9 files changed, 31 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/symbol.rb delete mode 100644 activesupport/lib/active_support/core_ext/symbol/to_proc.rb delete mode 100644 activesupport/test/core_ext/symbol_test.rb diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index 2da97a9d86..8445428e8f 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'active_support/core_ext/symbol' class ActionController::Base class << self diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 4e6090458a..056f29f029 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -12,7 +12,6 @@ require 'active_support/core_ext/hash/deep_merge' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/string/behavior' -require 'active_support/core_ext/symbol' require 'active_support/core_ext/object/metaclass' module ActiveRecord #:nodoc: diff --git a/activeresource/test/cases/base/load_test.rb b/activeresource/test/cases/base/load_test.rb index 189a4d81fe..7745a9439b 100644 --- a/activeresource/test/cases/base/load_test.rb +++ b/activeresource/test/cases/base/load_test.rb @@ -1,7 +1,6 @@ require 'abstract_unit' require "fixtures/person" require "fixtures/street_address" -require 'active_support/core_ext/symbol' require 'active_support/core_ext/hash/conversions' module Highrise diff --git a/activesupport/lib/active_support/core_ext/symbol.rb b/activesupport/lib/active_support/core_ext/symbol.rb deleted file mode 100644 index c103cd9dcf..0000000000 --- a/activesupport/lib/active_support/core_ext/symbol.rb +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 520369452b..0000000000 --- a/activesupport/lib/active_support/core_ext/symbol/to_proc.rb +++ /dev/null @@ -1,14 +0,0 @@ -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 diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index 37c57c485a..43e7ffc938 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -9,7 +9,6 @@ # 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' @@ -20,5 +19,4 @@ 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' diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 4170de3dce..a8e98891d3 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -1,6 +1,5 @@ require 'abstract_unit' require 'active_support/core_ext/array' -require 'active_support/core_ext/symbol' require 'active_support/core_ext/enumerable' Payment = Struct.new(:price) diff --git a/activesupport/test/core_ext/symbol_test.rb b/activesupport/test/core_ext/symbol_test.rb deleted file mode 100644 index 1eaccb9965..0000000000 --- a/activesupport/test/core_ext/symbol_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'abstract_unit' - -class SymbolTests < Test::Unit::TestCase - def test_to_proc - assert_equal %w(one two three), [:one, :two, :three].map(&:to_s) - assert_equal(%w(one two three), - {1 => "one", 2 => "two", 3 => "three"}.sort_by(&:first).map(&:last)) - end -end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 97d70cf8c4..0fcf1eaf00 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -3,7 +3,6 @@ require 'pp' require 'active_support/dependencies' require 'active_support/core_ext/module/loading' require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/symbol/to_proc' module ModuleWithMissing mattr_accessor :missing_count -- cgit v1.2.3 From f8e713f488bba264ba73251b56ad56385b8ed824 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 21:23:19 +0100 Subject: Object#tap is not needed for Ruby >= 1.8.7 --- actionpack/lib/action_dispatch/http/request.rb | 1 - .../lib/active_record/attribute_methods/dirty.rb | 2 -- activesupport/lib/active_support/core_ext/object/misc.rb | 1 - activesupport/lib/active_support/core_ext/object/tap.rb | 16 ---------------- activesupport/lib/active_support/ruby/shim.rb | 2 -- activesupport/test/core_ext/object_ext_test.rb | 9 --------- 6 files changed, 31 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/object/tap.rb delete mode 100644 activesupport/test/core_ext/object_ext_test.rb diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index c24b404e2f..b3bb8c623f 100755 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -5,7 +5,6 @@ require 'strscan' require 'active_support/memoizable' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/hash/indifferent_access' -require 'active_support/core_ext/object/tap' require 'active_support/core_ext/string/access' module ActionDispatch diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 4df0f1af69..4a3ab9ea82 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/object/tap' - module ActiveRecord module AttributeMethods module Dirty diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index 80011dfbed..3e3af03cc5 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -1,3 +1,2 @@ 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/tap.rb b/activesupport/lib/active_support/core_ext/object/tap.rb deleted file mode 100644 index db7e715e2d..0000000000 --- a/activesupport/lib/active_support/core_ext/object/tap.rb +++ /dev/null @@ -1,16 +0,0 @@ -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/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index 43e7ffc938..1f47c04826 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -5,7 +5,6 @@ # 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 @@ -15,7 +14,6 @@ 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' diff --git a/activesupport/test/core_ext/object_ext_test.rb b/activesupport/test/core_ext/object_ext_test.rb deleted file mode 100644 index 04c19ed2aa..0000000000 --- a/activesupport/test/core_ext/object_ext_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/object/metaclass' - -class ObjectExtTest < Test::Unit::TestCase - def test_tap_yields_and_returns_self - foo = Object.new - assert_equal foo, foo.tap { |x| assert_equal foo, x; :bar } - end -end -- cgit v1.2.3 From 004db18cb0f690486336f0fa141ad383c79f9558 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 21:27:58 +0100 Subject: String#bytesize is not needed for Ruby >= 1.8.7 --- actionpack/lib/action_controller/metal/streaming.rb | 2 -- activesupport/lib/active_support/core_ext/string/bytesize.rb | 5 ----- activesupport/lib/active_support/core_ext/string/interpolation.rb | 1 - activesupport/lib/active_support/message_verifier.rb | 2 -- activesupport/test/core_ext/string_ext_test.rb | 7 ------- 5 files changed, 17 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/string/bytesize.rb diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index 4761763a26..43c661bef4 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/string/bytesize' - module ActionController #:nodoc: # Methods for sending arbitrary data and for streaming files to the browser, # instead of rendering. diff --git a/activesupport/lib/active_support/core_ext/string/bytesize.rb b/activesupport/lib/active_support/core_ext/string/bytesize.rb deleted file mode 100644 index ed051b921e..0000000000 --- a/activesupport/lib/active_support/core_ext/string/bytesize.rb +++ /dev/null @@ -1,5 +0,0 @@ -unless '1.9'.respond_to?(:bytesize) - class String - alias :bytesize :size - end -end diff --git a/activesupport/lib/active_support/core_ext/string/interpolation.rb b/activesupport/lib/active_support/core_ext/string/interpolation.rb index d9159b690a..41a061c1a4 100644 --- a/activesupport/lib/active_support/core_ext/string/interpolation.rb +++ b/activesupport/lib/active_support/core_ext/string/interpolation.rb @@ -6,7 +6,6 @@ =end if RUBY_VERSION < '1.9' - require 'active_support/core_ext/string/bytesize' # KeyError is raised by String#% when the string contains a named placeholder # that is not contained in the given arguments hash. Ruby 1.9 includes and diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index 282346b1a6..87e4b1ad33 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/string/bytesize' - module ActiveSupport # MessageVerifier makes it easy to generate and verify messages which are signed # to prevent tampering. diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 584a41b631..0f988e78a4 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -350,13 +350,6 @@ class TestGetTextString < Test::Unit::TestCase end end -class StringBytesizeTest < Test::Unit::TestCase - def test_bytesize - assert_respond_to 'foo', :bytesize - assert_equal 3, 'foo'.bytesize - end -end - class OutputSafetyTest < ActiveSupport::TestCase def setup @string = "hello" -- cgit v1.2.3 From c0bb4c6ed2f5a5676569746e7bfd70405346ef8f Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 21:35:43 +0100 Subject: String#start_with? and String#end_with? are not needed for Ruby >= 1.8.7, leaves their plural aliases though --- .../lib/active_support/core_ext/string/starts_ends_with.rb | 14 -------------- activesupport/test/core_ext/string_ext_test.rb | 8 -------- 2 files changed, 22 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb index f65bb8f75b..641acf62d0 100644 --- a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb +++ b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb @@ -1,18 +1,4 @@ class String - unless '1.8.7 and up'.respond_to?(:start_with?) - # Does the string start with the specified +prefix+? - def start_with?(prefix) - prefix = prefix.to_s - self[0, prefix.length] == prefix - end - - # Does the string end with the specified +suffix+? - def end_with?(suffix) - suffix = suffix.to_s - self[-suffix.length, suffix.length] == suffix - end - end - alias_method :starts_with?, :start_with? alias_method :ends_with?, :end_with? end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 0f988e78a4..dd9e9e0ebb 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -185,17 +185,9 @@ class StringInflectionsTest < Test::Unit::TestCase assert s.starts_with?('hel') assert !s.starts_with?('el') - assert s.start_with?('h') - assert s.start_with?('hel') - assert !s.start_with?('el') - assert s.ends_with?('o') assert s.ends_with?('lo') assert !s.ends_with?('el') - - assert s.end_with?('o') - assert s.end_with?('lo') - assert !s.end_with?('el') end def test_string_squish -- cgit v1.2.3 From b6598c683bb8f8ef484f54755cced77a5d6200bb Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 21:39:32 +0100 Subject: String#each_char is not needed for Ruby >= 1.8.7 --- activesupport/lib/active_support/core_ext/string.rb | 1 - .../lib/active_support/core_ext/string/iterators.rb | 13 ------------- activesupport/test/core_ext/string_ext_test.rb | 11 ----------- 3 files changed, 25 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/string/iterators.rb diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb index 6c52f12712..0365b6af1c 100644 --- a/activesupport/lib/active_support/core_ext/string.rb +++ b/activesupport/lib/active_support/core_ext/string.rb @@ -4,7 +4,6 @@ require 'active_support/core_ext/string/multibyte' require 'active_support/core_ext/string/starts_ends_with' require 'active_support/core_ext/string/inflections' require 'active_support/core_ext/string/access' -require 'active_support/core_ext/string/iterators' require 'active_support/core_ext/string/xchar' require 'active_support/core_ext/string/behavior' require 'active_support/core_ext/string/interpolation' diff --git a/activesupport/lib/active_support/core_ext/string/iterators.rb b/activesupport/lib/active_support/core_ext/string/iterators.rb deleted file mode 100644 index 2f8aa84024..0000000000 --- a/activesupport/lib/active_support/core_ext/string/iterators.rb +++ /dev/null @@ -1,13 +0,0 @@ -unless '1.9'.respond_to?(:each_char) - 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 - require 'strscan' unless defined? ::StringScanner - scanner, char = ::StringScanner.new(self), /./mu - while c = scanner.scan(char) - yield c - end - end - end -end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index dd9e9e0ebb..ffcd086716 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -206,17 +206,6 @@ class StringInflectionsTest < Test::Unit::TestCase # And changes the original string: assert_equal original, expected end - - if RUBY_VERSION < '1.9' - def test_each_char_with_utf8_string_when_kcode_is_utf8 - with_kcode('UTF8') do - '€2.99'.each_char do |char| - assert_not_equal 1, char.length - break - end - end - end - end end class StringBehaviourTest < Test::Unit::TestCase -- cgit v1.2.3 From 329e7f44417c00a8d6fee337c288a463e9d64346 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 21:46:16 +0100 Subject: Integer#even? and Integer#odd? are not needed for Ruby >= 1.8.7 --- activerecord/lib/active_record/validations.rb | 2 -- activesupport/lib/active_support/core_ext/integer.rb | 2 +- .../lib/active_support/core_ext/integer/even_odd.rb | 16 ---------------- .../lib/active_support/core_ext/integer/multiple.rb | 6 ++++++ activesupport/lib/active_support/ruby/shim.rb | 2 -- activesupport/test/core_ext/integer_ext_test.rb | 16 ---------------- 6 files changed, 7 insertions(+), 37 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/integer/even_odd.rb create mode 100644 activesupport/lib/active_support/core_ext/integer/multiple.rb diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 0365cb592f..e8a2a72735 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/integer/even_odd' - module ActiveRecord # Raised by save! and create! when the record is invalid. Use the # +record+ method to retrieve the record which did not validate. diff --git a/activesupport/lib/active_support/core_ext/integer.rb b/activesupport/lib/active_support/core_ext/integer.rb index 7ba018ed7f..a44a1b4c74 100644 --- a/activesupport/lib/active_support/core_ext/integer.rb +++ b/activesupport/lib/active_support/core_ext/integer.rb @@ -1,3 +1,3 @@ -require 'active_support/core_ext/integer/even_odd' +require 'active_support/core_ext/integer/multiple' require 'active_support/core_ext/integer/inflections' require 'active_support/core_ext/integer/time' diff --git a/activesupport/lib/active_support/core_ext/integer/even_odd.rb b/activesupport/lib/active_support/core_ext/integer/even_odd.rb deleted file mode 100644 index 8f9a97b44c..0000000000 --- a/activesupport/lib/active_support/core_ext/integer/even_odd.rb +++ /dev/null @@ -1,16 +0,0 @@ -class Integer - # Check whether the integer is evenly divisible by the argument. - def multiple_of?(number) - self % number == 0 - end - - # Is the integer a multiple of 2? - def even? - multiple_of? 2 - end unless method_defined?(:even?) - - # Is the integer not a multiple of 2? - def odd? - !even? - end unless method_defined?(:odd?) -end diff --git a/activesupport/lib/active_support/core_ext/integer/multiple.rb b/activesupport/lib/active_support/core_ext/integer/multiple.rb new file mode 100644 index 0000000000..40bea54c67 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/integer/multiple.rb @@ -0,0 +1,6 @@ +class Integer + # Check whether the integer is evenly divisible by the argument. + def multiple_of?(number) + self % number == 0 + end +end diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index 1f47c04826..f811239077 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -4,7 +4,6 @@ # Date next_year, next_month # DateTime to_date, to_datetime, xmlschema # Enumerable group_by, each_with_object, none? -# Integer even?, odd? # Process Process.daemon # REXML security fix # String ord @@ -13,7 +12,6 @@ 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/process/daemon' require 'active_support/core_ext/string/conversions' require 'active_support/core_ext/rexml' diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb index 956ae5189d..e1591089f5 100644 --- a/activesupport/test/core_ext/integer_ext_test.rb +++ b/activesupport/test/core_ext/integer_ext_test.rb @@ -2,22 +2,6 @@ require 'abstract_unit' require 'active_support/core_ext/integer' class IntegerExtTest < Test::Unit::TestCase - def test_even - assert [ -2, 0, 2, 4 ].all? { |i| i.even? } - assert ![ -1, 1, 3 ].all? { |i| i.even? } - - assert 22953686867719691230002707821868552601124472329079.odd? - assert !22953686867719691230002707821868552601124472329079.even? - assert 22953686867719691230002707821868552601124472329080.even? - assert !22953686867719691230002707821868552601124472329080.odd? - end - - def test_odd - assert ![ -2, 0, 2, 4 ].all? { |i| i.odd? } - assert [ -1, 1, 3 ].all? { |i| i.odd? } - assert 1000000000000000000000000000000000000000000000000000000001.odd? - end - def test_multiple_of [ -7, 0, 7, 14 ].each { |i| assert i.multiple_of?(7) } [ -7, 7, 14 ].each { |i| assert ! i.multiple_of?(6) } -- cgit v1.2.3 From db2c0d79e3f9ba4fa921b7a122e9e7849729de64 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 22:05:31 +0100 Subject: Enumerable#none? is not needed for Ruby >= 1.8.7 --- activesupport/lib/active_support/core_ext/enumerable.rb | 9 --------- activesupport/test/core_ext/enumerable_test.rb | 11 ----------- 2 files changed, 20 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 15a303cf04..b11c916f61 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -101,15 +101,6 @@ module Enumerable size = block_given? ? select(&block).size : self.size size > 1 end - - # Returns true if none of the elements match the given block. - # - # success = responses.none? {|r| r.status / 100 == 5 } - # - # This is a builtin method in Ruby 1.8.7 and later. - def none?(&block) - !any?(&block) - end unless [].respond_to?(:none?) end class Range #:nodoc: diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index a8e98891d3..66f5f9fbde 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -89,15 +89,4 @@ class EnumerableTests < Test::Unit::TestCase assert ![ 1, 2 ].many? {|x| x > 1 } assert [ 1, 2, 2 ].many? {|x| x > 1 } end - - def test_none - assert [].none? - assert [nil, false].none? - assert ![1].none? - - assert [].none? {|x| x > 1 } - assert ![ 2 ].none? {|x| x > 1 } - assert ![ 1, 2 ].none? {|x| x > 1 } - assert [ 1, 1 ].none? {|x| x > 1 } - end end -- cgit v1.2.3 From a48f49e56bf53e0a2386da898576ef12d5258358 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Nov 2009 22:14:21 +0100 Subject: the REXML security fix is not needed for Ruby >= 1.8.7 --- activesupport/lib/active_support/core_ext/rexml.rb | 43 ---------------------- activesupport/lib/active_support/ruby/shim.rb | 2 - 2 files changed, 45 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/rexml.rb diff --git a/activesupport/lib/active_support/core_ext/rexml.rb b/activesupport/lib/active_support/core_ext/rexml.rb deleted file mode 100644 index 5288b639a6..0000000000 --- a/activesupport/lib/active_support/core_ext/rexml.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'active_support/core_ext/kernel/reporting' - -# Fixes the rexml vulnerability disclosed at: -# http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/ -# This fix is identical to rexml-expansion-fix version 1.0.1 -require 'rexml/rexml' - -# Earlier versions of rexml defined REXML::Version, newer ones REXML::VERSION -unless (defined?(REXML::VERSION) ? REXML::VERSION : REXML::Version) > "3.1.7.2" - silence_warnings { require 'rexml/document' } - - # REXML in 1.8.7 has the patch but early patchlevels didn't update Version from 3.1.7.2. - unless REXML::Document.respond_to?(:entity_expansion_limit=) - silence_warnings { require 'rexml/entity' } - - module REXML #:nodoc: - class Entity < Child #:nodoc: - undef_method :unnormalized - def unnormalized - document.record_entity_expansion! if document - v = value() - return nil if v.nil? - @unnormalized = Text::unnormalize(v, parent) - @unnormalized - end - end - class Document < Element #:nodoc: - @@entity_expansion_limit = 10_000 - def self.entity_expansion_limit= val - @@entity_expansion_limit = val - end - - def record_entity_expansion! - @number_of_expansions ||= 0 - @number_of_expansions += 1 - if @number_of_expansions > @@entity_expansion_limit - raise "Number of entity expansions exceeded, processing aborted." - end - end - end - end - end -end diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index f811239077..af6e8aa91e 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -5,7 +5,6 @@ # DateTime to_date, to_datetime, xmlschema # Enumerable group_by, each_with_object, none? # Process Process.daemon -# REXML security fix # String ord # Time to_date, to_time, to_datetime require 'active_support' @@ -14,5 +13,4 @@ require 'active_support/core_ext/date_time/conversions' require 'active_support/core_ext/enumerable' 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/time/conversions' -- cgit v1.2.3 From d5fd09246edbaf2d73ee13dabf2b7b378203a530 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 13:27:58 -0800 Subject: Bump AP gem dependencies to upgrade Rack to 1.0.1 and to include rack-mount and erubis. --- actionpack/actionpack.gemspec | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 1930416358..ae5985120e 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -16,8 +16,10 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', '= 3.0.pre') s.add_dependency('activemodel', '= 3.0.pre') - s.add_dependency('rack', '~> 1.0.0') - s.add_dependency('rack-test', '~> 0.5.0') + s.add_dependency('rack', '~> 1.0.1') + s.add_dependency('rack-test', '~> 0.5.0') + s.add_dependency('rack-mount', '~> 0.0.1') + s.add_dependency('erubis', '~> 2.6.0') s.require_path = 'lib' s.autorequire = 'action_controller' -- cgit v1.2.3 From a66449d85255fc3ec69aa842b8059f954d7b76e2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 14:36:49 -0800 Subject: Ruby 1.9.2: work around inherited hook being called before yielding to block --- railties/test/generators_test.rb | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 9c9a4e6016..5579e0f40d 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -165,15 +165,13 @@ class GeneratorsTest < GeneratorsTestCase def test_developer_options_are_overwriten_by_user_options Rails::Generators.options[:new_generator] = { :generate => false } - klass = Class.new(Rails::Generators::Base) do - def self.name - "NewGenerator" + self.class.class_eval <<-end_eval + class NewGenerator < Rails::Generators::Base + class_option :generate, :default => true end + end_eval - class_option :generate, :default => true - end - - assert_equal false, klass.class_options[:generate].default + assert_equal false, NewGenerator.class_options[:generate].default end def test_source_paths_for_not_namespaced_generators -- cgit v1.2.3 From 0ac88af998ead6c77d05f669e3494fed25bb6103 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 16:10:37 -0800 Subject: Remark when bundled env require fails --- actionpack/test/abstract_unit.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 214d79cd87..5b7dc2d4fc 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -2,6 +2,7 @@ root = File.expand_path('../../..', __FILE__) begin require "#{root}/vendor/gems/environment" rescue LoadError + $stderr.puts "Missing bundled environment, continuing: #{$!}" $:.unshift "#{root}/activesupport/lib" $:.unshift "#{root}/activemodel/lib" end -- cgit v1.2.3 From eeac054d59dd9373313596dc3ef9db30c4b227d5 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 16:57:10 -0800 Subject: Fix missing dependency --- activesupport/test/core_ext/string_ext_test.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index ffcd086716..1e8a1c4f08 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -5,6 +5,7 @@ require 'inflector_test_cases' require 'active_support/core_ext/string' require 'active_support/core_ext/time' +require 'active_support/core_ext/kernel/reporting' class StringInflectionsTest < Test::Unit::TestCase include InflectorTestCases -- cgit v1.2.3 From feaa762e40e7ca7fd9b43172dea92b14ed6b3584 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 16:59:38 -0800 Subject: Ditto --- activesupport/test/multibyte_utils_test.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/test/multibyte_utils_test.rb b/activesupport/test/multibyte_utils_test.rb index 0a2f20d282..1dff944922 100644 --- a/activesupport/test/multibyte_utils_test.rb +++ b/activesupport/test/multibyte_utils_test.rb @@ -2,6 +2,7 @@ require 'abstract_unit' require 'multibyte_test_helpers' +require 'active_support/core_ext/kernel/reporting' class MultibyteUtilsTest < ActiveSupport::TestCase include MultibyteTestHelpers -- cgit v1.2.3 From 703d31c20a7b531053d5c009972a89e857b07376 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 17:01:57 -0800 Subject: Clarify failed assertion --- activerecord/test/cases/relations_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 4833d04aff..1a2c8030fb 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -78,7 +78,7 @@ class RelationTest < ActiveRecord::TestCase relation = Topic.all ["map", "uniq", "sort", "insert", "delete", "update"].each do |method| - assert relation.respond_to?(method) + assert relation.respond_to?(method), "Topic.all should respond to #{method.inspect}" end end -- cgit v1.2.3 From 08f7c4dd8951053c443371f786be59d04448c225 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 19:30:02 -0800 Subject: Revert "the REXML security fix is not needed for Ruby >= 1.8.7" Still required on older 1.8.7 patchlevels. This reverts commit a48f49e56bf53e0a2386da898576ef12d5258358. --- activesupport/lib/active_support/core_ext/rexml.rb | 43 ++++++++++++++++++++++ activesupport/lib/active_support/ruby/shim.rb | 2 + 2 files changed, 45 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/rexml.rb diff --git a/activesupport/lib/active_support/core_ext/rexml.rb b/activesupport/lib/active_support/core_ext/rexml.rb new file mode 100644 index 0000000000..5288b639a6 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/rexml.rb @@ -0,0 +1,43 @@ +require 'active_support/core_ext/kernel/reporting' + +# Fixes the rexml vulnerability disclosed at: +# http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/ +# This fix is identical to rexml-expansion-fix version 1.0.1 +require 'rexml/rexml' + +# Earlier versions of rexml defined REXML::Version, newer ones REXML::VERSION +unless (defined?(REXML::VERSION) ? REXML::VERSION : REXML::Version) > "3.1.7.2" + silence_warnings { require 'rexml/document' } + + # REXML in 1.8.7 has the patch but early patchlevels didn't update Version from 3.1.7.2. + unless REXML::Document.respond_to?(:entity_expansion_limit=) + silence_warnings { require 'rexml/entity' } + + module REXML #:nodoc: + class Entity < Child #:nodoc: + undef_method :unnormalized + def unnormalized + document.record_entity_expansion! if document + v = value() + return nil if v.nil? + @unnormalized = Text::unnormalize(v, parent) + @unnormalized + end + end + class Document < Element #:nodoc: + @@entity_expansion_limit = 10_000 + def self.entity_expansion_limit= val + @@entity_expansion_limit = val + end + + def record_entity_expansion! + @number_of_expansions ||= 0 + @number_of_expansions += 1 + if @number_of_expansions > @@entity_expansion_limit + raise "Number of entity expansions exceeded, processing aborted." + end + end + end + end + end +end diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index af6e8aa91e..f811239077 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -5,6 +5,7 @@ # DateTime to_date, to_datetime, xmlschema # Enumerable group_by, each_with_object, none? # Process Process.daemon +# REXML security fix # String ord # Time to_date, to_time, to_datetime require 'active_support' @@ -13,4 +14,5 @@ require 'active_support/core_ext/date_time/conversions' require 'active_support/core_ext/enumerable' 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/time/conversions' -- cgit v1.2.3 From 1004fcb76761aa42ff18d8aa373614a41a259d3c Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 21:37:37 -0600 Subject: Fixed AD assertion autoloads [#3470 state:resolved] --- actionpack/lib/action_dispatch/testing/assertions.rb | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb index 96f08f2355..0e4a92048f 100644 --- a/actionpack/lib/action_dispatch/testing/assertions.rb +++ b/actionpack/lib/action_dispatch/testing/assertions.rb @@ -1,8 +1,21 @@ module ActionDispatch module Assertions - %w(response selector tag dom routing model).each do |kind| - require "action_dispatch/testing/assertions/#{kind}" - include const_get("#{kind.camelize}Assertions") + autoload :DomAssertions, 'action_dispatch/testing/assertions/dom' + autoload :ModelAssertions, 'action_dispatch/testing/assertions/model' + autoload :ResponseAssertions, 'action_dispatch/testing/assertions/response' + autoload :RoutingAssertions, 'action_dispatch/testing/assertions/routing' + autoload :SelectorAssertions, 'action_dispatch/testing/assertions/selector' + autoload :TagAssertions, 'action_dispatch/testing/assertions/tag' + + extend ActiveSupport::Concern + + included do + include DomAssertions + include ModelAssertions + include ResponseAssertions + include RoutingAssertions + include SelectorAssertions + include TagAssertions end end end -- cgit v1.2.3 From 763489ce064b92609634638c93022b6916976e4f Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 21:54:50 -0600 Subject: Add pending test for route generation with default param --- actionpack/test/controller/routing_test.rb | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index bb0b9247f3..71ae17a418 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1645,6 +1645,22 @@ class RouteSetTest < ActiveSupport::TestCase assert_uri_equal '/foo?x=hello+world', default_route_set.generate({:controller => 'foo', :x => 'hello world'}) end + def test_generate_with_default_params + set.draw do |map| + map.connect 'dummy/page/:page', :controller => 'dummy' + map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots' + map.connect 'ibocorp/:page', :controller => 'ibocorp', + :requirements => { :page => /\d+/ }, + :defaults => { :page => 1 } + + map.connect ':controller/:action/:id' + end + + pending do + assert_equal '/ibocorp', set.generate({:controller => 'ibocorp', :page => 1}) + end + end + private def assert_uri_equal(expected, actual) assert_equal(sort_query_string_params(expected), sort_query_string_params(actual)) -- cgit v1.2.3 From 3ce6a10b67b8a683c2543b29ac71102ca452e8b8 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 9 Nov 2009 20:09:55 -0800 Subject: Contortions to work around brittle naming dependency --- railties/lib/rails/generators/base.rb | 52 +++++++++++++++++------------------ railties/test/generators_test.rb | 11 ++++---- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index a64005497b..226ae63963 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -25,8 +25,11 @@ module Rails # Automatically sets the source root based on the class name. # def self.source_root - @_rails_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), - base_name, generator_name, 'templates')) + @_rails_source_root ||= begin + if base_name && generator_name + File.expand_path(File.join(File.dirname(__FILE__), base_name, generator_name, 'templates')) + end + end end # Tries to get the description from a USAGE file one folder above the source @@ -216,7 +219,7 @@ module Rails # and can point to wrong directions when inside an specified directory. base.source_root - if base.name && base.name !~ /Base$/ && defined?(Rails.root) && Rails.root + if base.name && base.name !~ /Base$/ && base.base_name && base.generator_name && defined?(Rails.root) && Rails.root path = File.expand_path(File.join(Rails.root, 'lib', 'templates')) if base.name.include?('::') base.source_paths << File.join(path, base.base_name, base.generator_name) @@ -276,8 +279,10 @@ module Rails # Sets the base_name taking into account the current class namespace. # def self.base_name - if name - @base_name ||= name.split('::').first.underscore + @base_name ||= begin + if base = name.to_s.split('::').first + base.underscore + end end end @@ -287,9 +292,10 @@ module Rails def self.generator_name if name @generator_name ||= begin - klass_name = name.to_s.split('::').last - klass_name.sub!(/Generator$/, '') - klass_name.underscore + if klass_name = name.to_s.split('::').last + klass_name.sub!(/Generator$/, '') + klass_name.underscore + end end end end @@ -298,35 +304,27 @@ module Rails # Rails::Generators.options. # def self.default_value_for_option(name, options) - config = Rails::Generators.options - generator, base = generator_name.to_sym, base_name.to_sym - - if config[generator] && config[generator].key?(name) - config[generator][name] - elsif config[base] && config[base].key?(name) - config[base][name] - elsif config[:rails].key?(name) - config[:rails][name] - else - options[:default] - end + default_for_option(Rails::Generators.options, name, options, options[:default]) end # Return default aliases for the option name given doing a lookup in # Rails::Generators.aliases. # def self.default_aliases_for_option(name, options) - config = Rails::Generators.aliases - generator, base = generator_name.to_sym, base_name.to_sym + default_for_option(Rails::Generators.aliases, name, options, options[:aliases]) + end - if config[generator] && config[generator].key?(name) - config[generator][name] - elsif config[base] && config[base].key?(name) - config[base][name] + # Return default for the option name given doing a lookup in config. + # + def self.default_for_option(config, name, options, default) + if generator_name and c = config[generator_name.to_sym] and c.key?(name) + c[name] + elsif base_name and c = config[base_name.to_sym] and c.key?(name) + c[name] elsif config[:rails].key?(name) config[:rails][name] else - options[:aliases] + default end end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 5579e0f40d..a8716d9992 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -165,13 +165,12 @@ class GeneratorsTest < GeneratorsTestCase def test_developer_options_are_overwriten_by_user_options Rails::Generators.options[:new_generator] = { :generate => false } - self.class.class_eval <<-end_eval - class NewGenerator < Rails::Generators::Base - class_option :generate, :default => true - end - end_eval + klass = Class.new(Rails::Generators::Base) do + def self.name() 'NewGenerator' end + class_option :generate, :default => true + end - assert_equal false, NewGenerator.class_options[:generate].default + assert_equal false, klass.class_options[:generate].default end def test_source_paths_for_not_namespaced_generators -- cgit v1.2.3 From e9d21ca903adbcfaae5ac37a1a46dbb285cd6761 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:17:38 -0600 Subject: Add pending test for generating routes with optional params that recall last request --- actionpack/test/controller/routing_test.rb | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 71ae17a418..3971aacadb 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1661,6 +1661,42 @@ class RouteSetTest < ActiveSupport::TestCase end end + def test_generate_with_optional_params_recalls_last_request + set.draw do |map| + map.connect "blog/", :controller => "blog", :action => "index" + + map.connect "blog/:year/:month/:day", + :controller => "blog", + :action => "show_date", + :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/ }, + :day => nil, :month => nil + + map.connect "blog/show/:id", :controller => "blog", :action => "show", :id => /\d+/ + map.connect "blog/:controller/:action/:id" + map.connect "*anything", :controller => "blog", :action => "unknown_request" + end + + assert_equal({:controller => "blog", :action => "index"}, set.recognize_path("/blog")) + assert_equal({:controller => "blog", :action => "show", :id => "123"}, set.recognize_path("/blog/show/123")) + assert_equal({:controller => "blog", :action => "show_date", :year => "2004"}, set.recognize_path("/blog/2004")) + assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12"}, set.recognize_path("/blog/2004/12")) + assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12", :day => "25"}, set.recognize_path("/blog/2004/12/25")) + assert_equal({:controller => "articles", :action => "edit", :id => "123"}, set.recognize_path("/blog/articles/edit/123")) + assert_equal({:controller => "articles", :action => "show_stats"}, set.recognize_path("/blog/articles/show_stats")) + assert_equal({:controller => "blog", :action => "unknown_request", :anything => ["blog", "wibble"]}, set.recognize_path("/blog/wibble")) + assert_equal({:controller => "blog", :action => "unknown_request", :anything => ["junk"]}, set.recognize_path("/junk")) + + last_request = set.recognize_path("/blog/2006/07/28").freeze + assert_equal({:controller => "blog", :action => "show_date", :year => "2006", :month => "07", :day => "28"}, last_request) + assert_equal("/blog/2006/07/25", set.generate({:day => 25}, last_request)) + assert_equal("/blog/2005", set.generate({:year => 2005}, last_request)) + assert_equal("/blog/show/123", set.generate({:action => "show" , :id => 123}, last_request)) + pending do + assert_equal("/blog/2006/07/28", set.generate({:year => 2006}, last_request)) + end + assert_equal("/blog/2006", set.generate({:year => 2006, :month => nil}, last_request)) + end + private def assert_uri_equal(expected, actual) assert_equal(sort_query_string_params(expected), sort_query_string_params(actual)) -- cgit v1.2.3 From f03bcf249527ba4945fdce673bae971a9ac11bb7 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:30:26 -0600 Subject: Don't load all of railties just for Rails::Version --- railties/Rakefile | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/railties/Rakefile b/railties/Rakefile index 3a87a88ddc..1280ad7f06 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -6,12 +6,8 @@ require 'rake/gempackagetask' require 'date' require 'rbconfig' -begin - require File.expand_path('../../vendor/gems/environment', __FILE__) -rescue LoadError -end $LOAD_PATH.unshift "#{File.dirname(__FILE__)}/lib" -require 'rails' +require 'rails/version' PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' PKG_NAME = ENV['PKG_NAME'] || 'rails' @@ -30,7 +26,7 @@ task :default => :test ## This is required until the regular test task ## below passes. It's not ideal, but at least ## we can see the failures -task :test do +task :test do dir = ENV["TEST_DIR"] || "**" Dir["test/#{dir}/*_test.rb"].all? do |file| next true if file.include?("fixtures") @@ -152,7 +148,7 @@ end # Publishing ------------------------------------------------------- desc "Publish the rails gem" -task :pgem => [:gem] do +task :pgem => [:gem] do require 'rake/contrib/sshpublisher' Rake::SshFilePublisher.new("gems.rubyonrails.org", "/u/sites/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload `ssh gems.rubyonrails.org '/u/sites/gems/gemupdate.sh'` -- cgit v1.2.3 From 335c0e62cd1e809a79e209977a62dba2e583cb88 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:36:30 -0600 Subject: Fix railties isolated tests if bundler environment doesn't exist --- railties/test/isolation/abstract_unit.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 462a4d8dea..0b479e944c 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -157,9 +157,13 @@ Module.new do FileUtils.mkdir(tmp_path) environment = File.expand_path('../../../../vendor/gems/environment', __FILE__) + if File.exist?(environment) + require_environment = "-r #{environment}" + end - `#{Gem.ruby} -r #{environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{tmp_path('app_template')}` + `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{tmp_path('app_template')}` File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f| - f.puts "require '#{environment}' ; require 'rails'" + f.puts "require '#{environment}'" if require_environment + f.puts "require 'rails'" end end -- cgit v1.2.3 From 94058c689a1ad74ccc6df2732c360fcdea267cae Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:44:28 -0600 Subject: Remove automatic rubygems loading from AS test runner --- activesupport/test/abstract_unit.rb | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index f390c66838..8967b54537 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -7,16 +7,8 @@ rescue LoadError $:.unshift("#{root}/activerecord/lib") end - require 'test/unit' - -begin - require 'mocha' -rescue LoadError - $stderr.puts 'Loading rubygems' - require 'rubygems' - require 'mocha' -end +require 'mocha' ENV['NO_RELOAD'] = '1' require 'active_support' -- cgit v1.2.3 From a31ecff554c9ef18af5ee85d57f8d10f9f31b320 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:51:48 -0600 Subject: Don't warn me if I'm not using bundler to run tests --- actionpack/test/abstract_unit.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 5b7dc2d4fc..214d79cd87 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -2,7 +2,6 @@ root = File.expand_path('../../..', __FILE__) begin require "#{root}/vendor/gems/environment" rescue LoadError - $stderr.puts "Missing bundled environment, continuing: #{$!}" $:.unshift "#{root}/activesupport/lib" $:.unshift "#{root}/activemodel/lib" end -- cgit v1.2.3 From 22b581e04cb13a1a80768c0487490eec3dd85879 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:56:49 -0600 Subject: Always add AS lib/ to path when running its test suite --- activesupport/test/abstract_unit.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index 8967b54537..d640c9bc63 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -1,12 +1,12 @@ ORIG_ARGV = ARGV.dup -root = File.expand_path('../../..', __FILE__) + begin - require "#{root}/vendor/gems/environment" + require File.expand_path('../../../vendor/gems/environment', __FILE__) rescue LoadError - $:.unshift("#{root}/activesupport/lib") - $:.unshift("#{root}/activerecord/lib") end +$:.unshift(File.dirname(__FILE__) + '/../lib') + require 'test/unit' require 'mocha' -- cgit v1.2.3 From 23229d5ad4cf1c222d4d8c4561fbdff284f9bdee Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 22:59:30 -0600 Subject: Remove preflight lib check during AP tests. Bundler resolves this issue --- actionpack/test/abstract_unit.rb | 6 ------ 1 file changed, 6 deletions(-) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 214d79cd87..32c5743382 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -11,12 +11,6 @@ $:.unshift(File.dirname(__FILE__) + '/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') -begin - %w( rack rack/test sqlite3 ).each { |lib| require lib } -rescue LoadError => e - abort e.message -end - ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp') require 'test/unit' -- cgit v1.2.3 From 11e798ae0f2f46498811282756c9d21df3d4b523 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 23:28:36 -0600 Subject: Avoid adding component lib/ to load path multiple times --- actionmailer/test/abstract_unit.rb | 4 +++- actionpack/test/abstract_unit.rb | 4 +++- activemodel/test/cases/helper.rb | 4 +++- activerecord/test/cases/helper.rb | 4 +++- activeresource/test/abstract_unit.rb | 4 +++- activesupport/test/abstract_unit.rb | 3 ++- 6 files changed, 17 insertions(+), 6 deletions(-) diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index fcbaa9e186..e84b3b0d23 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -4,9 +4,11 @@ begin rescue LoadError $:.unshift("#{root}/activesupport/lib") $:.unshift("#{root}/actionpack/lib") - $:.unshift("#{root}/actionmailer/lib") end +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'rubygems' require 'test/unit' diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 32c5743382..775cfc82bf 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -6,7 +6,9 @@ rescue LoadError $:.unshift "#{root}/activemodel/lib" end -$:.unshift(File.dirname(__FILE__) + '/../lib') +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + $:.unshift(File.dirname(__FILE__) + '/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb index 49783c2735..c1a3f6a4a7 100644 --- a/activemodel/test/cases/helper.rb +++ b/activemodel/test/cases/helper.rb @@ -3,9 +3,11 @@ begin require "#{root}/vendor/gems/environment" rescue LoadError $:.unshift("#{root}/activesupport/lib") - $:.unshift("#{root}/activemodel/lib") end +lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'config' require 'active_model' diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 871cfa6468..25613da912 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -3,9 +3,11 @@ begin require "#{root}/vendor/gems/environment" rescue LoadError $:.unshift("#{root}/activesupport/lib") - $:.unshift("#{root}/activerecord/lib") end +lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'config' require 'rubygems' diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb index ee12f785b5..10849be20c 100644 --- a/activeresource/test/abstract_unit.rb +++ b/activeresource/test/abstract_unit.rb @@ -3,9 +3,11 @@ begin require "#{root}/vendor/gems/environment" rescue LoadError $:.unshift("#{root}/activesupport/lib") - $:.unshift("#{root}/activeresource/lib") end +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'rubygems' require 'test/unit' require 'active_support' diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index d640c9bc63..dda139372e 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -5,7 +5,8 @@ begin rescue LoadError end -$:.unshift(File.dirname(__FILE__) + '/../lib') +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) require 'test/unit' require 'mocha' -- cgit v1.2.3 From d625312fe11bbf53e285a0efd570249f0bf91fd1 Mon Sep 17 00:00:00 2001 From: Matt Jones Date: Sat, 7 Nov 2009 14:00:54 -0500 Subject: delete correct records for a has_many with :primary_key and :dependent => :delete_all Signed-off-by: Michael Koziarski --- activerecord/lib/active_record/associations.rb | 2 +- .../test/cases/associations/has_many_associations_test.rb | 12 ++++++++++++ activerecord/test/cases/reflection_test.rb | 4 ++-- activerecord/test/models/company.rb | 2 ++ 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 03c8d4b3ed..3a5f3ed030 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1480,7 +1480,7 @@ module ActiveRecord if reflection.options.include?(:dependent) # Add polymorphic type if the :as option is present dependent_conditions = [] - dependent_conditions << "#{reflection.primary_key_name} = \#{record.quoted_id}" + dependent_conditions << "#{reflection.primary_key_name} = \#{record.#{reflection.name}.send(:owner_quoted_id)}" dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as] dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.quoted_table_name) if reflection.options[:conditions] dependent_conditions << extra_conditions if extra_conditions diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index b193f8d8ba..86d14c9c81 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -659,6 +659,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 1, Client.find_all_by_client_of(firm.id).size end + def test_delete_all_association_with_primary_key_deletes_correct_records + firm = Firm.find(:first) + # break the vanilla firm_id foreign key + assert_equal 2, firm.clients.count + firm.clients.first.update_attribute(:firm_id, nil) + assert_equal 1, firm.clients(true).count + assert_equal 1, firm.clients_using_primary_key_with_delete_all.count + old_record = firm.clients_using_primary_key_with_delete_all.first + firm = Firm.find(:first) + firm.destroy + assert Client.find_by_id(old_record.id).nil? + end def test_creation_respects_hash_condition ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 99e248743a..acd214eb5a 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -176,8 +176,8 @@ class ReflectionTest < ActiveRecord::TestCase def test_reflection_of_all_associations # FIXME these assertions bust a lot - assert_equal 36, Firm.reflect_on_all_associations.size - assert_equal 26, Firm.reflect_on_all_associations(:has_many).size + assert_equal 37, Firm.reflect_on_all_associations.size + assert_equal 27, Firm.reflect_on_all_associations(:has_many).size assert_equal 10, Firm.reflect_on_all_associations(:has_one).size assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size end diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index 469f5399ae..7e93fda1eb 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -68,6 +68,8 @@ class Firm < Company has_many :readonly_clients, :class_name => 'Client', :readonly => true has_many :clients_using_primary_key, :class_name => 'Client', :primary_key => 'name', :foreign_key => 'firm_name' + has_many :clients_using_primary_key_with_delete_all, :class_name => 'Client', + :primary_key => 'name', :foreign_key => 'firm_name', :dependent => :delete_all has_many :clients_grouped_by_firm_id, :class_name => "Client", :group => "firm_id", :select => "firm_id" has_many :clients_grouped_by_name, :class_name => "Client", :group => "name", :select => "name" -- cgit v1.2.3 From 38e8d5b10c8a7f8084e49f6571759bb424854d03 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 9 Nov 2009 23:42:17 -0600 Subject: Enable warnings for mailer tests --- actionmailer/Rakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile index 96c84b986e..140661ecb0 100644 --- a/actionmailer/Rakefile +++ b/actionmailer/Rakefile @@ -24,7 +24,7 @@ Rake::TestTask.new { |t| t.libs << "test" t.pattern = 'test/*_test.rb' t.verbose = true - t.warning = false + t.warning = true } task :isolated_test do -- cgit v1.2.3 From 7ad6e9bc782df377d500b4ed460c281c6b111e93 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 01:52:40 -0800 Subject: Fix generated performance test helper requires --- .../generators/rails/app/templates/test/performance/browsing_test.rb | 2 +- .../generators/test_unit/performance/templates/performance_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb index 4b60558b43..a3dc38d9e4 100644 --- a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb +++ b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb @@ -1,5 +1,5 @@ require 'test_helper' -require 'performance_test_help' +require 'rails/performance_test_help' # Profiling results for each test method are written to tmp/performance. class BrowsingTest < ActionController::PerformanceTest diff --git a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb index 27c91b0fca..362e3dc09f 100644 --- a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb +++ b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb @@ -1,5 +1,5 @@ require 'test_helper' -require 'performance_test_help' +require 'rails/performance_test_help' class <%= class_name %>Test < ActionController::PerformanceTest # Replace this with your real tests. -- cgit v1.2.3 From 77478f21af980c8879762fc65def8cacba5a7eb7 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 11:00:29 -0800 Subject: Resolve deadlock in pooled connections test --- activerecord/test/cases/pooled_connections_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index f9eea3d118..2529a33dab 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -105,7 +105,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase Thread.new do ActiveRecord::Base.connection.rollback_db_transaction ActiveRecord::Base.connection_pool.release_connection - end.join rescue nil + end add_record('three') end -- cgit v1.2.3 From 5fa497abf5b885187130e58aefcb1c3228295e3c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 11:00:50 -0800 Subject: Ruby 1.9: fix Relation respond_to? and method_missing --- activerecord/lib/active_record/relation.rb | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 6bc56ecf15..5f0eec754f 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -110,19 +110,17 @@ module ActiveRecord end def respond_to?(method) - if @relation.respond_to?(method) || Array.instance_methods.include?(method.to_s) - true - else - super - end + @relation.respond_to?(method) || Array.method_defined?(method) || super end private def method_missing(method, *args, &block) if @relation.respond_to?(method) @relation.send(method, *args, &block) - elsif Array.instance_methods.include?(method.to_s) + elsif Array.method_defined?(method) to_a.send(method, *args, &block) + else + super end end end -- cgit v1.2.3 From 1874a88765f01fa8a67f8af2db6e8511541bc815 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 11:57:56 -0800 Subject: Ruby 1.9: bump CI mysql from 2.7 -> 2.8.1 --- ci/geminstaller.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ci/geminstaller.yml b/ci/geminstaller.yml index a38221884b..ed06cf4342 100644 --- a/ci/geminstaller.yml +++ b/ci/geminstaller.yml @@ -11,8 +11,7 @@ gems: - name: mocha version: >= 0.9.7 - name: mysql - #version: >= 2.7 - version: = 2.7 + version: >= 2.8.1 - name: nokogiri version: >= 1.3.3 - name: pg -- cgit v1.2.3 From 3bdfda073098e37d852e58b6376fd3dcb5e00622 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 13:52:25 -0800 Subject: Bump arel dep to 0.2.pre --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index a60c1010d9..6263587146 100644 --- a/Gemfile +++ b/Gemfile @@ -16,7 +16,7 @@ gem "rack", "1.0.1" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", "~> 0.5.0" gem "erubis", "~> 2.6.0" -gem "arel", "0.1.3", :git => "git://github.com/rails/arel.git" +gem "arel", "0.2.pre", :git => "git://github.com/rails/arel.git" gem "mocha" gem "sqlite3-ruby" gem "RedCloth" -- cgit v1.2.3 From 90be80361f26d717f9842170315dd8659f35429d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:13:21 -0800 Subject: Eliminate warning with layout is unset --- actionpack/lib/abstract_controller/layouts.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 1616f8030a..60bd486763 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -100,7 +100,7 @@ module AbstractController # name, return that string. Otherwise, use the superclass' # layout (which might also be implied) def _write_layout_method - case @_layout + case @_layout ||= nil when String self.class_eval %{def _layout(details) #{@_layout.inspect} end} when Symbol -- cgit v1.2.3 From be664392c030a2a0241616be764725f0e66d872b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:13:54 -0800 Subject: Eliminate warning by initializing nil formats --- actionpack/lib/abstract_controller/rendering_controller.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/actionpack/lib/abstract_controller/rendering_controller.rb b/actionpack/lib/abstract_controller/rendering_controller.rb index 0aae2b18e9..7054b9cf26 100644 --- a/actionpack/lib/abstract_controller/rendering_controller.rb +++ b/actionpack/lib/abstract_controller/rendering_controller.rb @@ -12,6 +12,12 @@ module AbstractController self._view_paths ||= ActionView::PathSet.new end + # Initialize controller with nil formats. + def initialize(*) #:nodoc: + @_formats = nil + super + end + # An instance of a view class. The default view class is ActionView::Base # # The view class must have the following methods: -- cgit v1.2.3 From d887e46c2946eb1619f551420c5d076e31f9f919 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:14:17 -0800 Subject: Be sure to invoke the super chain! And initialize response body. --- actionmailer/lib/action_mailer/base.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 6a5a598f94..bef9bb8e79 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -452,6 +452,8 @@ module ActionMailer #:nodoc: # remain uninitialized (useful when you only need to invoke the "receive" # method, for instance). def initialize(method_name=nil, *parameters) #:nodoc: + @_response_body = nil + super() create!(method_name, *parameters) if method_name end -- cgit v1.2.3 From 457940e68496ca203bcb3c9c5599e4cffef0282c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:17:40 -0800 Subject: Bump CI mocha to 0.9.8 and rack to 1.0.1 --- ci/geminstaller.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/geminstaller.yml b/ci/geminstaller.yml index ed06cf4342..be4acaef57 100644 --- a/ci/geminstaller.yml +++ b/ci/geminstaller.yml @@ -9,7 +9,7 @@ gems: - name: memcache-client version: >= 1.5.0 - name: mocha - version: >= 0.9.7 + version: >= 0.9.8 - name: mysql version: >= 2.8.1 - name: nokogiri @@ -17,7 +17,7 @@ gems: - name: pg version: >= 0.8.0 - name: rack - version: '~> 1.0.0' + version: '~> 1.0.1' - name: rack-test version: >= 0.5.0 - name: rake -- cgit v1.2.3 From a584b4c13dc12ba102182e914e428ea6730cfef2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:59:22 -0800 Subject: Get rack from rails/rack.git. Introduce ci-only deps. --- Gemfile | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/Gemfile b/Gemfile index 6263587146..592fd30b2e 100644 --- a/Gemfile +++ b/Gemfile @@ -1,22 +1,28 @@ clear_sources source 'http://gemcutter.org' +gem "rake", ">= 0.8.7" +gem "mocha", ">= 0.9.8" + gem "rails", "3.0.pre", :vendored_at => "railties" -%w( - activesupport - activemodel - actionpack - actionmailer - activerecord - activeresource -).each do |lib| +%w(activesupport activemodel actionpack actionmailer activerecord activeresource).each do |lib| gem lib, '3.0.pre', :vendored_at => lib end -gem "rack", "1.0.1" -gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" -gem "rack-test", "~> 0.5.0" -gem "erubis", "~> 2.6.0" + +# AR gem "arel", "0.2.pre", :git => "git://github.com/rails/arel.git" -gem "mocha" -gem "sqlite3-ruby" -gem "RedCloth" +gem "sqlite3-ruby", ">= 1.2.5" + +# AP +gem "rack", "1.0.1", :git => "git://github.com/rails/rack.git" +gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" +gem "rack-test", ">= 0.5.0" +gem "erubis", ">= 2.6.5" +gem "RedCloth", ">= 4.2.2" + +only :ci do + gem "fcgi", ">= 0.8.7" + gem "nokogiri", ">= 1.4.0" + gem "memcache-client", ">= 1.7.6" + gem "pg", ">= 0.8.0" +end -- cgit v1.2.3 From 0247262833e8203351c59def564243ee26411b8b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:59:46 -0800 Subject: Rely on bundler for gem deps instead of geminstaller --- ci/geminstaller.yml | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/ci/geminstaller.yml b/ci/geminstaller.yml index be4acaef57..776ae8d98d 100644 --- a/ci/geminstaller.yml +++ b/ci/geminstaller.yml @@ -1,30 +1,8 @@ --- gems: -- name: erubis - version: >= 2.6.5 - name: geminstaller version: >= 0.4.3 -- name: fcgi - version: >= 0.8.7 -- name: memcache-client - version: >= 1.5.0 -- name: mocha - version: >= 0.9.8 -- name: mysql - version: >= 2.8.1 -- name: nokogiri - version: >= 1.3.3 -- name: pg - version: >= 0.8.0 -- name: rack - version: '~> 1.0.1' -- name: rack-test - version: >= 0.5.0 -- name: rake - version: >= 0.8.1 -- name: sqlite3-ruby - version: >= 1.2.2 - name: rubygems-update - version: >= 1.3.3 + version: >= 1.3.5 - name: bundler version: >= 0.6.0 -- cgit v1.2.3 From 74306b952626b1e0198718274b861a64ad2b5eb8 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:59:59 -0800 Subject: Use bundled bin/rake --- ci/ci_build.rb | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 0ee952c00b..cb3be9265b 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -16,6 +16,10 @@ root_dir = File.expand_path('../..', __FILE__) # A security hole, but there is nothing valuable on rails CI box anyway. build_results[:geminstaller] = system "sudo geminstaller --config=#{root_dir}/ci/geminstaller.yml --exceptions" +def rake(*tasks) + tasks.map { |task| system "#{root_dir}/bin/rake", task }.join("\n") +end + cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" @@ -27,8 +31,8 @@ cd "#{root_dir}/activesupport" do puts puts "[CruiseControl] Building ActiveSupport" puts - build_results[:activesupport] = system 'rake' - build_results[:activesupport_isolated] = system 'rake test:isolated' + build_results[:activesupport] = rake + build_results[:activesupport_isolated] = rake 'test:isolated' end rm_f "#{root_dir}/activerecord/debug.log" @@ -36,28 +40,28 @@ cd "#{root_dir}/activerecord" do puts puts "[CruiseControl] Building ActiveRecord with MySQL" puts - build_results[:activerecord_mysql] = system 'rake mysql:rebuild_databases && rake test_mysql' + build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'test_mysql' end cd "#{root_dir}/activerecord" do puts puts "[CruiseControl] Building ActiveRecord with PostgreSQL" puts - build_results[:activerecord_postgresql8] = system 'rake postgresql:rebuild_databases && rake test_postgresql' + build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'test_postgresql' end cd "#{root_dir}/activerecord" do puts puts "[CruiseControl] Building ActiveRecord with SQLite 3" puts - build_results[:activerecord_sqlite3] = system 'rake test_sqlite3' + build_results[:activerecord_sqlite3] = rake 'test_sqlite3' end cd "#{root_dir}/activemodel" do puts puts "[CruiseControl] Building ActiveModel" puts - build_results[:activemodel] = system 'rake' + build_results[:activemodel] = rake end rm_f "#{root_dir}/activeresource/debug.log" @@ -65,29 +69,29 @@ cd "#{root_dir}/activeresource" do puts puts "[CruiseControl] Building ActiveResource" puts - build_results[:activeresource] = system 'rake' + build_results[:activeresource] = rake end cd "#{root_dir}/actionpack" do puts puts "[CruiseControl] Building ActionPack" puts - build_results[:actionpack] = system 'rake' - build_results[:actionpack_isolated] = system 'rake test:isolated' + build_results[:actionpack] = rake + build_results[:actionpack_isolated] = rake 'test:isolated' end cd "#{root_dir}/actionmailer" do puts puts "[CruiseControl] Building ActionMailer" puts - build_results[:actionmailer] = system 'rake' + build_results[:actionmailer] = rake end cd "#{root_dir}/railties" do puts puts "[CruiseControl] Building RailTies" puts - build_results[:railties] = system 'rake' + build_results[:railties] = rake end -- cgit v1.2.3 From a4aa95ba0ca9c0a6282ed3d70d63be91acf7ab6d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:13:38 -0800 Subject: Bump AR.gemspec Arel dep too --- activerecord/activerecord.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 204cddde47..c84a3ac5a9 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -9,7 +9,7 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', '= 3.0.pre') s.add_dependency('activemodel', '= 3.0.pre') - s.add_dependency('arel', '~> 0.1.1') + s.add_dependency('arel', '= 0.2.pre') s.require_path = 'lib' s.autorequire = 'active_record' -- cgit v1.2.3 From ec2b2654e5dfc6cf6ec7255083561f1304e234d3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:18:21 -0800 Subject: Make root_dir a method so rails can call it --- ci/ci_build.rb | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index cb3be9265b..b62cca09a5 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -1,12 +1,17 @@ #!/usr/bin/env ruby require 'fileutils' - include FileUtils -puts "[CruiseControl] Rails build" +def root_dir + @root_dir ||= File.expand_path('../..', __FILE__) +end + +def rake(*tasks) + tasks.map { |task| system "#{root_dir}/bin/rake", task }.join("\n") +end +puts "[CruiseControl] Rails build" build_results = {} -root_dir = File.expand_path('../..', __FILE__) # Requires gem home and path to be writeable and/or overridden to be ~/.gem, # Will enable when RubyGems supports this properly (in a coming release) @@ -16,10 +21,6 @@ root_dir = File.expand_path('../..', __FILE__) # A security hole, but there is nothing valuable on rails CI box anyway. build_results[:geminstaller] = system "sudo geminstaller --config=#{root_dir}/ci/geminstaller.yml --exceptions" -def rake(*tasks) - tasks.map { |task| system "#{root_dir}/bin/rake", task }.join("\n") -end - cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" -- cgit v1.2.3 From a7dc7cd0c4ceccf0e89056d4429a1cfc84418a74 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:24:37 -0800 Subject: Ruby 1.9: don't bundle fcgi at all for CI --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 592fd30b2e..e279eb00aa 100644 --- a/Gemfile +++ b/Gemfile @@ -21,7 +21,7 @@ gem "erubis", ">= 2.6.5" gem "RedCloth", ">= 4.2.2" only :ci do - gem "fcgi", ">= 0.8.7" + gem "fcgi", ">= 0.8.7" if RUBY_VERSION <= '1.9.0' gem "nokogiri", ">= 1.4.0" gem "memcache-client", ">= 1.7.6" gem "pg", ">= 0.8.0" -- cgit v1.2.3 From aef7e214bd2484cd879d67bb92dda6314e0d6435 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:28:25 -0800 Subject: Use an env var to expand the CI bundle. Using bundler's 'only' includes this stuff for everybody, oops. --- Gemfile | 2 +- ci/ci_build.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index e279eb00aa..1a4bba32c1 100644 --- a/Gemfile +++ b/Gemfile @@ -20,7 +20,7 @@ gem "rack-test", ">= 0.5.0" gem "erubis", ">= 2.6.5" gem "RedCloth", ">= 4.2.2" -only :ci do +if ENV['CI'] gem "fcgi", ">= 0.8.7" if RUBY_VERSION <= '1.9.0' gem "nokogiri", ">= 1.4.0" gem "memcache-client", ">= 1.7.6" diff --git a/ci/ci_build.rb b/ci/ci_build.rb index b62cca09a5..453479d605 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -25,7 +25,7 @@ cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" puts - build_results[:bundle] = system 'rm -rf vendor && gem bundle --update' + build_results[:bundle] = system 'rm -rf vendor && env CI=1 gem bundle --update' end cd "#{root_dir}/activesupport" do -- cgit v1.2.3 From 907858c1fe24ea6e3a48cbc0d6e61ea07c0a0624 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:32:09 -0800 Subject: CI: shush complaints about 777 perms --- ci/ci_build.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 453479d605..9af407bc2e 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -25,7 +25,7 @@ cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" puts - build_results[:bundle] = system 'rm -rf vendor && env CI=1 gem bundle --update' + build_results[:bundle] = system 'rm -rf vendor && env CI=1 gem bundle --update && chmod 755 bin' end cd "#{root_dir}/activesupport" do -- cgit v1.2.3 From e889f315c8af6d67bf605069a0ffb8848aea145d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:40:54 -0800 Subject: CI: return result of last rake task --- ci/ci_build.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 9af407bc2e..bece33e736 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -7,7 +7,9 @@ def root_dir end def rake(*tasks) - tasks.map { |task| system "#{root_dir}/bin/rake", task }.join("\n") + result = nil + tasks.each { |task| result = system("#{root_dir}/bin/rake", task) } + result end puts "[CruiseControl] Rails build" -- cgit v1.2.3 From 6480850d3787a2e56bf7ef01e2b6d823f488972e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:43:37 -0800 Subject: Revert "Eliminate warning with layout is unset" This reverts commit 90be80361f26d717f9842170315dd8659f35429d. --- actionpack/lib/abstract_controller/layouts.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 60bd486763..1616f8030a 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -100,7 +100,7 @@ module AbstractController # name, return that string. Otherwise, use the superclass' # layout (which might also be implied) def _write_layout_method - case @_layout ||= nil + case @_layout when String self.class_eval %{def _layout(details) #{@_layout.inspect} end} when Symbol -- cgit v1.2.3 From f14eb686ef36babfbfc0eb9ef9de962f365c7277 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:46:32 -0800 Subject: CI: bundle test-unit on 1.9 --- Gemfile | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 1a4bba32c1..d44c689582 100644 --- a/Gemfile +++ b/Gemfile @@ -21,8 +21,15 @@ gem "erubis", ">= 2.6.5" gem "RedCloth", ">= 4.2.2" if ENV['CI'] - gem "fcgi", ">= 0.8.7" if RUBY_VERSION <= '1.9.0' gem "nokogiri", ">= 1.4.0" gem "memcache-client", ">= 1.7.6" gem "pg", ">= 0.8.0" + + # fcgi gem doesn't compile on 1.9 + # avoid minitest strangeness on 1.9 + if RUBY_VERSION < '1.9.0' + gem "fcgi", ">= 0.8.7" + else + gem "test-unit", ">= 2.0.5" + end end -- cgit v1.2.3 From 1fcf32f8fef8fb5a63a66edacf556a107d12c049 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 14:13:21 -0800 Subject: Eliminate warning with layout is unset --- actionpack/lib/abstract_controller/layouts.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 1616f8030a..c71cef42b2 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -100,7 +100,7 @@ module AbstractController # name, return that string. Otherwise, use the superclass' # layout (which might also be implied) def _write_layout_method - case @_layout + case defined?(@_layout) ? @_layout : nil when String self.class_eval %{def _layout(details) #{@_layout.inspect} end} when Symbol -- cgit v1.2.3 From 819bdd0f4a0e2f96cd43917f5c87e17cb3aec1e1 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:51:01 -0800 Subject: Bundle rack-1.0 branch --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index d44c689582..ca7fa759bf 100644 --- a/Gemfile +++ b/Gemfile @@ -14,7 +14,7 @@ gem "arel", "0.2.pre", :git => "git://github.com/rails/arel.git" gem "sqlite3-ruby", ">= 1.2.5" # AP -gem "rack", "1.0.1", :git => "git://github.com/rails/rack.git" +gem "rack", "1.0.1", :git => "git://github.com/rails/rack.git", :branch => "rack-1.0" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", ">= 0.5.0" gem "erubis", ">= 2.6.5" -- cgit v1.2.3 From 60558cc753f171d675783fafc6aa4855344a27cd Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 15:59:25 -0800 Subject: CI: no system gems required --- Gemfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gemfile b/Gemfile index ca7fa759bf..4a5881cf49 100644 --- a/Gemfile +++ b/Gemfile @@ -21,6 +21,8 @@ gem "erubis", ">= 2.6.5" gem "RedCloth", ">= 4.2.2" if ENV['CI'] + disable_system_gems + gem "nokogiri", ">= 1.4.0" gem "memcache-client", ">= 1.7.6" gem "pg", ">= 0.8.0" -- cgit v1.2.3 From c626be796ce2fd716d72f8d38784eabe7267625e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:08:02 -0800 Subject: CI: rearrange build order, AR last --- ci/ci_build.rb | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index bece33e736..3a4515054a 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -38,26 +38,26 @@ cd "#{root_dir}/activesupport" do build_results[:activesupport_isolated] = rake 'test:isolated' end -rm_f "#{root_dir}/activerecord/debug.log" -cd "#{root_dir}/activerecord" do +cd "#{root_dir}/railties" do puts - puts "[CruiseControl] Building ActiveRecord with MySQL" + puts "[CruiseControl] Building RailTies" puts - build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'test_mysql' + build_results[:railties] = rake end -cd "#{root_dir}/activerecord" do +cd "#{root_dir}/actionpack" do puts - puts "[CruiseControl] Building ActiveRecord with PostgreSQL" + puts "[CruiseControl] Building ActionPack" puts - build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'test_postgresql' + build_results[:actionpack] = rake + build_results[:actionpack_isolated] = rake 'test:isolated' end -cd "#{root_dir}/activerecord" do +cd "#{root_dir}/actionmailer" do puts - puts "[CruiseControl] Building ActiveRecord with SQLite 3" + puts "[CruiseControl] Building ActionMailer" puts - build_results[:activerecord_sqlite3] = rake 'test_sqlite3' + build_results[:actionmailer] = rake end cd "#{root_dir}/activemodel" do @@ -75,26 +75,26 @@ cd "#{root_dir}/activeresource" do build_results[:activeresource] = rake end -cd "#{root_dir}/actionpack" do +rm_f "#{root_dir}/activerecord/debug.log" +cd "#{root_dir}/activerecord" do puts - puts "[CruiseControl] Building ActionPack" + puts "[CruiseControl] Building ActiveRecord with MySQL" puts - build_results[:actionpack] = rake - build_results[:actionpack_isolated] = rake 'test:isolated' + build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'test_mysql' end -cd "#{root_dir}/actionmailer" do +cd "#{root_dir}/activerecord" do puts - puts "[CruiseControl] Building ActionMailer" + puts "[CruiseControl] Building ActiveRecord with PostgreSQL" puts - build_results[:actionmailer] = rake + build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'test_postgresql' end -cd "#{root_dir}/railties" do +cd "#{root_dir}/activerecord" do puts - puts "[CruiseControl] Building RailTies" + puts "[CruiseControl] Building ActiveRecord with SQLite 3" puts - build_results[:railties] = rake + build_results[:activerecord_sqlite3] = rake 'test_sqlite3' end -- cgit v1.2.3 From d8fd0499bfd6edc676ff3fbffc327656f6d5c320 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:09:52 -0800 Subject: Revert "Eliminate warning with layout is unset" This reverts commit 1fcf32f8fef8fb5a63a66edacf556a107d12c049. --- actionpack/lib/abstract_controller/layouts.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index c71cef42b2..1616f8030a 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -100,7 +100,7 @@ module AbstractController # name, return that string. Otherwise, use the superclass' # layout (which might also be implied) def _write_layout_method - case defined?(@_layout) ? @_layout : nil + case @_layout when String self.class_eval %{def _layout(details) #{@_layout.inspect} end} when Symbol -- cgit v1.2.3 From 8cd486da807d1b15b8ba4a049a79df6c47c56bd4 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:14:10 -0800 Subject: test-unit 2 compat: assert_raise doesn't support regexp second arg to match exception message --- actionpack/test/abstract/layouts_test.rb | 2 +- actionpack/test/controller/new_base/render_action_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/test/abstract/layouts_test.rb b/actionpack/test/abstract/layouts_test.rb index 9c29696ad5..ae2f1bf1f2 100644 --- a/actionpack/test/abstract/layouts_test.rb +++ b/actionpack/test/abstract/layouts_test.rb @@ -212,7 +212,7 @@ module AbstractControllerTests end test "when the layout is specified as a symbol and the method doesn't exist, raise an exception" do - assert_raises(NoMethodError, /:nilz/) { WithSymbolAndNoMethod.new.process(:index) } + assert_raises(NoMethodError) { WithSymbolAndNoMethod.new.process(:index) } end test "when the layout is specified as a symbol and the method returns something besides a string/false/nil, raise an exception" do diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb index ecd29c4530..239f68659c 100644 --- a/actionpack/test/controller/new_base/render_action_test.rb +++ b/actionpack/test/controller/new_base/render_action_test.rb @@ -86,7 +86,7 @@ module RenderAction describe "Both .html.erb and application.html.erb are missing" test "rendering with layout => true" do - assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do + assert_raise(ArgumentError) do get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false end end -- cgit v1.2.3 From 631a27d6a51b0f9b11c8cc2165cae70bcd8134dd Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:15:43 -0800 Subject: Revert "Revert "Eliminate warning with layout is unset"" This reverts commit d8fd0499bfd6edc676ff3fbffc327656f6d5c320. --- actionpack/lib/abstract_controller/layouts.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 1616f8030a..c71cef42b2 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -100,7 +100,7 @@ module AbstractController # name, return that string. Otherwise, use the superclass' # layout (which might also be implied) def _write_layout_method - case @_layout + case defined?(@_layout) ? @_layout : nil when String self.class_eval %{def _layout(details) #{@_layout.inspect} end} when Symbol -- cgit v1.2.3 From 13280a049e6aaee51e1c011c0c155dc4d1085c76 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:34:04 -0800 Subject: Back to rack master, rack-1.0 reverts the kind_of? String fix --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 4a5881cf49..55cf4e1104 100644 --- a/Gemfile +++ b/Gemfile @@ -14,7 +14,7 @@ gem "arel", "0.2.pre", :git => "git://github.com/rails/arel.git" gem "sqlite3-ruby", ">= 1.2.5" # AP -gem "rack", "1.0.1", :git => "git://github.com/rails/rack.git", :branch => "rack-1.0" +gem "rack", "1.0.1", :git => "git://github.com/rails/rack.git" gem "rack-mount", :git => "git://github.com/rails/rack-mount.git" gem "rack-test", ">= 0.5.0" gem "erubis", ">= 2.6.5" -- cgit v1.2.3 From e02bff2634d94c07780884cae83b258d3f3a9a0e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:50:12 -0800 Subject: CI: missed mysql gem in bundle --- Gemfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Gemfile b/Gemfile index 55cf4e1104..20d5263c07 100644 --- a/Gemfile +++ b/Gemfile @@ -26,6 +26,7 @@ if ENV['CI'] gem "nokogiri", ">= 1.4.0" gem "memcache-client", ">= 1.7.6" gem "pg", ">= 0.8.0" + gem "mysql", ">= 2.8.1" # fcgi gem doesn't compile on 1.9 # avoid minitest strangeness on 1.9 -- cgit v1.2.3 From bbb3e5a858b2d078b2af7516a583fa12f3edb565 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:50:15 -0800 Subject: Unify test:isolated across components and run by default at toplevel --- Rakefile | 4 ++-- actionmailer/Rakefile | 12 +++++++----- activemodel/Rakefile | 12 +++++++----- activerecord/Rakefile | 12 +++++++----- activeresource/Rakefile | 15 ++++++++------- railties/Rakefile | 20 +++++++++++--------- 6 files changed, 42 insertions(+), 33 deletions(-) diff --git a/Rakefile b/Rakefile index f9255a4269..6aa8f61028 100644 --- a/Rakefile +++ b/Rakefile @@ -10,9 +10,9 @@ Dir["#{File.dirname(__FILE__)}/*/lib/*/version.rb"].each do |version_path| end desc 'Run all tests by default' -task :default => :test +task :default => %w(test test:isolated) -%w(test isolated_test rdoc pgem package release gem gemspec).each do |task_name| +%w(test test:isolated rdoc pgem package release gem gemspec).each do |task_name| desc "Run #{task_name} task for all projects" task task_name do errors = [] diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile index 140661ecb0..1a7ece5068 100644 --- a/actionmailer/Rakefile +++ b/actionmailer/Rakefile @@ -27,11 +27,13 @@ Rake::TestTask.new { |t| t.warning = true } -task :isolated_test do - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - Dir.glob("test/*_test.rb").all? do |file| - system(ruby, '-Ilib:test', file) - end or raise "Failures" +namespace :test do + task :isolated do + ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) + Dir.glob("test/*_test.rb").all? do |file| + system(ruby, '-Ilib:test', file) + end or raise "Failures" + end end # Generate the RDoc documentation diff --git a/activemodel/Rakefile b/activemodel/Rakefile index a63e1982b9..1f4a8466c9 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -19,11 +19,13 @@ Rake::TestTask.new do |t| t.warning = true end -task :isolated_test do - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - Dir.glob("#{dir}/test/**/*_test.rb").all? do |file| - system(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file) - end or raise "Failures" +namespace :test do + task :isolated do + ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) + Dir.glob("#{dir}/test/**/*_test.rb").all? do |file| + system(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file) + end or raise "Failures" + end end diff --git a/activerecord/Rakefile b/activerecord/Rakefile index f7585f789b..2511f13fed 100644 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -49,11 +49,13 @@ task :test do run_without_aborting(*tasks) end -task :isolated_test do - tasks = defined?(JRUBY_VERSION) ? - %w(isolated_test_jdbcmysql isolated_test_jdbcsqlite3 isolated_test_jdbcpostgresql) : - %w(isolated_test_mysql isolated_test_sqlite3 isolated_test_postgresql) - run_without_aborting(*tasks) +namespace :test do + task :isolated do + tasks = defined?(JRUBY_VERSION) ? + %w(isolated_test_jdbcmysql isolated_test_jdbcsqlite3 isolated_test_jdbcpostgresql) : + %w(isolated_test_mysql isolated_test_sqlite3 isolated_test_postgresql) + run_without_aborting(*tasks) + end end %w( mysql postgresql sqlite3 firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter| diff --git a/activeresource/Rakefile b/activeresource/Rakefile index 834d4c0c59..6566e84d4c 100644 --- a/activeresource/Rakefile +++ b/activeresource/Rakefile @@ -35,15 +35,16 @@ Rake::TestTask.new { |t| t.warning = true } -task :isolated_test do - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib" - Dir.glob("test/**/*_test.rb").all? do |file| - system(ruby, '-w', "-Ilib:test:#{activesupport_path}", file) - end or raise "Failures" +namespace :test do + task :isolated do + ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) + activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib" + Dir.glob("test/**/*_test.rb").all? do |file| + system(ruby, '-w', "-Ilib:test:#{activesupport_path}", file) + end or raise "Failures" + end end - # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| diff --git a/railties/Rakefile b/railties/Rakefile index 1280ad7f06..e6f698fc74 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -22,21 +22,23 @@ RUBY_FORGE_USER = "webster132" task :default => :test +task :test => 'test:isolated' ## This is required until the regular test task ## below passes. It's not ideal, but at least ## we can see the failures -task :test do - dir = ENV["TEST_DIR"] || "**" - Dir["test/#{dir}/*_test.rb"].all? do |file| - next true if file.include?("fixtures") - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - system(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file) - end or raise "Failures" +namespace :test do + task :isolated do + dir = ENV["TEST_DIR"] || "**" + Dir["test/#{dir}/*_test.rb"].all? do |file| + next true if file.include?("fixtures") + ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) + system(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file) + end or raise "Failures" + end end -task :isolated_test => :test -Rake::TestTask.new("regular_test") do |t| +Rake::TestTask.new('test:regular') do |t| t.libs << 'test' << "#{File.dirname(__FILE__)}/../activesupport/lib" t.pattern = 'test/**/*_test.rb' t.warning = true -- cgit v1.2.3 From 215fa167342067675b6a6968b11111be25425a38 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:54:15 -0800 Subject: CI: list bundled gems in build environment --- ci/ci_build.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 3a4515054a..12b1f6b955 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -107,6 +107,8 @@ puts "[CruiseControl] #{`mysql --version`}" puts "[CruiseControl] #{`pg_config --version`}" puts "[CruiseControl] SQLite3: #{`sqlite3 -version`}" `gem env`.each_line {|line| print "[CruiseControl] #{line}"} +puts "[CruiseControl] Bundled gems:" +`gem bundle --list`.each_line {|line| print "[CruiseControl] #{line}"} puts "[CruiseControl] Local gems:" `gem list`.each_line {|line| print "[CruiseControl] #{line}"} -- cgit v1.2.3 From 1ac8e0662fbf4e14570ad8ec490fd4cece15bbe4 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 16:57:55 -0800 Subject: Rack: HTTPS is either 'on' or 'off' as of 9b7a0569e4067d0c23a00fc24273436e85c56d7f --- actionpack/test/dispatch/test_request_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb index b2006a0d2f..5da02b2ea6 100644 --- a/actionpack/test/dispatch/test_request_test.rb +++ b/actionpack/test/dispatch/test_request_test.rb @@ -5,7 +5,7 @@ class TestRequestTest < ActiveSupport::TestCase env = ActionDispatch::TestRequest.new.env assert_equal "GET", env.delete("REQUEST_METHOD") - assert_equal nil, env.delete("HTTPS") + assert_equal "off", env.delete("HTTPS") assert_equal "http", env.delete("rack.url_scheme") assert_equal "example.org", env.delete("SERVER_NAME") assert_equal "80", env.delete("SERVER_PORT") -- cgit v1.2.3 From 486a63c258c7eff44ece0dbfbca4e6a08eeb01a0 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 17:13:43 -0800 Subject: CI: short-circuit at first failing task. Chmod 755 bin, vendor, vendor/gems --- ci/ci_build.rb | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 12b1f6b955..1b8a880a2f 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -7,9 +7,8 @@ def root_dir end def rake(*tasks) - result = nil - tasks.each { |task| result = system("#{root_dir}/bin/rake", task) } - result + tasks.each { |task| return false unless system("#{root_dir}/bin/rake", task) } + true end puts "[CruiseControl] Rails build" @@ -27,7 +26,7 @@ cd root_dir do puts puts "[CruiseControl] Bundling RubyGems" puts - build_results[:bundle] = system 'rm -rf vendor && env CI=1 gem bundle --update && chmod 755 bin' + build_results[:bundle] = system 'rm -rf vendor && env CI=1 gem bundle --update && chmod 755 bin vendor vendor/gems' end cd "#{root_dir}/activesupport" do -- cgit v1.2.3 From 0df1dc5a7274b28ed9474e871e6af1ca9b9a2fe9 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 17:19:39 -0800 Subject: CI: yeah, run those tests --- ci/ci_build.rb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 1b8a880a2f..7ae660fb7d 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -33,7 +33,7 @@ cd "#{root_dir}/activesupport" do puts puts "[CruiseControl] Building ActiveSupport" puts - build_results[:activesupport] = rake + build_results[:activesupport] = rake 'test' build_results[:activesupport_isolated] = rake 'test:isolated' end @@ -41,14 +41,14 @@ cd "#{root_dir}/railties" do puts puts "[CruiseControl] Building RailTies" puts - build_results[:railties] = rake + build_results[:railties] = rake 'test' end cd "#{root_dir}/actionpack" do puts puts "[CruiseControl] Building ActionPack" puts - build_results[:actionpack] = rake + build_results[:actionpack] = rake 'test' build_results[:actionpack_isolated] = rake 'test:isolated' end @@ -56,14 +56,14 @@ cd "#{root_dir}/actionmailer" do puts puts "[CruiseControl] Building ActionMailer" puts - build_results[:actionmailer] = rake + build_results[:actionmailer] = rake 'test' end cd "#{root_dir}/activemodel" do puts puts "[CruiseControl] Building ActiveModel" puts - build_results[:activemodel] = rake + build_results[:activemodel] = rake 'test' end rm_f "#{root_dir}/activeresource/debug.log" @@ -71,7 +71,7 @@ cd "#{root_dir}/activeresource" do puts puts "[CruiseControl] Building ActiveResource" puts - build_results[:activeresource] = rake + build_results[:activeresource] = rake 'test' end rm_f "#{root_dir}/activerecord/debug.log" -- cgit v1.2.3 From 322b6b29c272aa6c9b9d2556b736dbe32db3aa45 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 10 Nov 2009 21:04:00 -0800 Subject: test-unit 2: filter_backtrace is private --- railties/test/backtrace_cleaner_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb index 4e273852e0..6cff591b94 100644 --- a/railties/test/backtrace_cleaner_test.rb +++ b/railties/test/backtrace_cleaner_test.rb @@ -16,12 +16,12 @@ if defined? Test::Unit::Util::BacktraceFilter test "test with backtrace should use the rails backtrace cleaner to clean" do Rails.stubs(:backtrace_cleaner).returns(stub(:clean)) Rails.backtrace_cleaner.expects(:clean).with(@backtrace, nil) - @test.filter_backtrace(@backtrace) + @test.send(:filter_backtrace, @backtrace) end test "filter backtrace should have the same arity as Test::Unit::Util::BacktraceFilter" do assert_nothing_raised do - @test.filter_backtrace(@backtrace, '/opt/local/lib') + @test.send(:filter_backtrace, @backtrace, '/opt/local/lib') end end end -- cgit v1.2.3 From fca32eb6c5b41e4f19a25b7b246c4a8a3d763667 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 11 Nov 2009 01:43:58 -0800 Subject: Update AR logger subscriber for Notifications subscriber args change --- activerecord/lib/active_record/notifications.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/notifications.rb b/activerecord/lib/active_record/notifications.rb index a5ce7ac524..562a5b91f4 100644 --- a/activerecord/lib/active_record/notifications.rb +++ b/activerecord/lib/active_record/notifications.rb @@ -1,5 +1,5 @@ require 'active_support/notifications' -ActiveSupport::Notifications.subscribe("sql") do |event| - ActiveRecord::Base.connection.log_info(event.payload[:sql], event.payload[:name], event.duration) +ActiveSupport::Notifications.subscribe("sql") do |name, before, after, result, instrumenter_id, payload| + ActiveRecord::Base.connection.log_info(payload[:sql], name, after - before) end -- cgit v1.2.3