diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2009-01-10 12:14:44 -0800 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-01-10 12:14:44 -0800 |
commit | 223a1d9451c88800e9fcc93a726fdebec99e2650 (patch) | |
tree | 207b0b671778ac7a0e00829f6f642256b261cb28 /activesupport | |
parent | 13c6c3cfc59ff0b400b294dce15f32752b0fb5f5 (diff) | |
parent | 9fe69b225cfbf12c02ee1433adf3a5aa17bcdf59 (diff) | |
download | rails-223a1d9451c88800e9fcc93a726fdebec99e2650.tar.gz rails-223a1d9451c88800e9fcc93a726fdebec99e2650.tar.bz2 rails-223a1d9451c88800e9fcc93a726fdebec99e2650.zip |
Merge branch 'master' into savepoints
Diffstat (limited to 'activesupport')
49 files changed, 1748 insertions, 632 deletions
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 0e796d802c..757cb1da04 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,14 +1,27 @@ *2.3.0 [Edge]* +* Object#tap shim for Ruby < 1.8.7. Similar to Object#returning, tap yields self then returns self. [Jeremy Kemper] + array.select { ... }.tap(&:inspect).map { ... } + +* TimeWithZone#- gives correct result with wrapped DateTime, and with DateTime argument [Geoff Buesing] + +* Updated i18n gem to version 0.1.1 #1635 [Yaroslav Markin] + +* Add :allow_nil option to delegate. #1127 [Sergio Gil] + +* Add Benchmark.ms convenience method to benchmark realtime in milliseconds. [Jeremy Kemper] + +* Updated included memcache-client to the 1.5.0.5 version which includes fixes from fiveruns and 37signals to deal with failover and timeouts #1535 [Joshua Sierles] + * Multibyte: add multibyte-safe Chars#ord rather than falling back to String#ord. #1483 [Jason Cheow] * I18n support for Array#to_sentence. Introduces support.array.words_connector, .two_words_connector, and .last_word_connector translation keys. #1397 [Akira Matsuda] * Added ActiveSupport::OrderedHash#each_key and ActiveSupport::OrderedHash#each_value #1410 [Christoffer Sawicki] -* Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. [Koz] +* Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. [Michael Koziarski] -* Added ActiveSupport::BacktraceCleaner to cut down on backtrace noise according to filters and silencers [DHH] +* Added ActiveSupport::BacktraceCleaner to cut down on backtrace noise according to filters and silencers [David Heinemeier Hansson] * Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath] @@ -27,7 +40,7 @@ * Fixed the option merging in Array#to_xml #1126 [Rudolf Gavlas] -* Make I18n::Backend::Simple reload its translations in development mode [DHH/Sven Fuchs] +* Make I18n::Backend::Simple reload its translations in development mode [David Heinemeier Hansson/Sven Fuchs] *2.2.0 [RC1] (October 24th, 2008)* @@ -38,7 +51,7 @@ * Time#advance recognizes fractional days and weeks. Deprecate Durations of fractional months and years #970 [Tom Lea] -* Add ActiveSupport::Rescuable module abstracting ActionController::Base rescue_from features. [Norbert Crombach, Pratik] +* Add ActiveSupport::Rescuable module abstracting ActionController::Base rescue_from features. [Norbert Crombach, Pratik Naik] * Switch from String#chars to String#mb_chars for the unicode proxy. [Manfred Stienstra] @@ -52,7 +65,7 @@ * Added Inflector#parameterize for easy slug generation ("Donald E. Knuth".parameterize => "donald-e-knuth") #713 [Matt Darby] -* Changed cache benchmarking to be reported in milliseconds [DHH] +* Changed cache benchmarking to be reported in milliseconds [David Heinemeier Hansson] * Fix Ruby's Time marshaling bug in pre-1.9 versions of Ruby: utc instances are now correctly unmarshaled with a utc zone instead of the system local zone [#900 state:resolved] [Luca Guidi, Geoff Buesing] @@ -68,7 +81,7 @@ * Move the test related core_ext stuff out of core_ext so it's only loaded by the test helpers. [Michael Koziarski] -* Add Inflection rules for String#humanize. #535 [dcmanges] +* Add Inflection rules for String#humanize. #535 [Dan Manges] ActiveSupport::Inflector.inflections do |inflect| inflect.human(/_cnt$/i, '\1_count') @@ -80,19 +93,19 @@ * Added TimeZone #=~, to support matching zones by regex in time_zone_select. #195 [Ernie Miller] -* Added Array#second through Array#fifth as aliases for Array#[1] through Array#[4] + Array#forty_two as alias for Array[41] [DHH] +* Added Array#second through Array#fifth as aliases for Array#[1] through Array#[4] + Array#forty_two as alias for Array[41] [David Heinemeier Hansson] * Added test/do declaration style testing to ActiveSupport::TestCase [DHH via Jay Fields] -* Added Object#present? which is equivalent to !Object#blank? [DHH] +* Added Object#present? which is equivalent to !Object#blank? [David Heinemeier Hansson] -* Added Enumberable#many? to encapsulate collection.size > 1 [DHH/Damian Janowski] +* Added Enumberable#many? to encapsulate collection.size > 1 [David Heinemeier Hansson/Damian Janowski] * Add more standard Hash methods to ActiveSupport::OrderedHash [Steve Purcell] * Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under ActiveSupport [Josh Peek] -* Added StringInquirer for doing things like StringInquirer.new("production").production? # => true and StringInquirer.new("production").development? # => false [DHH] +* Added StringInquirer for doing things like StringInquirer.new("production").production? # => true and StringInquirer.new("production").development? # => false [David Heinemeier Hansson] * Fixed Date#end_of_quarter to not blow up on May 31st [#289 state:resolved] (Danger) @@ -129,7 +142,7 @@ * TimeWithZone respects config.active_support.use_standard_json_time_format [Geoff Buesing] -* Add config.active_support.escape_html_entities_in_json to allow disabling of html entity escaping. [rick] +* Add config.active_support.escape_html_entities_in_json to allow disabling of html entity escaping. [Rick Olson] * Improve documentation. [Xavier Noria] @@ -141,7 +154,7 @@ * TimeWithZone#method_missing: send to utc to advance with dst correctness, otherwise send to time. Adding tests for time calculations methods [Geoff Buesing] -* Add config.active_support.use_standard_json_time_format setting so that Times and Dates export to ISO 8601 dates. [rick] +* Add config.active_support.use_standard_json_time_format setting so that Times and Dates export to ISO 8601 dates. [Rick Olson] * TZInfo: Removing unneeded TimezoneProxy class [Geoff Buesing] @@ -159,9 +172,9 @@ * TimeWithZone#usec returns 0 instead of error when DateTime is wrapped [Geoff Buesing] -* Improve documentation. [Radar, Jan De Poorter, chuyeow, xaviershay, danger, miloops, Xavier Noria, Sunny Ripert] +* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert] -* Ensure that TimeWithZone#to_yaml works when passed a YAML::Emitter. [rick] +* Ensure that TimeWithZone#to_yaml works when passed a YAML::Emitter. [Rick Olson] * Ensure correct TimeWithZone#to_date [Geoff Buesing] @@ -193,7 +206,7 @@ * Adding TimeWithZone #marshal_dump and #marshal_load [Geoff Buesing] -* Add OrderedHash#to_hash [josh] +* Add OrderedHash#to_hash [Josh Peek] * Adding Time#end_of_day, _quarter, _week, and _year. #9312 [Juanjo Bazan, Tarmo Tänav, BigTitus] @@ -203,9 +216,9 @@ * TimeWithZone #+ and #- behave consistently with numeric arguments regardless of whether wrapped time is a Time or DateTime; consistenty answers false to #acts_like?(:date) [Geoff Buesing] -* Add String#squish and String#squish! to remove consecutive chunks of whitespace. #11123 [jordi, Henrik N] +* Add String#squish and String#squish! to remove consecutive chunks of whitespace. #11123 [Jordi Bunster, Henrik N] -* Serialize BigDecimals as Floats when using to_yaml. #8746 [ernesto.jimenez] +* Serialize BigDecimals as Floats when using to_yaml. #8746 [Ernesto Jimenez] * Adding TimeWithZone #to_yaml, #to_datetime, #eql? and method aliases for duck-typing compatibility with Time [Geoff Buesing] @@ -223,7 +236,7 @@ * TimeZone#new method renamed #local; when used with Time.zone, constructor now reads: Time.zone.local() [Geoff Buesing] -* Added Base64.encode64s to encode values in base64 without the newlines. This makes the values immediately usable as URL parameters or memcache keys without further processing [DHH] +* Added Base64.encode64s to encode values in base64 without the newlines. This makes the values immediately usable as URL parameters or memcache keys without further processing [David Heinemeier Hansson] * Remove :nodoc: entries around the ActiveSupport test/unit assertions. #10946 [dancroak, jamesh] @@ -231,7 +244,7 @@ * cache.fetch(key, :force => true) to force a cache miss. [Jeremy Kemper] -* Support retrieving TimeZones with a Duration. TimeZone[-28800] == TimeZone[-480.minutes]. [rick] +* Support retrieving TimeZones with a Duration. TimeZone[-28800] == TimeZone[-480.minutes]. [Rick Olson] * TimeWithZone#- added, so that #- can handle a Time or TimeWithZone argument correctly [Geoff Buesing] @@ -279,21 +292,21 @@ * TestCase: introduce declared setup and teardown callbacks. Pass a list of methods and an optional block to call before setup or after teardown. Setup callbacks are run in the order declared; teardown callbacks are run in reverse. [Jeremy Kemper] -* Added ActiveSupport::Gzip.decompress/compress(source) as an easy wrapper for Zlib [Tobias Luetke] +* Added ActiveSupport::Gzip.decompress/compress(source) as an easy wrapper for Zlib [Tobias Lütke] * Included MemCache-Client to make the improved ActiveSupport::Cache::MemCacheStore work out of the box [Bob Cottrell, Eric Hodel] -* Added ActiveSupport::Cache::* framework as an extraction from ActionController::Caching::Fragments::* [DHH] +* Added ActiveSupport::Cache::* framework as an extraction from ActionController::Caching::Fragments::* [David Heinemeier Hansson] * Fixed String#titleize to work for strings with 's too #10571 [trek] -* Changed the implementation of Enumerable#group_by to use a double array approach instead of a hash such that the insert order is honored [DHH/Marcel] +* Changed the implementation of Enumerable#group_by to use a double array approach instead of a hash such that the insert order is honored [David Heinemeier Hansson/Marcel Molina Jr.] -* remove multiple enumerations from ActiveSupport::JSON#convert_json_to_yaml when dealing with date/time values. [rick] +* remove multiple enumerations from ActiveSupport::JSON#convert_json_to_yaml when dealing with date/time values. [Rick Olson] * Hash#symbolize_keys skips keys that can't be symbolized. #10500 [Brad Greenlee] -* Ruby 1.9 compatibility. #1689, #10466, #10468, #10554, #10594, #10632 [Cheah Chu Yeow, Pratik Naik, Jeremy Kemper, Dirkjan Bussink, fxn] +* Ruby 1.9 compatibility. #1689, #10466, #10468, #10554, #10594, #10632 [Cheah Chu Yeow, Pratik Naik, Jeremy Kemper, Dirkjan Bussink, Xavier Noria] * TimeZone#to_s uses UTC rather than GMT. #1689 [Cheah Chu Yeow] @@ -304,7 +317,7 @@ *2.0.1* (December 7th, 2007) -* Added Array#from and Array#to that behaves just from String#from and String#to [DHH] +* Added Array#from and Array#to that behaves just from String#from and String#to [David Heinemeier Hansson] * Fix that empty collections should be treated as empty arrays regardless of whitespace for Hash#from_xml #10255 [adamj] @@ -312,17 +325,17 @@ * Change Time and DateTime #end_of_month to return last second of month instead of beginning of last day of month. Closes #10200 [Geoff Buesing] -* Speedup String#blank? [Jeremy Kemper, Koz] +* Speedup String#blank? [Jeremy Kemper, Michael Koziarski] * Add documentation for Hash#diff. Closes #9306 [Tarmo Tänav] -* Add new superclass_delegating_accessors. Similar to class inheritable attributes but with subtly different semantics. [Koz, Tarmo Tänav] +* Add new superclass_delegating_accessors. Similar to class inheritable attributes but with subtly different semantics. [Michael Koziarski, Tarmo Tänav] * Change JSON to encode %w(< > &) as 4 digit hex codes to be in compliance with the JSON spec. Closes #9975 [Josh Peek, Cheah Chu Yeow, Tim Pope] -* Fix JSON encoding/decoding bugs dealing with /'s. Closes #9990 [Rick, theamazingrando] +* Fix JSON encoding/decoding bugs dealing with /'s. Closes #9990 [Rick Olson, theamazingrando] -* Introduce a base class for all test cases used by rails applications. ActiveSupport::TestCase [Koz] +* Introduce a base class for all test cases used by rails applications. ActiveSupport::TestCase [Michael Koziarski] The intention is to use this to reduce the amount of monkeypatching / overriding that is done to test/unit's classes. @@ -375,13 +388,13 @@ * Backport Object#instance_variable_defined? for Ruby < 1.8.6. [Jeremy Kemper] -* BufferedLogger#add converts the message to a string. #9702, #9724 [eigentone, DrMark, tomafro] +* BufferedLogger#add converts the message to a string. #9702, #9724 [eigentone, DrMark, Tom Ward] -* Added ActiveSupport::BufferedLogger as a duck-typing alternative (albeit with no formatter) to the Ruby Logger, which provides a very nice speed bump (inspired by Ezra's buffered logger) [DHH] +* Added ActiveSupport::BufferedLogger as a duck-typing alternative (albeit with no formatter) to the Ruby Logger, which provides a very nice speed bump (inspired by Ezra's buffered logger) [David Heinemeier Hansson] * Object#instance_exec produces fewer garbage methods. [Mauricio Fernandez] -* Decode json strings as Dates/Times if they're using a YAML-compatible format. Closes #9614 [Rick] +* Decode json strings as Dates/Times if they're using a YAML-compatible format. Closes #9614 [Rick Olson] * Fixed cache_page to use the request url instead of the routing options when picking a save path. #8614 [Josh Peek] @@ -389,11 +402,11 @@ * Fixed that pluralizing an empty string should return the same empty string, not "s". #7720 [Josh Peek] -* Added call to inspect on non-string classes for the logger #8533 [codahale] +* Added call to inspect on non-string classes for the logger #8533 [Coda Hale] * Deprecation: remove deprecated :mday option from Time, Date, and DateTime#change. [Jeremy Kemper] -* Fix JSON decoder with nested quotes and commas. #9579 [zdennis] +* Fix JSON decoder with nested quotes and commas. #9579 [Zach Dennis] * Hash#to_xml doesn't double-unescape. #8806 [Ezran] @@ -405,27 +418,27 @@ * Deprecation: removed Reloadable. [Jeremy Kemper] -* Make the utf-handler return the correct value for non-matching regular expressions. Closes #9049 [manfred] +* Make the utf-handler return the correct value for non-matching regular expressions. Closes #9049 [Manfred Stienstra] -* Add ljust, rjust and center to utf8-handler. Closes #9165 [manfred] +* Add ljust, rjust and center to utf8-handler. Closes #9165 [Manfred Stienstra] -* Fix Time#advance bug when trying to advance a year from leap day. Closes #8655 [gbuesing] +* Fix Time#advance bug when trying to advance a year from leap day. Closes #8655 [Geoff Buesing] -* Add support for []= on ActiveSupport::Multibyte::Chars. Closes #9142. [ewan, manfred] +* Add support for []= on ActiveSupport::Multibyte::Chars. Closes #9142. [ewan, Manfred Stienstra] * Added Array#extract_options! to encapsulate the pattern of getting an options hash out of a variable number of parameters. #8759 [Norbert Crombach] * Let alias_attribute work with attributes with initial capital letters (legacy columns etc). Closes #8596 [mpalmer] -* Added Hash#except which is the inverse of Hash#slice -- return the hash except the keys that are specified [DHH] +* Added Hash#except which is the inverse of Hash#slice -- return the hash except the keys that are specified [David Heinemeier Hansson] -* Added support for pluralization with a different starting letter than the singular version (cow/kine) #4929 [norri_b/hasmanyjosh] +* Added support for pluralization with a different starting letter than the singular version (cow/kine) #4929 [norri_b/Josh Susser] * Demote Hash#to_xml to use XmlSimple#xml_in_string so it can't read files or stdin. #8453 [candlerb, Jeremy Kemper] -* Backport clean_logger changes to support ruby 1.8.2 [mislav] +* Backport clean_logger changes to support ruby 1.8.2 [Mislav Marohnić] -* Added proper handling of arrays #8537 [hasmanyjosh] +* Added proper handling of arrays #8537 [Josh Susser] Before: Hash.from_xml '<images></images>' @@ -459,7 +472,7 @@ * Move common DateTime calculations to Date. #8536 [Geoff Buesing] -* Added Date#change (like Time#change) [DHH] +* Added Date#change (like Time#change) [David Heinemeier Hansson] * DateTime#to_time converts to Time unless out of range. #8512 [Geoff Buesing] @@ -467,7 +480,7 @@ * Time durations use since instead of + for accuracy. #8513 [Geoff Buesing] -* escape <'s and >'s in JSON strings. #8371 [Rick] +* escape <'s and >'s in JSON strings. #8371 [Rick Olson] * Inflections: MatrixTest -> MatrixTests instead of MatricesTest. #8496 [jbwiv] @@ -483,11 +496,11 @@ * Simplify API of assert_difference by passing in an expression that is evaluated before and after the passed in block. See documenation for examples of new API. [Marcel Molina Jr.] -* Added assert_difference and assert_no_difference to test/unit assertions [Tobias Luetke] +* Added assert_difference and assert_no_difference to test/unit assertions [Tobias Lütke] -* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [DHH] +* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson] -* Added parsing of file type in Hash.xml_in so you can easily do file uploads with base64 from an API [DHH] +* Added parsing of file type in Hash.xml_in so you can easily do file uploads with base64 from an API [David Heinemeier Hansson] <person> <name>David</name> @@ -507,9 +520,9 @@ * Use XSD-compatible type names for Hash#to_xml and make the converters extendable #8047 [Tim Pope] -* Added yielding of builder in Hash#to_xml [DHH] +* Added yielding of builder in Hash#to_xml [David Heinemeier Hansson] -* Hash#with_indifferent_access now also converts hashes kept in arrays to indifferent access (makes it easier to treat HTML and XML parameters the same) [DHH] +* Hash#with_indifferent_access now also converts hashes kept in arrays to indifferent access (makes it easier to treat HTML and XML parameters the same) [David Heinemeier Hansson] * Hash#to_xml supports YAML attributes. #7502 [jonathan] @@ -527,9 +540,9 @@ * Give DateTime correct .to_s implementations, lets it play nice with ActiveRecord quoting. #7649 [Geoff Buesing] -* Add File.atomic_write, allows you to write large files in an atomic manner, preventing users from seeing half written files. [Koz] +* Add File.atomic_write, allows you to write large files in an atomic manner, preventing users from seeing half written files. [Michael Koziarski] -* Allow users to provide custom formatters to Logger. [aeden] +* Allow users to provide custom formatters to Logger. [Anthony Eden] * Hash#to_query CGI-escapes its keys. [Jeremy Kemper] @@ -538,7 +551,7 @@ * :db format for Date#to_s [Jeremy Kemper] Date.new(2007, 1, 27).to_s(:db) # => '2007-01-27' -* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. [Rick] +* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. [Rick Olson] * Added Hash#to_query to turn a hash of values into a form-encoded query string [Nicholas Seckar] @@ -573,7 +586,7 @@ public for compatibility. [Jeremy Kemper] * Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 [Bruce Perens] -* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. [Rick] +* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. [Rick Olson] * Full test coverage for Inflector. #7228 [Dan Kubb] @@ -598,13 +611,13 @@ public for compatibility. [Jeremy Kemper] * Fixed Array#to_xml when it contains a series of hashes (each piece would get its own XML declaration) #6610 [thkarcher/cyu] -* Added Time#to_s(:time) which will just return H:M, like 17:44 [DHH] +* Added Time#to_s(:time) which will just return H:M, like 17:44 [David Heinemeier Hansson] * Add Module#attr_accessor_with_default to initialize value of attribute before setting it. Closes #6538. [Stuart Halloway, Marcel Molina Jr.] -* Hash#to_xml handles keys with the same name as Kernel methods. #6613 [Catfish] +* Hash#to_xml handles keys with the same name as Kernel methods. #6613 [Jonathan del Strother] -* Added Time#end_of_day to get 23:59:59 of that day [DHH] +* Added Time#end_of_day to get 23:59:59 of that day [David Heinemeier Hansson] * Don't quote hash keys in Hash#to_json if they're valid JavaScript identifiers. Disable this with ActiveSupport::JSON.unquote_hash_key_identifiers = false if you need strict JSON compliance. [Sam Stephenson] @@ -614,11 +627,11 @@ public for compatibility. [Jeremy Kemper] * Fix unicode JSON regexp for Onigurama compatibility. #6494 [whitley] -* update XmlSimple to 1.0.10. Closes #6532. [nicksieger] +* update XmlSimple to 1.0.10. Closes #6532. [Nick Sieger] * Update dependencies to allow constants to be defined alongside their siblings. A common case for this is AR model classes with STI; user.rb might define User, Administrator and Guest for example. [Nicholas Seckar] -* next_week respects DST changes. #6483, #5617, #2353, #2509, #4551 [marclove, rabiedenharn, rails@roetzel.de, jsolson@damogran.org, drbrain@segment7.net] +* next_week respects DST changes. #6483, #5617, #2353, #2509, #4551 [marclove, Rob Biedenharn, rails@roetzel.de, jsolson@damogran.org, drbrain@segment7.net] * Expose methods added to Enumerable in the documentation, such as group_by. Closes #6170. [sergeykojin@gmail.com, Marcel Molina Jr.] @@ -638,9 +651,9 @@ public for compatibility. [Jeremy Kemper] * Hash#to_xml supports Bignum and BigDecimal. #6313 [edibiase] -* Don't undefine #class in OptionMerger [Rick] +* Don't undefine #class in OptionMerger [Rick Olson] -* Hash.create_from_xml has been renamed to Hash.from_xml, alias will exist until Rails 2.0 [DHH] +* Hash.create_from_xml has been renamed to Hash.from_xml, alias will exist until Rails 2.0 [David Heinemeier Hansson] * alias_method_chain works with accessor= methods also. #6153 [Caio Chassot] @@ -692,13 +705,13 @@ public for compatibility. [Jeremy Kemper] self.attr_internal_naming_format = '@%s__rofl' attr_internal :foo -* Raise fully qualified names upon name errors. #5533 [lars@pinds.com, Nicholas Seckar] +* Raise fully qualified names upon name errors. #5533 [Lars Pind, Nicholas Seckar] * Add extention to obtain the missing constant from NameError instances. [Nicholas Seckar] * Thoroughly document inflections. #5700 [petermichaux@gmail.com] -* Added Module#alias_attribute [Jamis/DHH]. Example: +* Added Module#alias_attribute [Jamis/David Heinemeier Hansson]. Example: class Content < ActiveRecord::Base # has a title attribute @@ -720,23 +733,23 @@ public for compatibility. [Jeremy Kemper] Provide your own per-environment in e.g. config/environments/development.rb: ActiveSupport::Deprecation.behavior = Proc.new { |message| raise message } -* First cut of the Rails Deprecation system. [Koz] +* First cut of the Rails Deprecation system. [Michael Koziarski] * Strip boolean XML content before checking for 'true' [Rick Olson] -* Customize default BigDecimal formatting. References #5672 [dave@pragprog.com] +* Customize default BigDecimal formatting. References #5672 [Dave Thomas] -* Correctly convert <foo nil="true"> to nil when using Hash.create_from_xml. [Rick] +* Correctly convert <foo nil="true"> to nil when using Hash.create_from_xml. [Rick Olson] * Optional identity for Enumerable#sum defaults to zero. #5657 [gensym@mac.com] -* HashWithIndifferentAccess shouldn't confuse false and nil. #5601 [shugo@ruby-lang.org] +* HashWithIndifferentAccess shouldn't confuse false and nil. #5601 [Shugo Maeda] * Fixed HashWithIndifferentAccess#default #5586 [chris@seagul.co.uk] * More compatible Hash.create_from_xml. #5523 [nunemaker@gmail.com] -* Added Enumerable#sum for calculating a sum from the elements [DHH, jonathan@daikini.com]. Examples: +* Added Enumerable#sum for calculating a sum from the elements [David Heinemeier Hansson, jonathan@daikini.com]. Examples: [1, 2, 3].sum payments.sum { |p| p.price * p.tax_rate } @@ -758,7 +771,7 @@ public for compatibility. [Jeremy Kemper] {1 => "one", 2 => "two", 3 => "three"}.sort_by(&:first).map(&:last) #=> ["one", "two", "three"] -* Added Hash.create_from_xml(string) which will create a hash from a XML string and even typecast if possible [DHH]. Example: +* Added Hash.create_from_xml(string) which will create a hash from a XML string and even typecast if possible [David Heinemeier Hansson]. Example: Hash.create_from_xml <<-EOT <note> @@ -771,7 +784,7 @@ public for compatibility. [Jeremy Kemper] { :note => { :title => "This is a note", :created_at => Date.new(2004, 10, 10) } } -* Added Jim Weirich's excellent FlexMock class to vendor (Copyright 2003, 2004 by Jim Weirich (jim@weriichhouse.org)) -- it's not automatically required, though, so require 'flexmock' is still necessary [DHH] +* Added Jim Weirich's excellent FlexMock class to vendor (Copyright 2003, 2004 by Jim Weirich (jim@weriichhouse.org)) -- it's not automatically required, though, so require 'flexmock' is still necessary [David Heinemeier Hansson] * Fixed that Module#alias_method_chain should work with both foo? foo! and foo at the same time #4954 [anna@wota.jp] @@ -779,13 +792,13 @@ public for compatibility. [Jeremy Kemper] * Add OrderedHash#values. [Sam Stephenson] -* Added Array#to_s(:db) that'll produce a comma-separated list of ids [DHH]. Example: +* Added Array#to_s(:db) that'll produce a comma-separated list of ids [David Heinemeier Hansson]. Example: Purchase.find(:all, :conditions => "product_id IN (#{shops.products.to_s(:db)})" * Normalize classify's argument to a String so that it plays nice with Symbols. [Marcel Molina Jr.] -* Strip out leading schema name in classify. References #5139. [schoenm@earthlink.net] +* Strip out leading schema name in classify. References #5139. [Michael Schoen] * Remove Enumerable#first_match since break(value) handles the use case well enough. [Nicholas Seckar] @@ -817,7 +830,7 @@ public for compatibility. [Jeremy Kemper] * Added Module#alias_method_chain [Jamis Buck] -* Updated to Builder 2.0 [DHH] +* Updated to Builder 2.0 [David Heinemeier Hansson] * Add Array#split for dividing arrays into one or more subarrays by value or block. [Sam Stephenson] @@ -848,7 +861,7 @@ public for compatibility. [Jeremy Kemper] * Added Fixnum#seconds for consistency, so you can say 5.minutes + 30.seconds instead of 5.minutes + 30 #4389 [François Beausoleil] -* Added option to String#camelize to generate lower-cased camel case by passing in :lower, like "super_man".camelize(:lower) # => "superMan" [DHH] +* Added option to String#camelize to generate lower-cased camel case by passing in :lower, like "super_man".camelize(:lower) # => "superMan" [David Heinemeier Hansson] * Added Hash#diff to show the difference between two hashes [Chris McGrath] @@ -856,12 +869,12 @@ public for compatibility. [Jeremy Kemper] * Enhance Inflector.underscore to convert '-' into '_' (as the inverse of Inflector.dasherize) [Jamis Buck] -* Switched to_xml to use the xml schema format for datetimes. This allows the encoding of time zones and should improve operability. [Koz] +* Switched to_xml to use the xml schema format for datetimes. This allows the encoding of time zones and should improve operability. [Michael Koziarski] * Added a note to the documentation for the Date related Numeric extensions to indicate that they're -approximations and shouldn't be used for critical calculations. [Koz] +approximations and shouldn't be used for critical calculations. [Michael Koziarski] -* Added Hash#to_xml and Array#to_xml that makes it much easier to produce XML from basic structures [DHH]. Examples: +* Added Hash#to_xml and Array#to_xml that makes it much easier to produce XML from basic structures [David Heinemeier Hansson]. Examples: { :name => "David", :street_name => "Paulina", :age => 26, :moved_on => Date.new(2005, 11, 15) }.to_xml @@ -874,7 +887,7 @@ approximations and shouldn't be used for critical calculations. [Koz] <moved-on type="date">2005-11-15</moved-on> </person> -* Moved Jim Weirich's wonderful Builder from Action Pack to Active Support (it's simply too useful to be stuck in AP) [DHH] +* Moved Jim Weirich's wonderful Builder from Action Pack to Active Support (it's simply too useful to be stuck in AP) [David Heinemeier Hansson] * Fixed that Array#to_sentence will return "" on an empty array instead of ", and" #3842, #4031 [rubyonrails@beautifulpixel.com] @@ -903,7 +916,7 @@ approximations and shouldn't be used for critical calculations. [Koz] [Marcel Molina Jr., Sam Stephenson] -* Added Kernel#daemonize to turn the current process into a daemon that can be killed with a TERM signal [DHH] +* Added Kernel#daemonize to turn the current process into a daemon that can be killed with a TERM signal [David Heinemeier Hansson] * Add 'around' methods to Logger, to make it easy to log before and after messages for a given block as requested in #3809. [Michael Koziarski] Example: @@ -918,7 +931,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Make String#last return the string instead of nil when it is shorter than the limit [Scott Barron]. -* Added delegation support to Module that allows multiple delegations at once (unlike Forwardable in the stdlib) [DHH]. Example: +* Added delegation support to Module that allows multiple delegations at once (unlike Forwardable in the stdlib) [David Heinemeier Hansson]. Example: class Account < ActiveRecord::Base has_one :subscription @@ -953,7 +966,7 @@ approximations and shouldn't be used for critical calculations. [Koz] include Reloadable end - Reloading a class is done by removing its constant which will cause it to be loaded again on the next reference. [DHH] + Reloading a class is done by removing its constant which will cause it to be loaded again on the next reference. [David Heinemeier Hansson] * Added auto-loading support for classes in modules, so Conductor::Migration will look for conductor/migration.rb and Conductor::Database::Settings will look for conductor/database/settings.rb [Nicholas Seckar] @@ -961,7 +974,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Add Proc#bind(object) for changing a proc or block's self by returning a Method bound to the given object. Based on why the lucky stiff's "cloaker" method. [Sam Stephenson] -* Fix merge and dup for hashes with indifferent access #3404 [kenneth.miller@bitfield.net] +* Fix merge and dup for hashes with indifferent access #3404 [Ken Miller] * Fix the requires in option_merger_test to unbreak AS tests. [Sam Stephenson] @@ -1068,7 +1081,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Fixed clean logger to work with Ruby 1.8.3 Logger class #2245 -* Fixed memory leak with Active Record classes when Dependencies.mechanism = :load #1704 [c.r.mcgrath@gmail.com] +* Fixed memory leak with Active Record classes when Dependencies.mechanism = :load #1704 [Chris McGrath] * Fixed Inflector.underscore for use with acronyms, so HTML becomes html instead of htm_l #2173 [k@v2studio.com] @@ -1078,11 +1091,11 @@ approximations and shouldn't be used for critical calculations. [Koz] * Added Hash#reverse_merge, Hash#reverse_merge!, and Hash#reverse_update to ease the use of default options -* Added Array#to_sentence that'll turn ['one', 'two', 'three'] into "one, two, and three" #2157 [m.stienstra@fngtps.com] +* Added Array#to_sentence that'll turn ['one', 'two', 'three'] into "one, two, and three" #2157 [Manfred Stienstra] * Added Kernel#silence_warnings to turn off warnings temporarily for the passed block -* Added String#starts_with? and String#ends_with? #2118 [thijs@vandervossen.net] +* Added String#starts_with? and String#ends_with? #2118 [Thijs van der Vossen] * Added easy extendability to the inflector through Inflector.inflections (using the Inflector::Inflections singleton class). Examples: @@ -1125,7 +1138,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Added new rules to the Inflector to deal with more unusual plurals mouse/louse => mice/lice, information => information, ox => oxen, virus => viri, archive => archives #1571, #1583, #1490, #1599, #1608 [foamdino@gmail.com/others] -* Fixed memory leak with Object#remove_subclasses_of, which inflicted a Rails application running in development mode with a ~20KB leak per request #1289 [c.r.mcgrath@gmail.com] +* Fixed memory leak with Object#remove_subclasses_of, which inflicted a Rails application running in development mode with a ~20KB leak per request #1289 [Chris McGrath] * Made 1.year == 365.25.days to account for leap years. This allows you to do User.find(:all, :conditions => ['birthday > ?', 50.years.ago]) without losing a lot of days. #1488 [tuxie@dekadance.se] @@ -1160,7 +1173,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 [Nicholas Seckar] -* Fixed inflection of perspectives and similar words #1045 [thijs@vandervossen.net] +* Fixed inflection of perspectives and similar words #1045 [Thijs van der Vossen] * Added Fixnum#even? and Fixnum#odd? @@ -1202,7 +1215,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Added inflection rules for "sh" words, like "wish" and "fish" #755 [phillip@pjbsoftware.com] -* Fixed an exception when using Ajax based requests from Safari because Safari appends a \000 to the post body. Symbols can't have \000 in them so indifferent access would throw an exception in the constructor. Indifferent hashes now use strings internally instead. #746 [Tobias Luetke] +* Fixed an exception when using Ajax based requests from Safari because Safari appends a \000 to the post body. Symbols can't have \000 in them so indifferent access would throw an exception in the constructor. Indifferent hashes now use strings internally instead. #746 [Tobias Lütke] * Added String#to_time and String#to_date for wrapping ParseDate @@ -1268,7 +1281,7 @@ approximations and shouldn't be used for critical calculations. [Koz] * Added Inflections as an extension on String, so Inflector.pluralize(Inflector.classify(name)) becomes name.classify.pluralize #476 [Jeremy Kemper] -* Added Byte operations to Numeric, so 5.5.megabytes + 200.kilobytes #461 [Marcel Molina] +* Added Byte operations to Numeric, so 5.5.megabytes + 200.kilobytes #461 [Marcel Molina Jr.] * Fixed that Dependencies.reload can't load the same file twice #420 [Kent Sibilev] diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb index b2c863c893..33bcf327f8 100644 --- a/activesupport/lib/active_support/buffered_logger.rb +++ b/activesupport/lib/active_support/buffered_logger.rb @@ -68,13 +68,13 @@ module ActiveSupport for severity in Severity.constants class_eval <<-EOT, __FILE__, __LINE__ - def #{severity.downcase}(message = nil, progname = nil, &block) - add(#{severity}, message, progname, &block) - end - - def #{severity.downcase}? - #{severity} >= @level - end + def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block) + add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block) + end # end + # + def #{severity.downcase}? # def debug? + #{severity} >= @level # DEBUG >= @level + end # end EOT end @@ -96,9 +96,12 @@ module ActiveSupport @guard.synchronize do unless buffer.empty? old_buffer = buffer - clear_buffer @log.write(old_buffer.join) end + + # Important to do this even if buffer was empty or else @buffer will + # accumulate empty arrays for each request where nothing was logged. + clear_buffer end end diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 10281d60eb..6a6c861458 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -143,13 +143,13 @@ module ActiveSupport log("miss", key, options) value = nil - seconds = Benchmark.realtime { value = yield } + ms = Benchmark.ms { value = yield } @logger_off = true write(key, value, options) @logger_off = false - log("write (will save #{'%.2f' % (seconds * 1000)}ms)", key, nil) + log('write (will save %.2fms)' % ms, key, nil) value end diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 5cdcaf5ad1..86e66e0588 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -192,13 +192,8 @@ module ActiveSupport end def should_run_callback?(*args) - if options[:if] - evaluate_method(options[:if], *args) - elsif options[:unless] - !evaluate_method(options[:unless], *args) - else - true - end + [options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } && + ![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) } end end @@ -210,20 +205,24 @@ module ActiveSupport def define_callbacks(*callbacks) callbacks.each do |callback| class_eval <<-"end_eval" - def self.#{callback}(*methods, &block) - callbacks = CallbackChain.build(:#{callback}, *methods, &block) - (@#{callback}_callbacks ||= CallbackChain.new).concat callbacks - end - - def self.#{callback}_callback_chain - @#{callback}_callbacks ||= CallbackChain.new - - if superclass.respond_to?(:#{callback}_callback_chain) - CallbackChain.new(superclass.#{callback}_callback_chain + @#{callback}_callbacks) - else - @#{callback}_callbacks - end - end + def self.#{callback}(*methods, &block) # def self.before_save(*methods, &block) + callbacks = CallbackChain.build(:#{callback}, *methods, &block) # callbacks = CallbackChain.build(:before_save, *methods, &block) + @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new + @#{callback}_callbacks.concat callbacks # @before_save_callbacks.concat callbacks + end # end + # + def self.#{callback}_callback_chain # def self.before_save_callback_chain + @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new + # + if superclass.respond_to?(:#{callback}_callback_chain) # if superclass.respond_to?(:before_save_callback_chain) + CallbackChain.new( # CallbackChain.new( + superclass.#{callback}_callback_chain + # superclass.before_save_callback_chain + + @#{callback}_callbacks # @before_save_callbacks + ) # ) + else # else + @#{callback}_callbacks # @before_save_callbacks + end # end + end # end end_eval end end diff --git a/activesupport/lib/active_support/core_ext/benchmark.rb b/activesupport/lib/active_support/core_ext/benchmark.rb index 79ba165e3a..ae57b152e8 100644 --- a/activesupport/lib/active_support/core_ext/benchmark.rb +++ b/activesupport/lib/active_support/core_ext/benchmark.rb @@ -1,12 +1,19 @@ require 'benchmark' class << Benchmark - remove_method :realtime + # Earlier Ruby had a slower implementation. + if RUBY_VERSION < '1.8.7' + remove_method :realtime - def realtime - r0 = Time.now - yield - r1 = Time.now - r1.to_f - r0.to_f + def realtime + r0 = Time.now + yield + r1 = Time.now + r1.to_f - r0.to_f + end + end + + def ms + 1000 * realtime { yield } end end diff --git a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb index 186ca69c05..c795871474 100644 --- a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb +++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb @@ -11,17 +11,17 @@ class Class syms.flatten.each do |sym| next if sym.is_a?(Hash) class_eval(<<-EOS, __FILE__, __LINE__) - unless defined? @@#{sym} - @@#{sym} = nil - end - - def self.#{sym} - @@#{sym} - end - - def #{sym} - @@#{sym} - end + unless defined? @@#{sym} # unless defined? @@hair_colors + @@#{sym} = nil # @@hair_colors = nil + end # end + # + def self.#{sym} # def self.hair_colors + @@#{sym} # @@hair_colors + end # end + # + def #{sym} # def hair_colors + @@#{sym} # @@hair_colors + end # end EOS end end @@ -30,19 +30,19 @@ class Class options = syms.extract_options! syms.flatten.each do |sym| class_eval(<<-EOS, __FILE__, __LINE__) - unless defined? @@#{sym} - @@#{sym} = nil - end - - def self.#{sym}=(obj) - @@#{sym} = obj - end - - #{" - def #{sym}=(obj) - @@#{sym} = obj - end - " unless options[:instance_writer] == false } + unless defined? @@#{sym} # unless defined? @@hair_colors + @@#{sym} = nil # @@hair_colors = nil + end # end + # + def self.#{sym}=(obj) # def self.hair_colors=(obj) + @@#{sym} = obj # @@hair_colors = obj + end # end + # + #{" # + def #{sym}=(obj) # def hair_colors=(obj) + @@#{sym} = obj # @@hair_colors = obj + end # end + " unless options[:instance_writer] == false } # # instance writer above is generated unless options[:instance_writer] == false EOS end end diff --git a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb index 368317df9b..000ccf4d55 100644 --- a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb @@ -9,22 +9,23 @@ class Class class_name_to_stop_searching_on = self.superclass.name.blank? ? "Object" : self.superclass.name names.each do |name| class_eval <<-EOS - def self.#{name} - if defined?(@#{name}) - @#{name} - elsif superclass < #{class_name_to_stop_searching_on} && superclass.respond_to?(:#{name}) - superclass.#{name} - end - end - def #{name} - self.class.#{name} - end - def self.#{name}? - !!#{name} - end - def #{name}? - !!#{name} - end + def self.#{name} # def self.only_reader + if defined?(@#{name}) # if defined?(@only_reader) + @#{name} # @only_reader + elsif superclass < #{class_name_to_stop_searching_on} && # elsif superclass < Object && + superclass.respond_to?(:#{name}) # superclass.respond_to?(:only_reader) + superclass.#{name} # superclass.only_reader + end # end + end # end + def #{name} # def only_reader + self.class.#{name} # self.class.only_reader + end # end + def self.#{name}? # def self.only_reader? + !!#{name} # !!only_reader + end # end + def #{name}? # def only_reader? + !!#{name} # !!only_reader + end # end EOS end end @@ -32,9 +33,9 @@ class Class def superclass_delegating_writer(*names) names.each do |name| class_eval <<-EOS - def self.#{name}=(value) - @#{name} = value - end + def self.#{name}=(value) # def self.only_writer=(value) + @#{name} = value # @only_writer = value + end # end EOS end end diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb index e6143a274b..1794afe77c 100644 --- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb @@ -11,13 +11,13 @@ class Class # :nodoc: syms.each do |sym| next if sym.is_a?(Hash) class_eval <<-EOS - def self.#{sym} - read_inheritable_attribute(:#{sym}) - end - - def #{sym} - self.class.#{sym} - end + def self.#{sym} # def self.before_add_for_comments + read_inheritable_attribute(:#{sym}) # read_inheritable_attribute(:before_add_for_comments) + end # end + # + def #{sym} # def before_add_for_comments + self.class.#{sym} # self.class.before_add_for_comments + end # end EOS end end @@ -26,15 +26,15 @@ class Class # :nodoc: options = syms.extract_options! syms.each do |sym| class_eval <<-EOS - def self.#{sym}=(obj) - write_inheritable_attribute(:#{sym}, obj) - end - - #{" - def #{sym}=(obj) - self.class.#{sym} = obj - end - " unless options[:instance_writer] == false } + def self.#{sym}=(obj) # def self.color=(obj) + write_inheritable_attribute(:#{sym}, obj) # write_inheritable_attribute(:color, obj) + end # end + # + #{" # + def #{sym}=(obj) # def color=(obj) + self.class.#{sym} = obj # self.class.color = obj + end # end + " unless options[:instance_writer] == false } # # the writer above is generated unless options[:instance_writer] == false EOS end end @@ -43,15 +43,15 @@ class Class # :nodoc: options = syms.extract_options! syms.each do |sym| class_eval <<-EOS - def self.#{sym}=(obj) - write_inheritable_array(:#{sym}, obj) - end - - #{" - def #{sym}=(obj) - self.class.#{sym} = obj - end - " unless options[:instance_writer] == false } + def self.#{sym}=(obj) # def self.levels=(obj) + write_inheritable_array(:#{sym}, obj) # write_inheritable_array(:levels, obj) + end # end + # + #{" # + def #{sym}=(obj) # def levels=(obj) + self.class.#{sym} = obj # self.class.levels = obj + end # end + " unless options[:instance_writer] == false } # # the writer above is generated unless options[:instance_writer] == false EOS end end @@ -60,15 +60,15 @@ class Class # :nodoc: options = syms.extract_options! syms.each do |sym| class_eval <<-EOS - def self.#{sym}=(obj) - write_inheritable_hash(:#{sym}, obj) - end - - #{" - def #{sym}=(obj) - self.class.#{sym} = obj - end - " unless options[:instance_writer] == false } + def self.#{sym}=(obj) # def self.nicknames=(obj) + write_inheritable_hash(:#{sym}, obj) # write_inheritable_hash(:nicknames, obj) + end # end + # + #{" # + def #{sym}=(obj) # def nicknames=(obj) + self.class.#{sym} = obj # self.class.nicknames = obj + end # end + " unless options[:instance_writer] == false } # # the writer above is generated unless options[:instance_writer] == false EOS 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 437b44c51c..a254e45624 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -94,8 +94,7 @@ module ActiveSupport #:nodoc: options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]), :root => "hash" }) options[:builder].instruct! unless options.delete(:skip_instruct) - dasherize = !options.has_key?(:dasherize) || options[:dasherize] - root = dasherize ? options[:root].to_s.dasherize : options[:root].to_s + root = rename_key(options[:root].to_s, options) options[:builder].__send__(:method_missing, root) do each do |key, value| @@ -122,7 +121,7 @@ module ActiveSupport #:nodoc: else type_name = XML_TYPE_NAMES[value.class.name] - key = dasherize ? key.to_s.dasherize : key.to_s + key = rename_key(key.to_s, options) attributes = options[:skip_types] || value.nil? || type_name.nil? ? { } : { :type => type_name } if value.nil? @@ -142,9 +141,16 @@ module ActiveSupport #:nodoc: end + def rename_key(key, options = {}) + camelize = options.has_key?(:camelize) && options[:camelize] + dasherize = !options.has_key?(:dasherize) || options[:dasherize] + key = key.camelize if camelize + dasherize ? key.dasherize : key + end + module ClassMethods def from_xml(xml) - typecast_xml_value(undasherize_keys(XmlMini.parse(xml))) + typecast_xml_value(unrename_keys(XmlMini.parse(xml))) end private @@ -210,15 +216,15 @@ module ActiveSupport #:nodoc: end end - def undasherize_keys(params) + def unrename_keys(params) case params.class.to_s when "Hash" params.inject({}) do |h,(k,v)| - h[k.to_s.tr("-", "_")] = undasherize_keys(v) + h[k.to_s.underscore.tr("-", "_")] = unrename_keys(v) h end when "Array" - params.map { |v| undasherize_keys(v) } + params.map { |v| unrename_keys(v) } else params end diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb index 88df49a69f..d845a6d8ca 100644 --- a/activesupport/lib/active_support/core_ext/hash/slice.rb +++ b/activesupport/lib/active_support/core_ext/hash/slice.rb @@ -24,10 +24,17 @@ module ActiveSupport #:nodoc: end # Replaces the hash with only the given keys. + # Returns a hash contained the removed key/value pairs + # {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d =>4} def slice!(*keys) - replace(slice(*keys)) + keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) + omit = slice(*self.keys - keys) + hash = slice(*keys) + replace(hash) + omit end end end end end + diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb index 24fe7294c9..858da7aa07 100644 --- a/activesupport/lib/active_support/core_ext/logger.rb +++ b/activesupport/lib/active_support/core_ext/logger.rb @@ -3,12 +3,12 @@ class Logger def self.define_around_helper(level) module_eval <<-end_eval - def around_#{level}(before_message, after_message, &block) - self.#{level}(before_message) - return_value = block.call(self) - self.#{level}(after_message) - return return_value - end + def around_#{level}(before_message, after_message, &block) # def around_debug(before_message, after_message, &block) + self.#{level}(before_message) # self.debug(before_message) + return_value = block.call(self) # return_value = block.call(self) + self.#{level}(after_message) # self.debug(after_message) + return return_value # return return_value + end # end end_eval end [:debug, :info, :error, :fatal].each {|level| define_around_helper(level) } diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb index e640f64520..10fa520ba1 100644 --- a/activesupport/lib/active_support/core_ext/module/aliasing.rb +++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb @@ -64,9 +64,9 @@ module ActiveSupport # e.title # => "Megastars" def alias_attribute(new_name, old_name) module_eval <<-STR, __FILE__, __LINE__+1 - def #{new_name}; self.#{old_name}; end - def #{new_name}?; self.#{old_name}?; end - def #{new_name}=(v); self.#{old_name} = v; end + def #{new_name}; self.#{old_name}; end # def subject; self.title; end + def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end + def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end STR end end diff --git a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb index 683789d853..4d0198f028 100644 --- a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb +++ b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb @@ -22,10 +22,10 @@ class Module raise 'Default value or block required' unless !default.nil? || block define_method(sym, block_given? ? block : Proc.new { default }) module_eval(<<-EVAL, __FILE__, __LINE__) - def #{sym}=(value) - class << self; attr_reader :#{sym} end - @#{sym} = value - end + def #{sym}=(value) # def age=(value) + class << self; attr_reader :#{sym} end # class << self; attr_reader :age end + @#{sym} = value # @age = value + end # end EVAL end end diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb index 51e1c9af90..9402cb8534 100644 --- a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb +++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb @@ -15,17 +15,17 @@ class Module syms.each do |sym| next if sym.is_a?(Hash) class_eval(<<-EOS, __FILE__, __LINE__) - unless defined? @@#{sym} - @@#{sym} = nil - end - - def self.#{sym} - @@#{sym} - end - - def #{sym} - @@#{sym} - end + unless defined? @@#{sym} # unless defined? @@pagination_options + @@#{sym} = nil # @@pagination_options = nil + end # end + # + def self.#{sym} # def self.pagination_options + @@#{sym} # @@pagination_options + end # end + # + def #{sym} # def pagination_options + @@#{sym} # @@pagination_options + end # end EOS end end @@ -34,19 +34,19 @@ class Module options = syms.extract_options! syms.each do |sym| class_eval(<<-EOS, __FILE__, __LINE__) - unless defined? @@#{sym} - @@#{sym} = nil - end - - def self.#{sym}=(obj) - @@#{sym} = obj - end - - #{" - def #{sym}=(obj) - @@#{sym} = obj - end - " unless options[:instance_writer] == false } + unless defined? @@#{sym} # unless defined? @@pagination_options + @@#{sym} = nil # @@pagination_options = nil + end # end + # + def self.#{sym}=(obj) # def self.pagination_options=(obj) + @@#{sym} = obj # @@pagination_options = obj + end # end + # + #{" # + def #{sym}=(obj) # def pagination_options=(obj) + @@#{sym} = obj # @@pagination_options = obj + end # end + " unless options[:instance_writer] == false } # # instance writer above is generated unless options[:instance_writer] == false EOS end end diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index 2905eebc85..fb4b5f0f3c 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -72,6 +72,30 @@ class Module # invoice.customer_name # => "John Doe" # invoice.customer_address # => "Vimmersvej 13" # + # If the object to which you delegate can be nil, you may want to use the + # :allow_nil option. In that case, it returns nil instead of raising a + # NoMethodError exception: + # + # class Foo + # attr_accessor :bar + # def initialize(bar = nil) + # @bar = bar + # end + # delegate :zoo, :to => :bar + # end + # + # Foo.new.zoo # raises NoMethodError exception (you called nil.zoo) + # + # class Foo + # attr_accessor :bar + # def initialize(bar = nil) + # @bar = bar + # end + # delegate :zoo, :to => :bar, :allow_nil => true + # end + # + # Foo.new.zoo # returns nil + # def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] @@ -84,11 +108,13 @@ class Module prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_" + allow_nil = options[:allow_nil] && "#{to} && " + methods.each do |method| module_eval(<<-EOS, "(__DELEGATION__)", 1) - def #{prefix}#{method}(*args, &block) - #{to}.__send__(#{method.inspect}, *args, &block) - end + def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block) + #{allow_nil}#{to}.__send__(#{method.inspect}, *args, &block) # client && client.__send__(:name, *args, &block) + end # end EOS end end diff --git a/activesupport/lib/active_support/core_ext/module/synchronization.rb b/activesupport/lib/active_support/core_ext/module/synchronization.rb index 251606024e..069db3fed0 100644 --- a/activesupport/lib/active_support/core_ext/module/synchronization.rb +++ b/activesupport/lib/active_support/core_ext/module/synchronization.rb @@ -26,11 +26,11 @@ class Module end module_eval(<<-EOS, __FILE__, __LINE__) - def #{aliased_method}_with_synchronization#{punctuation}(*args, &block) - #{with}.synchronize do - #{aliased_method}_without_synchronization#{punctuation}(*args, &block) - end - end + def #{aliased_method}_with_synchronization#{punctuation}(*args, &block) # def expire_with_synchronization(*args, &block) + #{with}.synchronize do # @@lock.synchronize do + #{aliased_method}_without_synchronization#{punctuation}(*args, &block) # expire_without_synchronization(*args, &block) + end # end + end # end EOS alias_method_chain method, :synchronization diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index 46f9c7d676..4570570bbc 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -40,6 +40,21 @@ class Object value end + # Yields <code>x</code> to the block, and then returns <code>x</code>. + # The primary purpose of this method is to "tap into" a method chain, + # in order to perform operations on intermediate results within the chain. + # + # (1..10).tap { |x| puts "original: #{x.inspect}" }.to_a. + # tap { |x| puts "array: #{x.inspect}" }. + # select { |x| x%2 == 0 }. + # tap { |x| puts "evens: #{x.inspect}" }. + # map { |x| x*x }. + # tap { |x| puts "squares: #{x.inspect}" } + def tap + yield self + self + end unless Object.respond_to?(:tap) + # An elegant way to factor duplication out of options passed to a series of # method calls. Each method called in the block, with the block variable as # the receiver, will have its options merged with the default +options+ hash diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 293450c180..7ce9adec2c 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -559,9 +559,9 @@ module ActiveSupport #:nodoc: # Old style environment.rb referenced this method directly. Please note, it doesn't # actually *do* anything any more. def self.root(*args) - if defined?(RAILS_DEFAULT_LOGGER) - RAILS_DEFAULT_LOGGER.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases." - RAILS_DEFAULT_LOGGER.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19" + if defined?(Rails) && Rails.logger + Rails.logger.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases." + Rails.logger.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19" end end end diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb index 543e3b08d2..d20151661b 100644 --- a/activesupport/lib/active_support/deprecation.rb +++ b/activesupport/lib/active_support/deprecation.rb @@ -13,7 +13,7 @@ module ActiveSupport $stderr.puts callstack.join("\n ") if debug }, 'development' => Proc.new { |message, callstack| - logger = defined?(::RAILS_DEFAULT_LOGGER) ? ::RAILS_DEFAULT_LOGGER : Logger.new($stderr) + logger = defined?(Rails) ? Rails.logger : Logger.new($stderr) logger.warn message logger.debug callstack.join("\n ") if debug } @@ -90,10 +90,15 @@ module ActiveSupport method_names.each do |method_name| alias_method_chain(method_name, :deprecation) do |target, punctuation| class_eval(<<-EOS, __FILE__, __LINE__) - def #{target}_with_deprecation#{punctuation}(*args, &block) - ::ActiveSupport::Deprecation.warn(self.class.deprecated_method_warning(:#{method_name}, #{options[method_name].inspect}), caller) - #{target}_without_deprecation#{punctuation}(*args, &block) - end + def #{target}_with_deprecation#{punctuation}(*args, &block) # def generate_secret_with_deprecation(*args, &block) + ::ActiveSupport::Deprecation.warn( # ::ActiveSupport::Deprecation.warn( + self.class.deprecated_method_warning( # self.class.deprecated_method_warning( + :#{method_name}, # :generate_secret, + #{options[method_name].inspect}), # "You should use ActiveSupport::SecureRandom.hex(64)"), + caller # caller + ) # ) + #{target}_without_deprecation#{punctuation}(*args, &block) # generate_secret_without_deprecation(*args, &block) + end # end EOS end end diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb index fdb219dbf7..9da4048272 100644 --- a/activesupport/lib/active_support/json/decoding.rb +++ b/activesupport/lib/active_support/json/decoding.rb @@ -16,7 +16,7 @@ module ActiveSupport protected # matches YAML-formatted dates - DATE_REGEX = /^\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?$/ + DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?)$/ # Ensure that ":" and "," are always followed by a space def convert_json_to_yaml(json) #:nodoc: diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb index 9f2fd3a401..952b4d8063 100644 --- a/activesupport/lib/active_support/memoizable.rb +++ b/activesupport/lib/active_support/memoizable.rb @@ -59,34 +59,36 @@ module ActiveSupport memoized_ivar = ActiveSupport::Memoizable.memoized_ivar_for(symbol) class_eval <<-EOS, __FILE__, __LINE__ - include InstanceMethods - - raise "Already memoized #{symbol}" if method_defined?(:#{original_method}) - alias #{original_method} #{symbol} - - if instance_method(:#{symbol}).arity == 0 - def #{symbol}(reload = false) - if reload || !defined?(#{memoized_ivar}) || #{memoized_ivar}.empty? - #{memoized_ivar} = [#{original_method}.freeze] - end - #{memoized_ivar}[0] - end - else - def #{symbol}(*args) - #{memoized_ivar} ||= {} unless frozen? - reload = args.pop if args.last == true || args.last == :reload - - if defined?(#{memoized_ivar}) && #{memoized_ivar} - if !reload && #{memoized_ivar}.has_key?(args) - #{memoized_ivar}[args] - elsif #{memoized_ivar} - #{memoized_ivar}[args] = #{original_method}(*args).freeze - end - else - #{original_method}(*args) - end - end - end + include InstanceMethods # include InstanceMethods + # + if method_defined?(:#{original_method}) # if method_defined?(:_unmemoized_mime_type) + raise "Already memoized #{symbol}" # raise "Already memoized mime_type" + end # end + alias #{original_method} #{symbol} # alias _unmemoized_mime_type mime_type + # + if instance_method(:#{symbol}).arity == 0 # if instance_method(:mime_type).arity == 0 + def #{symbol}(reload = false) # def mime_type(reload = false) + if reload || !defined?(#{memoized_ivar}) || #{memoized_ivar}.empty? # if reload || !defined?(@_memoized_mime_type) || @_memoized_mime_type.empty? + #{memoized_ivar} = [#{original_method}.freeze] # @_memoized_mime_type = [_unmemoized_mime_type.freeze] + end # end + #{memoized_ivar}[0] # @_memoized_mime_type[0] + end # end + else # else + def #{symbol}(*args) # def mime_type(*args) + #{memoized_ivar} ||= {} unless frozen? # @_memoized_mime_type ||= {} unless frozen? + reload = args.pop if args.last == true || args.last == :reload # reload = args.pop if args.last == true || args.last == :reload + # + if defined?(#{memoized_ivar}) && #{memoized_ivar} # if defined?(@_memoized_mime_type) && @_memoized_mime_type + if !reload && #{memoized_ivar}.has_key?(args) # if !reload && @_memoized_mime_type.has_key?(args) + #{memoized_ivar}[args] # @_memoized_mime_type[args] + elsif #{memoized_ivar} # elsif @_memoized_mime_type + #{memoized_ivar}[args] = #{original_method}(*args).freeze # @_memoized_mime_type[args] = _unmemoized_mime_type(*args).freeze + end # end + else # else + #{original_method}(*args) # _unmemoized_mime_type(*args) + end # end + end # end + end # end EOS end end diff --git a/activesupport/lib/active_support/multibyte/unicode_database.rb b/activesupport/lib/active_support/multibyte/unicode_database.rb index 3b8cf8f9eb..a08f38cdbb 100644 --- a/activesupport/lib/active_support/multibyte/unicode_database.rb +++ b/activesupport/lib/active_support/multibyte/unicode_database.rb @@ -24,10 +24,10 @@ module ActiveSupport #:nodoc: # Lazy load the Unicode database so it's only loaded when it's actually used ATTRIBUTES.each do |attr_name| class_eval(<<-EOS, __FILE__, __LINE__) - def #{attr_name} - load - @#{attr_name} - end + def #{attr_name} # def codepoints + load # load + @#{attr_name} # @codepoints + end # end EOS end diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 5de94c67e0..3def0be639 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -4,62 +4,85 @@ module ActiveSupport if RUBY_VERSION >= '1.9' OrderedHash = ::Hash else - class OrderedHash < Array #:nodoc: + class OrderedHash < Hash #:nodoc: + def initialize(*args, &block) + super + @keys = [] + end + def []=(key, value) - if pair = assoc(key) - pair.pop - pair << value - else - self << [key, value] + if !has_key?(key) + @keys << key end - value + super end - def [](key) - pair = assoc(key) - pair ? pair.last : nil + def delete(key) + if has_key? key + index = @keys.index(key) + @keys.delete_at index + end + super end - def delete(key) - pair = assoc(key) - pair ? array_index = index(pair) : nil - array_index ? delete_at(array_index).last : nil + def reject! + super + sync_keys! + self + end + + def reject(&block) + dup.reject!(&block) end def keys - collect { |key, value| key } + @keys end def values - collect { |key, value| value } + @keys.collect { |key| self[key] } end def to_hash - returning({}) do |hash| - each { |array| hash[array[0]] = array[1] } - end + Hash.new(self) + end + + def each_key + @keys.each { |key| yield key } + end + + def each_value + @keys.each { |key| yield self[key]} end - def has_key?(k) - !assoc(k).nil? + def each + keys.each {|key| yield [key, self[key]]} end - alias_method :key?, :has_key? - alias_method :include?, :has_key? - alias_method :member?, :has_key? + alias_method :each_pair, :each - def has_value?(v) - any? { |key, value| value == v } + def clear + super + @keys.clear + self end - alias_method :value?, :has_value? + def shift + k = @keys.first + v = delete(k) + [k, v] + end - def each_key - each { |key, value| yield key } + def merge(other_hash) + result = dup + other_hash.each {|k,v| result[k]=v} + result end - def each_value - each { |key, value| yield value } + private + + def sync_keys! + @keys.delete_if {|k| !has_key?(k)} end end end diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb index bd136c2596..f8d12e82b3 100644 --- a/activesupport/lib/active_support/testing/performance.rb +++ b/activesupport/lib/active_support/testing/performance.rb @@ -12,7 +12,7 @@ module ActiveSupport if benchmark = ARGV.include?('--benchmark') # HAX for rake test { :benchmark => true, :runs => 4, - :metrics => [:process_time, :memory, :objects, :gc_runs, :gc_time], + :metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time], :output => 'tmp/performance' } else { :benchmark => false, diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 9a2d283b30..99be89fdf0 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -199,7 +199,7 @@ module ActiveSupport # If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time, # otherwise move backwards #utc, for accuracy when moving across DST boundaries if other.acts_like?(:time) - utc - other + utc.to_f - other.to_f elsif duration_of_variable_length?(other) method_missing(:-, other) else @@ -234,9 +234,9 @@ module ActiveSupport %w(year mon month day mday wday yday hour min sec to_date).each do |method_name| class_eval <<-EOV - def #{method_name} - time.#{method_name} - end + def #{method_name} # def year + time.#{method_name} # time.year + end # end EOV end diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb index 463610722c..3d7d52ca71 100644 --- a/activesupport/lib/active_support/vendor.rb +++ b/activesupport/lib/active_support/vendor.rb @@ -9,9 +9,9 @@ end require 'builder' begin - gem 'memcache-client', '~> 1.5.1' + gem 'memcache-client', '~> 1.5.0.5' rescue Gem::LoadError - $:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.1" + $:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.0.5" end begin @@ -22,8 +22,8 @@ end # TODO I18n gem has not been released yet # begin -# gem 'i18n', '~> 0.0.1' +# gem 'i18n', '~> 0.1.1' # rescue Gem::LoadError - $:.unshift "#{File.dirname(__FILE__)}/vendor/i18n-0.0.1" + $:.unshift "#{File.dirname(__FILE__)}/vendor/i18n-0.1.1/lib" require 'i18n' # end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.1/.gitignore b/activesupport/lib/active_support/vendor/i18n-0.1.1/.gitignore new file mode 100644 index 0000000000..0f41a39f89 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +test/rails/fixtures +doc diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.1/MIT-LICENSE b/activesupport/lib/active_support/vendor/i18n-0.1.1/MIT-LICENSE new file mode 100755 index 0000000000..ed8e9ee66d --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/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.1/README.textile b/activesupport/lib/active_support/vendor/i18n-0.1.1/README.textile new file mode 100644 index 0000000000..a07fc8426d --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/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.1/Rakefile b/activesupport/lib/active_support/vendor/i18n-0.1.1/Rakefile new file mode 100644 index 0000000000..2164e13e69 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/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.1/i18n.gemspec b/activesupport/lib/active_support/vendor/i18n-0.1.1/i18n.gemspec new file mode 100644 index 0000000000..14294606bd --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/i18n.gemspec @@ -0,0 +1,27 @@ +Gem::Specification.new do |s| + s.name = "i18n" + s.version = "0.1.1" + s.date = "2008-10-26" + 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.0.1/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/lib/i18n.rb index 2ffe3618b5..b5ad094d0e 100755 --- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/lib/i18n.rb @@ -2,39 +2,39 @@ # 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/) +# Stephan Soller (http://www.arkanis-development.de/) # Copyright:: Copyright (c) 2008 The Ruby i18n Team # License:: MIT require 'i18n/backend/simple' require 'i18n/exceptions' -module I18n +module I18n @@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) + def backend=(backend) @@backend = backend end - - # Returns the current default locale. Defaults to 'en' + + # Returns the current default locale. Defaults to :'en' def default_locale - @@default_locale + @@default_locale end - + # Sets the current default locale. Used to set a custom default locale. - def default_locale=(locale) - @@default_locale = 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 @@ -44,12 +44,12 @@ module I18n def locale=(locale) Thread.current[:locale] = locale 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. # @@ -74,25 +74,25 @@ module I18n def reload! backend.reload! end - - # Translates, pluralizes and interpolates a given key using a given locale, + + # 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. <em>E.g.</em>, ActionView ships with the translation: + # Translation data is organized as a nested hash using the upper-level keys + # as namespaces. <em>E.g.</em>, ActionView ships with the translation: # <tt>:date => {:formats => {:short => "%b %d"}}</tt>. - # - # Translations can be looked up at any level of this hash using the key argument - # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt> + # + # Translations can be looked up at any level of this hash using the key argument + # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt> # returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>. - # - # Key can be either a single key or a dot-separated key (both Strings and Symbols + # + # Key can be either a single key or a dot-separated key (both Strings and Symbols # work). <em>E.g.</em>, 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: @@ -105,9 +105,9 @@ module I18n # # 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. + # the interpolation variable names. # - # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option + # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option # value for the key +bar+ will be interpolated into the translation: # I18n.t :foo, :bar => 'baz' # => 'foo baz' # @@ -116,7 +116,7 @@ module I18n # Translation data can contain pluralized translations. Pluralized translations # are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>. # - # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English + # Note that <tt>I18n::Backend::Simple</tt> 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: @@ -125,9 +125,9 @@ module I18n # These both return the plural version of a pluralized translation: # I18n.t :foo, :count => 0 # => 'Foos' # I18n.t :foo, :count => 2 # => 'Foos' - # - # The <tt>:count</tt> option can be used both for pluralization and interpolation. - # <em>E.g.</em>, with the translation + # + # The <tt>:count</tt> option can be used both for pluralization and interpolation. + # <em>E.g.</em>, with the translation # <tt>:foo => ['{{count}} foo', '{{count}} foos']</tt>, count will # be interpolated to the pluralized translation: # I18n.t :foo, :count => 1 # => '1 foo' @@ -137,11 +137,11 @@ module I18n # This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found: # I18n.t :foo, :default => 'default' # - # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no + # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no # translation for <tt>:foo</tt> was found: # I18n.t :foo, :default => :bar # - # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> + # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> # or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found. # I18n.t :foo, :default => [:bar, 'default'] # @@ -161,9 +161,9 @@ module I18n rescue I18n::ArgumentError => e raise e if options[:raise] send(@@exception_handler, e, locale, key, options) - end + end alias :t :translate - + # Localizes certain objects, such as dates and numbers to local formatting. def localize(object, options = {}) locale = options[:locale] || I18n.locale @@ -171,7 +171,7 @@ module I18n 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 @@ -181,7 +181,7 @@ module I18n 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. @@ -191,4 +191,4 @@ module I18n keys.flatten.map { |k| k.to_sym } end end -end
\ No newline at end of file +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/lib/i18n/backend/simple.rb index bdda55d3fe..d298b3a85a 100644 --- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/lib/i18n/backend/simple.rb @@ -6,21 +6,21 @@ module I18n INTERPOLATION_RESERVED_KEYS = %w(scope default) MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ - # Accepts a list of paths to translation files. Loads translations from + # 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. + + # 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 @@ -41,13 +41,13 @@ module I18n 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 (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>). + + # 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 (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>). 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") @@ -57,14 +57,14 @@ module I18n # 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.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 @@ -79,12 +79,12 @@ module I18n load_translations(*I18n.load_path) @initialized = true end - + def translations @translations ||= {} end - - # Looks up a translation from the translations hash. Returns nil if + + # 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. <tt>currency.format</tt> is regarded the same as @@ -101,19 +101,19 @@ module I18n end end end - - # Evaluates a default translation. + + # 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. - # - # <em>I.e.</em>, <tt>default(locale, [:foo, 'default'])</tt> will return +default+ if + # + # <em>I.e.</em>, <tt>default(locale, [:foo, 'default'])</tt> will return +default+ if # <tt>translate(locale, :foo)</tt> 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| + when Array then default.each do |obj| result = default(locale, obj, options.dup) and return result end and nil end @@ -135,10 +135,10 @@ module I18n end # Interpolates values into a given string. - # - # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X' + # + # 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 <tt>\\</tt> when you want to escape # the <tt>{{...}}</tt> key in a string (once for the string and once for the # interpolation). @@ -167,8 +167,8 @@ module I18n result.force_encoding(original_encoding) if original_encoding result end - - # Loads a single translations file by delegating to #load_rb or + + # 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. @@ -178,19 +178,19 @@ module I18n 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 + + # Loads a YAML translations file. The data must have locales as # toplevel keys. def load_yml(filename) 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) @@ -202,7 +202,7 @@ module I18n 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)| diff --git a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/exceptions.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/lib/i18n/exceptions.rb index 0f3eff1071..b5cea7acb4 100644 --- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/exceptions.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/lib/i18n/exceptions.rb @@ -1,6 +1,6 @@ module I18n class ArgumentError < ::ArgumentError; end - + class InvalidLocale < ArgumentError attr_reader :locale def initialize(locale) @@ -42,7 +42,7 @@ module I18n super "reserved key #{key.inspect} used in #{string.inspect}" end end - + class UnknownFileType < ArgumentError attr_reader :type, :filename def initialize(type, filename) @@ -50,4 +50,4 @@ module I18n super "can not load translations from #{filename}, the file type #{type} is not known" end end -end
\ No newline at end of file +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.1/test/all.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/all.rb new file mode 100644 index 0000000000..353712da49 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/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.1/test/i18n_exceptions_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/i18n_exceptions_test.rb new file mode 100644 index 0000000000..dfcba6901f --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/i18n_exceptions_test.rb @@ -0,0 +1,100 @@ +$:.unshift "lib" + +require 'rubygems' +require 'test/unit' +require 'mocha' +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.1/test/i18n_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/i18n_test.rb new file mode 100644 index 0000000000..bbb35ec809 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/i18n_test.rb @@ -0,0 +1,125 @@ +$:.unshift "lib" + +require 'rubygems' +require 'test/unit' +require 'mocha' +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_raises(I18n::ArgumentError) { I18n.l nil } + end + + def test_localize_object_raises_argument_error + assert_raises(I18n::ArgumentError) { I18n.l Object.new } + end +end diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.1/test/locale/en.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/locale/en.rb new file mode 100644 index 0000000000..6044ce10d9 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/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.1/test/locale/en.yml b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/locale/en.yml new file mode 100644 index 0000000000..0b298c9c0e --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/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.1/test/simple_backend_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/simple_backend_test.rb new file mode 100644 index 0000000000..e181975f38 --- /dev/null +++ b/activesupport/lib/active_support/vendor/i18n-0.1.1/test/simple_backend_test.rb @@ -0,0 +1,502 @@ +# encoding: utf-8 +$:.unshift "lib" + +require 'rubygems' +require 'test/unit' +require 'mocha' +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 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_raises 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_raises(I18n::InvalidLocale){ @backend.translate nil, :bar } + end + + def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_data + assert_raises(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_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, {:one => 'bar'}, 2) } + end + + # def test_interpolate_given_a_string_raises_invalid_pluralization_data + # assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, 'bar', 2) } + # end + # + # def test_interpolate_given_an_array_raises_invalid_pluralization_data + # assert_raises(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_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_raises(I18n::MissingInterpolationArgument) { @backend.send(:interpolate, nil, 'Hi {{name}}!', {}) } + end + + def test_interpolate_given_a_string_containing_a_reserved_key_raises_reserved_interpolation_key + assert_raises(I18n::ReservedInterpolationKey) { @backend.send(:interpolate, nil, '{{default}}', {:default => nil}) } + 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_raises(I18n::ArgumentError) { @backend.localize 'de', nil } + end + + def test_localize_object_raises_argument_error + assert_raises(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_raises(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 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
\ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb b/activesupport/lib/active_support/vendor/memcache-client-1.5.0.5/memcache.rb index 99c9af0398..e90ddf3359 100644 --- a/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb +++ b/activesupport/lib/active_support/vendor/memcache-client-1.5.0.5/memcache.rb @@ -26,36 +26,13 @@ # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +$TESTING = defined?($TESTING) && $TESTING require 'socket' require 'thread' require 'timeout' require 'rubygems' - -class String - - ## - # Uses the ITU-T polynomial in the CRC32 algorithm. - - def crc32_ITU_T - n = length - r = 0xFFFFFFFF - - n.times do |i| - r ^= self[i] - 8.times do - if (r & 1) != 0 then - r = (r>>1) ^ 0xEDB88320 - else - r >>= 1 - end - end - end - - r ^ 0xFFFFFFFF - end - -end +require 'zlib' ## # A Ruby client library for memcached. @@ -69,7 +46,7 @@ class MemCache ## # The version of MemCache you are using. - VERSION = '1.5.0' + VERSION = '1.5.0.5' ## # Default options for the cache object. @@ -78,6 +55,7 @@ class MemCache :namespace => nil, :readonly => false, :multithread => false, + :failover => true } ## @@ -113,6 +91,10 @@ class MemCache attr_reader :servers ## + # Whether this client should failover reads and writes to another server + + attr_accessor :failover + ## # Accepts a list of +servers+ and a list of +opts+. +servers+ may be # omitted. See +servers=+ for acceptable server list arguments. # @@ -148,6 +130,7 @@ class MemCache @namespace = opts[:namespace] @readonly = opts[:readonly] @multithread = opts[:multithread] + @failover = opts[:failover] @mutex = Mutex.new if @multithread @buckets = [] self.servers = servers @@ -182,7 +165,7 @@ class MemCache def servers=(servers) # Create the server objects. - @servers = servers.collect do |server| + @servers = Array(servers).collect do |server| case server when String host, port, weight = server.split ':', 3 @@ -212,15 +195,12 @@ class MemCache # 0. +key+ can not be decremented below 0. def decr(key, amount = 1) - server, cache_key = request_setup key - - if @multithread then - threadsafe_cache_decr server, cache_key, amount - else + raise MemCacheError, "Update of readonly cache" if @readonly + with_server(key) do |server, cache_key| cache_decr server, cache_key, amount end - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err + rescue TypeError => err + handle_error nil, err end ## @@ -228,21 +208,14 @@ class MemCache # unmarshalled. def get(key, raw = false) - server, cache_key = request_setup key - - value = if @multithread then - threadsafe_cache_get server, cache_key - else - cache_get server, cache_key - end - - return nil if value.nil? - - value = Marshal.load value unless raw - - return value - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err + with_server(key) do |server, cache_key| + value = cache_get server, cache_key + return nil if value.nil? + value = Marshal.load value unless raw + return value + end + rescue TypeError => err + handle_error nil, err end ## @@ -280,36 +253,29 @@ class MemCache server_keys.each do |server, keys_for_server| keys_for_server = keys_for_server.join ' ' - values = if @multithread then - threadsafe_cache_get_multi server, keys_for_server - else - cache_get_multi server, keys_for_server - end + values = cache_get_multi server, keys_for_server values.each do |key, value| results[cache_keys[key]] = Marshal.load value end end return results - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err + rescue TypeError, IndexError => err + handle_error nil, err end ## - # Increments the value for +key+ by +amount+ and retruns the new value. + # Increments the value for +key+ by +amount+ and returns the new value. # +key+ must already exist. If +key+ is not an integer, it is assumed to be # 0. def incr(key, amount = 1) - server, cache_key = request_setup key - - if @multithread then - threadsafe_cache_incr server, cache_key, amount - else + raise MemCacheError, "Update of readonly cache" if @readonly + with_server(key) do |server, cache_key| cache_incr server, cache_key, amount end - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err + rescue TypeError => err + handle_error nil, err end ## @@ -321,23 +287,23 @@ class MemCache def set(key, value, expiry = 0, raw = false) raise MemCacheError, "Update of readonly cache" if @readonly - server, cache_key = request_setup key - socket = server.socket + with_server(key) do |server, cache_key| - value = Marshal.dump value unless raw - command = "set #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" + value = Marshal.dump value unless raw + command = "set #{cache_key} 0 #{expiry} #{value.to_s.size}\r\n#{value}\r\n" - begin - @mutex.lock if @multithread - socket.write command - result = socket.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - ensure - @mutex.unlock if @multithread + with_socket_management(server) do |socket| + socket.write command + result = socket.gets + raise_on_error_response! result + + if result.nil? + server.close + raise MemCacheError, "lost connection to #{server.host}:#{server.port}" + end + + result + end end end @@ -351,23 +317,16 @@ class MemCache def add(key, value, expiry = 0, raw = false) raise MemCacheError, "Update of readonly cache" if @readonly - server, cache_key = request_setup key - socket = server.socket - - value = Marshal.dump value unless raw - command = "add #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" - - begin - @mutex.lock if @multithread - socket.write command - result = socket.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - ensure - @mutex.unlock if @multithread + with_server(key) do |server, cache_key| + value = Marshal.dump value unless raw + command = "add #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" + + with_socket_management(server) do |socket| + socket.write command + result = socket.gets + raise_on_error_response! result + result + end end end @@ -375,26 +334,15 @@ class MemCache # Removes +key+ from the cache in +expiry+ seconds. def delete(key, expiry = 0) - @mutex.lock if @multithread - - raise MemCacheError, "No active servers" unless active? - cache_key = make_cache_key key - server = get_server_for_key cache_key - - sock = server.socket - raise MemCacheError, "No connection to server" if sock.nil? - - begin - sock.write "delete #{cache_key} #{expiry}\r\n" - result = sock.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message + raise MemCacheError, "Update of readonly cache" if @readonly + with_server(key) do |server, cache_key| + with_socket_management(server) do |socket| + socket.write "delete #{cache_key} #{expiry}\r\n" + result = socket.gets + raise_on_error_response! result + result + end end - ensure - @mutex.unlock if @multithread end ## @@ -403,21 +351,19 @@ class MemCache def flush_all raise MemCacheError, 'No active servers' unless active? raise MemCacheError, "Update of readonly cache" if @readonly + begin @mutex.lock if @multithread @servers.each do |server| - begin - sock = server.socket - raise MemCacheError, "No connection to server" if sock.nil? - sock.write "flush_all\r\n" - result = sock.gets + with_socket_management(server) do |socket| + socket.write "flush_all\r\n" + result = socket.gets raise_on_error_response! result result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message end end + rescue IndexError => err + handle_error nil, err ensure @mutex.unlock if @multithread end @@ -469,14 +415,13 @@ class MemCache server_stats = {} @servers.each do |server| - sock = server.socket - raise MemCacheError, "No connection to server" if sock.nil? + next unless server.alive? - value = nil - begin - sock.write "stats\r\n" + with_socket_management(server) do |socket| + value = nil + socket.write "stats\r\n" stats = {} - while line = sock.gets do + while line = socket.gets do raise_on_error_response! line break if line == "END\r\n" if line =~ /\ASTAT ([\w]+) ([\w\.\:]+)/ then @@ -498,12 +443,10 @@ class MemCache end end server_stats["#{server.host}:#{server.port}"] = stats - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message end end + raise MemCacheError, "No active servers" if server_stats.empty? server_stats end @@ -520,7 +463,7 @@ class MemCache set key, value end - protected + protected unless $TESTING ## # Create a key for the cache, incorporating the namespace qualifier if @@ -537,7 +480,7 @@ class MemCache ## # Pick a server to handle the request based on a hash of the key. - def get_server_for_key(key) + def get_server_for_key(key, options = {}) raise ArgumentError, "illegal character in key #{key.inspect}" if key =~ /\s/ raise ArgumentError, "key too long #{key.inspect}" if key.length > 250 @@ -545,13 +488,17 @@ class MemCache return @servers.first if @servers.length == 1 hkey = hash_for key - - 20.times do |try| - server = @buckets[hkey % @buckets.nitems] - return server if server.alive? - hkey += hash_for "#{try}#{key}" + + if @failover + 20.times do |try| + server = @buckets[hkey % @buckets.compact.size] + return server if server.alive? + hkey += hash_for "#{try}#{key}" + end + else + return @buckets[hkey % @buckets.compact.size] end - + raise MemCacheError, "No servers available" end @@ -560,7 +507,7 @@ class MemCache # sketchy for down servers). def hash_for(key) - (key.crc32_ITU_T >> 16) & 0x7fff + (Zlib.crc32(key) >> 16) & 0x7fff end ## @@ -568,12 +515,13 @@ class MemCache # found. def cache_decr(server, cache_key, amount) - socket = server.socket - socket.write "decr #{cache_key} #{amount}\r\n" - text = socket.gets - raise_on_error_response! text - return nil if text == "NOT_FOUND\r\n" - return text.to_i + with_socket_management(server) do |socket| + socket.write "decr #{cache_key} #{amount}\r\n" + text = socket.gets + raise_on_error_response! text + return nil if text == "NOT_FOUND\r\n" + return text.to_i + end end ## @@ -581,52 +529,54 @@ class MemCache # miss. def cache_get(server, cache_key) - socket = server.socket - socket.write "get #{cache_key}\r\n" - keyline = socket.gets # "VALUE <key> <flags> <bytes>\r\n" + with_socket_management(server) do |socket| + socket.write "get #{cache_key}\r\n" + keyline = socket.gets # "VALUE <key> <flags> <bytes>\r\n" - if keyline.nil? then - server.close - raise MemCacheError, "lost connection to #{server.host}:#{server.port}" - end + if keyline.nil? then + server.close + raise MemCacheError, "lost connection to #{server.host}:#{server.port}" + end - raise_on_error_response! keyline - return nil if keyline == "END\r\n" + raise_on_error_response! keyline + return nil if keyline == "END\r\n" - unless keyline =~ /(\d+)\r/ then - server.close - raise MemCacheError, "unexpected response #{keyline.inspect}" + unless keyline =~ /(\d+)\r/ then + server.close + raise MemCacheError, "unexpected response #{keyline.inspect}" + end + value = socket.read $1.to_i + socket.read 2 # "\r\n" + socket.gets # "END\r\n" + return value end - value = socket.read $1.to_i - socket.read 2 # "\r\n" - socket.gets # "END\r\n" - return value end ## # Fetches +cache_keys+ from +server+ using a multi-get. def cache_get_multi(server, cache_keys) - values = {} - socket = server.socket - socket.write "get #{cache_keys}\r\n" + with_socket_management(server) do |socket| + values = {} + socket.write "get #{cache_keys}\r\n" - while keyline = socket.gets do - return values if keyline == "END\r\n" - raise_on_error_response! keyline + while keyline = socket.gets do + return values if keyline == "END\r\n" + raise_on_error_response! keyline - unless keyline =~ /\AVALUE (.+) (.+) (.+)/ then - server.close - raise MemCacheError, "unexpected response #{keyline.inspect}" + unless keyline =~ /\AVALUE (.+) (.+) (.+)/ then + server.close + raise MemCacheError, "unexpected response #{keyline.inspect}" + end + + key, data_length = $1, $3 + values[$1] = socket.read data_length.to_i + socket.read(2) # "\r\n" end - key, data_length = $1, $3 - values[$1] = socket.read data_length.to_i - socket.read(2) # "\r\n" + server.close + raise MemCacheError, "lost connection to #{server.host}:#{server.port}" # TODO: retry here too end - - server.close - raise MemCacheError, "lost connection to #{server.host}:#{server.port}" end ## @@ -634,18 +584,76 @@ class MemCache # found. def cache_incr(server, cache_key, amount) - socket = server.socket - socket.write "incr #{cache_key} #{amount}\r\n" - text = socket.gets - raise_on_error_response! text - return nil if text == "NOT_FOUND\r\n" - return text.to_i + with_socket_management(server) do |socket| + socket.write "incr #{cache_key} #{amount}\r\n" + text = socket.gets + raise_on_error_response! text + return nil if text == "NOT_FOUND\r\n" + return text.to_i + end + end + + ## + # Gets or creates a socket connected to the given server, and yields it + # to the block, wrapped in a mutex synchronization if @multithread is true. + # + # If a socket error (SocketError, SystemCallError, IOError) or protocol error + # (MemCacheError) is raised by the block, closes the socket, attempts to + # connect again, and retries the block (once). If an error is again raised, + # reraises it as MemCacheError. + # + # If unable to connect to the server (or if in the reconnect wait period), + # raises MemCacheError. Note that the socket connect code marks a server + # dead for a timeout period, so retrying does not apply to connection attempt + # failures (but does still apply to unexpectedly lost connections etc.). + + def with_socket_management(server, &block) + @mutex.lock if @multithread + retried = false + + begin + socket = server.socket + + # Raise an IndexError to show this server is out of whack. If were inside + # a with_server block, we'll catch it and attempt to restart the operation. + + raise IndexError, "No connection to server (#{server.status})" if socket.nil? + + block.call(socket) + + rescue SocketError => err + server.mark_dead(err.message) + handle_error(server, err) + + rescue MemCacheError, SocketError, SystemCallError, IOError => err + handle_error(server, err) if retried || socket.nil? + retried = true + retry + end + ensure + @mutex.unlock if @multithread + end + + def with_server(key) + retried = false + begin + server, cache_key = request_setup(key) + yield server, cache_key + rescue IndexError => e + if !retried && @servers.size > 1 + puts "Connection to server #{server.inspect} DIED! Retrying operation..." + retried = true + retry + end + handle_error(nil, e) + end end ## # Handles +error+ from +server+. def handle_error(server, error) + raise error if error.is_a?(MemCacheError) server.close if server new_error = MemCacheError.new error.message new_error.set_backtrace error.backtrace @@ -660,45 +668,15 @@ class MemCache raise MemCacheError, 'No active servers' unless active? cache_key = make_cache_key key server = get_server_for_key cache_key - raise MemCacheError, 'No connection to server' if server.socket.nil? return server, cache_key end - def threadsafe_cache_decr(server, cache_key, amount) # :nodoc: - @mutex.lock - cache_decr server, cache_key, amount - ensure - @mutex.unlock - end - - def threadsafe_cache_get(server, cache_key) # :nodoc: - @mutex.lock - cache_get server, cache_key - ensure - @mutex.unlock - end - - def threadsafe_cache_get_multi(socket, cache_keys) # :nodoc: - @mutex.lock - cache_get_multi socket, cache_keys - ensure - @mutex.unlock - end - - def threadsafe_cache_incr(server, cache_key, amount) # :nodoc: - @mutex.lock - cache_incr server, cache_key, amount - ensure - @mutex.unlock - end - def raise_on_error_response!(response) - if response =~ /\A(?:CLIENT_|SERVER_)?ERROR (.*)/ + if response =~ /\A(?:CLIENT_|SERVER_)?ERROR(.*)/ raise MemCacheError, $1.strip end end - ## # This class represents a memcached server instance. @@ -712,6 +690,13 @@ class MemCache CONNECT_TIMEOUT = 0.25 ## + # The amount of time to wait for a response from a memcached server. + # If a response isn't received within this time limit, + # the server will be marked as down. + + SOCKET_TIMEOUT = 0.5 + + ## # The amount of time to wait before attempting to re-establish a # connection with a server that is marked dead. @@ -795,9 +780,9 @@ class MemCache # Attempt to connect if not already connected. begin - @sock = timeout CONNECT_TIMEOUT do - TCPSocket.new @host, @port - end + + @sock = TCPTimeoutSocket.new @host, @port + if Socket.constants.include? 'TCP_NODELAY' then @sock.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1 end @@ -826,8 +811,6 @@ class MemCache @mutex.unlock if @multithread end - private - ## # Mark the server as dead and close its socket. @@ -836,8 +819,9 @@ class MemCache @sock = nil @retry = Time.now + RETRY_DELAY - @status = sprintf "DEAD: %s, will retry at %s", reason, @retry + @status = sprintf "%s:%s DEAD: %s, will retry at %s", @host, @port, reason, @retry end + end ## @@ -847,3 +831,38 @@ class MemCache end +# TCPSocket facade class which implements timeouts. +class TCPTimeoutSocket + def initialize(*args) + Timeout::timeout(MemCache::Server::CONNECT_TIMEOUT, SocketError) do + @sock = TCPSocket.new(*args) + @len = MemCache::Server::SOCKET_TIMEOUT.to_f || 0.5 + end + end + + def write(*args) + Timeout::timeout(@len, SocketError) do + @sock.write(*args) + end + end + + def gets(*args) + Timeout::timeout(@len, SocketError) do + @sock.gets(*args) + end + end + + def read(*args) + Timeout::timeout(@len, SocketError) do + @sock.read(*args) + end + end + + def _socket + @sock + end + + def method_missing(meth, *args) + @sock.__send__(meth, *args) + end +end
\ No newline at end of file diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb index 28dd34334f..e178ced06d 100644 --- a/activesupport/test/buffered_logger_test.rb +++ b/activesupport/test/buffered_logger_test.rb @@ -137,4 +137,10 @@ class BufferedLoggerTest < Test::Unit::TestCase assert @output.string.include?("a\nb\nc\n") assert @output.string.include?("x\ny\nz\n") end + + def test_flush_should_remove_empty_buffers + @logger.send :buffer + @logger.expects :clear_buffer + @logger.flush + end end diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 25b8eecef5..2bc2e1eaf0 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -53,10 +53,41 @@ class Person < Record end class ConditionalPerson < Record + # proc before_save Proc.new { |r| r.history << [:before_save, :proc] }, :if => Proc.new { |r| true } before_save Proc.new { |r| r.history << "b00m" }, :if => Proc.new { |r| false } before_save Proc.new { |r| r.history << [:before_save, :proc] }, :unless => Proc.new { |r| false } before_save Proc.new { |r| r.history << "b00m" }, :unless => Proc.new { |r| true } + # symbol + before_save Proc.new { |r| r.history << [:before_save, :symbol] }, :if => :yes + before_save Proc.new { |r| r.history << "b00m" }, :if => :no + before_save Proc.new { |r| r.history << [:before_save, :symbol] }, :unless => :no + before_save Proc.new { |r| r.history << "b00m" }, :unless => :yes + # string + before_save Proc.new { |r| r.history << [:before_save, :string] }, :if => 'yes' + before_save Proc.new { |r| r.history << "b00m" }, :if => 'no' + before_save Proc.new { |r| r.history << [:before_save, :string] }, :unless => 'no' + before_save Proc.new { |r| r.history << "b00m" }, :unless => 'yes' + # Array with conditions + before_save Proc.new { |r| r.history << [:before_save, :symbol_array] }, :if => [:yes, :other_yes] + before_save Proc.new { |r| r.history << "b00m" }, :if => [:yes, :no] + before_save Proc.new { |r| r.history << [:before_save, :symbol_array] }, :unless => [:no, :other_no] + before_save Proc.new { |r| r.history << "b00m" }, :unless => [:yes, :no] + # Combined if and unless + before_save Proc.new { |r| r.history << [:before_save, :combined_symbol] }, :if => :yes, :unless => :no + before_save Proc.new { |r| r.history << "b00m" }, :if => :yes, :unless => :yes + # Array with different types of conditions + before_save Proc.new { |r| r.history << [:before_save, :symbol_proc_string_array] }, :if => [:yes, Proc.new { |r| true }, 'yes'] + before_save Proc.new { |r| r.history << "b00m" }, :if => [:yes, Proc.new { |r| true }, 'no'] + # Array with different types of conditions comibned if and unless + before_save Proc.new { |r| r.history << [:before_save, :combined_symbol_proc_string_array] }, + :if => [:yes, Proc.new { |r| true }, 'yes'], :unless => [:no, 'no'] + before_save Proc.new { |r| r.history << "b00m" }, :if => [:yes, Proc.new { |r| true }, 'no'], :unless => [:no, 'no'] + + def yes; true; end + def other_yes; true; end + def no; false; end + def other_no; false; end def save run_callbacks(:before_save) @@ -90,7 +121,16 @@ class ConditionalCallbackTest < Test::Unit::TestCase person.save assert_equal [ [:before_save, :proc], - [:before_save, :proc] + [:before_save, :proc], + [:before_save, :symbol], + [:before_save, :symbol], + [:before_save, :string], + [:before_save, :string], + [:before_save, :symbol_array], + [:before_save, :symbol_array], + [:before_save, :combined_symbol], + [:before_save, :symbol_proc_string_array], + [:before_save, :combined_symbol_proc_string_array] ], person.history end end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 30cbba26b0..b63ab30965 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -287,10 +287,14 @@ class HashExtTest < Test::Unit::TestCase # Should return a new hash with only the given keys. assert_equal expected, original.slice(:a, :b) assert_not_equal expected, original + end + + def test_slice_inplace + original = { :a => 'x', :b => 'y', :c => 10 } + expected = { :c => 10 } # Should replace the hash with only the given keys. assert_equal expected, original.slice!(:a, :b) - assert_equal expected, original end def test_slice_with_an_array_key @@ -300,10 +304,14 @@ class HashExtTest < Test::Unit::TestCase # Should return a new hash with only the given keys when given an array key. assert_equal expected, original.slice([:a, :b], :c) assert_not_equal expected, original + end + + def test_slice_inplace_with_an_array_key + original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" } + expected = { :a => 'x', :b => 'y' } # Should replace the hash with only the given keys when given an array key. assert_equal expected, original.slice!([:a, :b], :c) - assert_equal expected, original end def test_slice_with_splatted_keys @@ -322,11 +330,17 @@ class HashExtTest < Test::Unit::TestCase # Should return a new hash with only the given keys. assert_equal expected, original.slice(*keys), keys.inspect assert_not_equal expected, original + end + end + + def test_indifferent_slice_inplace + original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access + expected = { :c => 10 }.with_indifferent_access + [['a', 'b'], [:a, :b]].each do |keys| # Should replace the hash with only the given keys. copy = original.dup assert_equal expected, copy.slice!(*keys) - assert_equal expected, copy end end @@ -403,6 +417,13 @@ class HashToXmlTest < Test::Unit::TestCase assert xml.include?(%(<name>David</name>)) end + def test_one_level_camelize_true + xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:camelize => true)) + assert_equal "<Person>", xml.first(8) + assert xml.include?(%(<StreetName>Paulina</StreetName>)) + assert xml.include?(%(<Name>David</Name>)) + end + def test_one_level_with_types xml = { :name => "David", :street => "Paulina", :age => 26, :age_in_millis => 820497600000, :moved_on => Date.new(2005, 11, 15), :resident => :yes }.to_xml(@xml_options) assert_equal "<person>", xml.first(8) diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 886f692499..a5d98507ba 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -41,6 +41,10 @@ Invoice = Struct.new(:client) do delegate :street, :city, :name, :to => :client, :prefix => :customer end +Project = Struct.new(:description, :person) do + delegate :name, :to => :person, :allow_nil => true +end + class Name delegate :upcase, :to => :@full_name @@ -117,6 +121,29 @@ class ModuleTest < Test::Unit::TestCase end end + def test_delegation_with_allow_nil + rails = Project.new("Rails", Someone.new("David")) + assert_equal rails.name, "David" + end + + def test_delegation_with_allow_nil_and_nil_value + rails = Project.new("Rails") + assert_nil rails.name + end + + def test_delegation_with_allow_nil_and_nil_value_and_prefix + Project.class_eval do + delegate :name, :to => :person, :allow_nil => true, :prefix => true + end + rails = Project.new("Rails") + assert_nil rails.person_name + end + + def test_delegation_without_allow_nil_and_nil_value + david = Someone.new("David") + assert_raises(NoMethodError) { david.street } + end + def test_parent assert_equal Yz::Zy, Yz::Zy::Cd.parent assert_equal Yz, Yz::Zy.parent diff --git a/activesupport/test/core_ext/object_ext_test.rb b/activesupport/test/core_ext/object_ext_test.rb new file mode 100644 index 0000000000..a413d331c4 --- /dev/null +++ b/activesupport/test/core_ext/object_ext_test.rb @@ -0,0 +1,8 @@ +require 'abstract_unit' + +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 diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index dc36336239..7c8fb7dd94 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -256,6 +256,15 @@ class TimeWithZoneTest < Test::Unit::TestCase twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) assert_equal 86_400.0, twz2 - twz1 end + + def test_minus_with_datetime + assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1) + end + + def test_minus_with_wrapped_datetime + assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 1) + assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1) + end def test_plus_and_minus_enforce_spring_dst_rules silence_warnings do # silence warnings raised by tzinfo gem diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 19ae3a01a8..558b03b90d 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -15,7 +15,8 @@ class TestJSONDecoding < Test::Unit::TestCase # no time zone %({a: "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"}, # needs to be *exact* - %({a: " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "}, + %({a: " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "}, + %({a: "2007-01-01 : it's your birthday"}) => {'a' => "2007-01-01 : it's your birthday"}, %([]) => [], %({}) => {}, %(1) => 1, diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 17dffbd624..0e2aa4543d 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -36,9 +36,11 @@ class OrderedHashTest < Test::Unit::TestCase @ordered_hash[key] = value assert_equal @keys.length + 1, @ordered_hash.length + assert_equal @ordered_hash.keys.length, @ordered_hash.length assert_equal value, @ordered_hash.delete(key) assert_equal @keys.length, @ordered_hash.length + assert_equal @ordered_hash.keys.length, @ordered_hash.length assert_nil @ordered_hash.delete(bad_key) end @@ -73,4 +75,69 @@ class OrderedHashTest < Test::Unit::TestCase @ordered_hash.each_value { |v| values << v } assert_equal @values, values end -end + + def test_each + values = [] + @ordered_hash.each {|key, value| values << value} + assert_equal @values, values + end + + def test_each_with_index + @ordered_hash.each_with_index { |pair, index| assert_equal [@keys[index], @values[index]], pair} + end + + def test_each_pair + values = [] + keys = [] + @ordered_hash.each_pair do |key, value| + keys << key + values << value + end + assert_equal @values, values + assert_equal @keys, keys + end + + def test_delete_if + (copy = @ordered_hash.dup).delete('pink') + assert_equal copy, @ordered_hash.delete_if { |k, _| k == 'pink' } + assert !@ordered_hash.keys.include?('pink') + end + + def test_reject! + (copy = @ordered_hash.dup).delete('pink') + @ordered_hash.reject! { |k, _| k == 'pink' } + assert_equal copy, @ordered_hash + assert !@ordered_hash.keys.include?('pink') + end + + def test_reject + copy = @ordered_hash.dup + new_ordered_hash = @ordered_hash.reject { |k, _| k == 'pink' } + assert_equal copy, @ordered_hash + assert !new_ordered_hash.keys.include?('pink') + end + + def test_clear + @ordered_hash.clear + assert_equal [], @ordered_hash.keys + end + + def test_merge + other_hash = ActiveSupport::OrderedHash.new + other_hash['purple'] = '800080' + other_hash['violet'] = 'ee82ee' + merged = @ordered_hash.merge other_hash + assert_equal merged.length, @ordered_hash.length + other_hash.length + assert_equal @keys + ['purple', 'violet'], merged.keys + + @ordered_hash.merge! other_hash + assert_equal @ordered_hash, merged + assert_equal @ordered_hash.keys, merged.keys + end + + def test_shift + pair = @ordered_hash.shift + assert_equal [@keys.first, @values.first], pair + assert !@ordered_hash.keys.include?(pair.first) + end +end
\ No newline at end of file |