aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport')
-rw-r--r--activesupport/CHANGELOG.md909
-rw-r--r--activesupport/MIT-LICENSE2
-rw-r--r--activesupport/README.rdoc4
-rw-r--r--activesupport/Rakefile15
-rw-r--r--activesupport/activesupport.gemspec39
-rwxr-xr-xactivesupport/bin/generate_tables40
-rwxr-xr-xactivesupport/bin/test7
-rw-r--r--activesupport/lib/active_support.rb16
-rw-r--r--activesupport/lib/active_support/all.rb8
-rw-r--r--activesupport/lib/active_support/array_inquirer.rb14
-rw-r--r--activesupport/lib/active_support/backtrace_cleaner.rb10
-rw-r--r--activesupport/lib/active_support/benchmarkable.rb8
-rw-r--r--activesupport/lib/active_support/builder.rb4
-rw-r--r--activesupport/lib/active_support/cache.rb247
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb40
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb89
-rw-r--r--activesupport/lib/active_support/cache/memory_store.rb28
-rw-r--r--activesupport/lib/active_support/cache/null_store.rb10
-rw-r--r--activesupport/lib/active_support/cache/redis_cache_store.rb406
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb46
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb19
-rw-r--r--activesupport/lib/active_support/callbacks.rb1222
-rw-r--r--activesupport/lib/active_support/concern.rb4
-rw-r--r--activesupport/lib/active_support/concurrency/latch.rb19
-rw-r--r--activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb17
-rw-r--r--activesupport/lib/active_support/concurrency/share_lock.rb79
-rw-r--r--activesupport/lib/active_support/configurable.rb12
-rw-r--r--activesupport/lib/active_support/core_ext.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/array.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/array/access.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb32
-rw-r--r--activesupport/lib/active_support/core_ext/array/extract_options.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/array/grouping.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/array/inquiry.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/array/prepend_and_append.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/array/wrap.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/benchmark.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal/conversions.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/class.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute.rb58
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute_accessors.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/class/subclasses.rb23
-rw-r--r--activesupport/lib/active_support/core_ext/date.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/date/acts_like.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/date/blank.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb18
-rw-r--r--activesupport/lib/active_support/core_ext/date/conversions.rb41
-rw-r--r--activesupport/lib/active_support/core_ext/date/zones.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/calculations.rb117
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/zones.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/date_time.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/acts_like.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/blank.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb32
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/compatibility.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/conversions.rb26
-rw-r--r--activesupport/lib/active_support/core_ext/digest/uuid.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb105
-rw-r--r--activesupport/lib/active_support/core_ext/file.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/file/atomic.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/hash.rb20
-rw-r--r--activesupport/lib/active_support/core_ext/hash/compact.rb39
-rw-r--r--activesupport/lib/active_support/core_ext/hash/conversions.rb78
-rw-r--r--activesupport/lib/active_support/core_ext/hash/deep_merge.rb20
-rw-r--r--activesupport/lib/active_support/core_ext/hash/except.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/hash/indifferent_access.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/hash/keys.rb18
-rw-r--r--activesupport/lib/active_support/core_ext/hash/reverse_merge.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/hash/slice.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/hash/transform_values.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/integer.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/integer/inflections.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/integer/multiple.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/integer/time.rb29
-rw-r--r--activesupport/lib/active_support/core_ext/kernel.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/agnostics.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/concern.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/debugger.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/reporting.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/singleton_class.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/load_error.rb25
-rw-r--r--activesupport/lib/active_support/core_ext/marshal.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/module.rb26
-rw-r--r--activesupport/lib/active_support/core_ext/module/aliasing.rb53
-rw-r--r--activesupport/lib/active_support/core_ext/module/anonymous.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/attr_internal.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/module/attribute_accessors.rb61
-rw-r--r--activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb39
-rw-r--r--activesupport/lib/active_support/core_ext/module/concerning.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb118
-rw-r--r--activesupport/lib/active_support/core_ext/module/deprecation.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/introspection.rb22
-rw-r--r--activesupport/lib/active_support/core_ext/module/method_transplanting.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/module/qualified_const.rb70
-rw-r--r--activesupport/lib/active_support/core_ext/module/reachable.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/module/redefine_method.rb49
-rw-r--r--activesupport/lib/active_support/core_ext/module/remove_method.rb28
-rw-r--r--activesupport/lib/active_support/core_ext/name_error.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/numeric.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/bytes.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/conversions.rb55
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/inquiry.rb44
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/time.rb44
-rw-r--r--activesupport/lib/active_support/core_ext/object.rb26
-rw-r--r--activesupport/lib/active_support/core_ext/object/acts_like.rb13
-rw-r--r--activesupport/lib/active_support/core_ext/object/blank.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/object/conversions.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/object/deep_dup.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/duplicable.rb130
-rw-r--r--activesupport/lib/active_support/core_ext/object/inclusion.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/instance_variables.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/json.rb46
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_param.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_query.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/object/with_options.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/range.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/range/conversions.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/range/each.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/range/include_range.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/range/include_time_with_zone.rb23
-rw-r--r--activesupport/lib/active_support/core_ext/range/overlaps.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/regexp.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/securerandom.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/string.rb28
-rw-r--r--activesupport/lib/active_support/core_ext/string/access.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/string/behavior.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/conversions.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/string/exclude.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/string/indent.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb62
-rw-r--r--activesupport/lib/active_support/core_ext/string/inquiry.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/string/multibyte.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb52
-rw-r--r--activesupport/lib/active_support/core_ext/string/starts_ends_with.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/strip.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/string/zones.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/struct.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/time.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/time/acts_like.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb111
-rw-r--r--activesupport/lib/active_support/core_ext/time/compatibility.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb29
-rw-r--r--activesupport/lib/active_support/core_ext/time/marshal.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/time/zones.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/uri.rb9
-rw-r--r--activesupport/lib/active_support/current_attributes.rb195
-rw-r--r--activesupport/lib/active_support/dependencies.rb128
-rw-r--r--activesupport/lib/active_support/dependencies/autoload.rb2
-rw-r--r--activesupport/lib/active_support/dependencies/interlock.rb8
-rw-r--r--activesupport/lib/active_support/deprecation.rb21
-rw-r--r--activesupport/lib/active_support/deprecation/behaviors.rb35
-rw-r--r--activesupport/lib/active_support/deprecation/constant_accessor.rb52
-rw-r--r--activesupport/lib/active_support/deprecation/instance_delegator.rb19
-rw-r--r--activesupport/lib/active_support/deprecation/method_wrappers.rb29
-rw-r--r--activesupport/lib/active_support/deprecation/proxy_wrappers.rb15
-rw-r--r--activesupport/lib/active_support/deprecation/reporting.rb20
-rw-r--r--activesupport/lib/active_support/descendants_tracker.rb2
-rw-r--r--activesupport/lib/active_support/digest.rb20
-rw-r--r--activesupport/lib/active_support/duration.rb335
-rw-r--r--activesupport/lib/active_support/duration/iso8601_parser.rb135
-rw-r--r--activesupport/lib/active_support/duration/iso8601_serializer.rb22
-rw-r--r--activesupport/lib/active_support/encrypted_configuration.rb49
-rw-r--r--activesupport/lib/active_support/encrypted_file.rb99
-rw-r--r--activesupport/lib/active_support/evented_file_update_checker.rb168
-rw-r--r--activesupport/lib/active_support/execution_wrapper.rb37
-rw-r--r--activesupport/lib/active_support/executor.rb4
-rw-r--r--activesupport/lib/active_support/file_update_checker.rb106
-rw-r--r--activesupport/lib/active_support/gem_version.rb6
-rw-r--r--activesupport/lib/active_support/gzip.rb12
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb117
-rw-r--r--activesupport/lib/active_support/i18n.rb14
-rw-r--r--activesupport/lib/active_support/i18n_railtie.rb31
-rw-r--r--activesupport/lib/active_support/inflections.rb24
-rw-r--r--activesupport/lib/active_support/inflector.rb12
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb42
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb158
-rw-r--r--activesupport/lib/active_support/inflector/transliterate.rb42
-rw-r--r--activesupport/lib/active_support/json.rb6
-rw-r--r--activesupport/lib/active_support/json/decoding.rb19
-rw-r--r--activesupport/lib/active_support/json/encoding.rb19
-rw-r--r--activesupport/lib/active_support/key_generator.rb44
-rw-r--r--activesupport/lib/active_support/lazy_load_hooks.rb70
-rw-r--r--activesupport/lib/active_support/log_subscriber.rb21
-rw-r--r--activesupport/lib/active_support/log_subscriber/test_helper.rb20
-rw-r--r--activesupport/lib/active_support/logger.rb26
-rw-r--r--activesupport/lib/active_support/logger_silence.rb11
-rw-r--r--activesupport/lib/active_support/logger_thread_safe_level.rb4
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb219
-rw-r--r--activesupport/lib/active_support/message_verifier.rb99
-rw-r--r--activesupport/lib/active_support/messages/metadata.rb71
-rw-r--r--activesupport/lib/active_support/messages/rotation_configuration.rb22
-rw-r--r--activesupport/lib/active_support/messages/rotator.rb56
-rw-r--r--activesupport/lib/active_support/multibyte.rb6
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb46
-rw-r--r--activesupport/lib/active_support/multibyte/unicode.rb159
-rw-r--r--activesupport/lib/active_support/notifications.rb14
-rw-r--r--activesupport/lib/active_support/notifications/fanout.rb8
-rw-r--r--activesupport/lib/active_support/notifications/instrumenter.rb12
-rw-r--r--activesupport/lib/active_support/number_helper.rb11
-rw-r--r--activesupport/lib/active_support/number_helper/number_converter.rb24
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_currency_converter.rb8
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb5
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_human_converter.rb20
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb19
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb4
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_phone_converter.rb6
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb64
-rw-r--r--activesupport/lib/active_support/number_helper/rounding_helper.rb66
-rw-r--r--activesupport/lib/active_support/option_merger.rb4
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb8
-rw-r--r--activesupport/lib/active_support/ordered_options.rb16
-rw-r--r--activesupport/lib/active_support/per_thread_registry.rb12
-rw-r--r--activesupport/lib/active_support/proxy_object.rb2
-rw-r--r--activesupport/lib/active_support/rails.rb20
-rw-r--r--activesupport/lib/active_support/railtie.rb48
-rw-r--r--activesupport/lib/active_support/reloader.rb14
-rw-r--r--activesupport/lib/active_support/rescuable.rb163
-rw-r--r--activesupport/lib/active_support/security_utils.rb26
-rw-r--r--activesupport/lib/active_support/string_inquirer.rb12
-rw-r--r--activesupport/lib/active_support/subscriber.rb16
-rw-r--r--activesupport/lib/active_support/tagged_logging.rb21
-rw-r--r--activesupport/lib/active_support/test_case.rb42
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb103
-rw-r--r--activesupport/lib/active_support/testing/autorun.rb15
-rw-r--r--activesupport/lib/active_support/testing/constant_lookup.rb3
-rw-r--r--activesupport/lib/active_support/testing/declarative.rb4
-rw-r--r--activesupport/lib/active_support/testing/deprecation.rb7
-rw-r--r--activesupport/lib/active_support/testing/file_fixtures.rb2
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb39
-rw-r--r--activesupport/lib/active_support/testing/method_call_assertions.rb4
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb6
-rw-r--r--activesupport/lib/active_support/testing/stream.rb58
-rw-r--r--activesupport/lib/active_support/testing/tagged_logging.rb4
-rw-r--r--activesupport/lib/active_support/testing/time_helpers.rb104
-rw-r--r--activesupport/lib/active_support/time.rb26
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb83
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb170
-rw-r--r--activesupport/lib/active_support/values/unicode_tables.datbin1068675 -> 1116857 bytes
-rw-r--r--activesupport/lib/active_support/version.rb4
-rw-r--r--activesupport/lib/active_support/xml_mini.rb115
-rw-r--r--activesupport/lib/active_support/xml_mini/jdom.rb228
-rw-r--r--activesupport/lib/active_support/xml_mini/libxml.rb29
-rw-r--r--activesupport/lib/active_support/xml_mini/libxmlsax.rb34
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogiri.rb26
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogirisax.rb31
-rw-r--r--activesupport/lib/active_support/xml_mini/rexml.rb24
-rw-r--r--activesupport/test/abstract_unit.rb43
-rw-r--r--activesupport/test/array_inquirer_test.rb32
-rw-r--r--activesupport/test/autoload_test.rb18
-rw-r--r--activesupport/test/autoloading_fixtures/a/b.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/a/c/d.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/a/c/em/f.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/application.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/circular1.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/circular2.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/class_folder.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/class_folder/inline_class.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/class_folder/nested_class.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/conflict.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/counting_loader.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/cross_site_dependency.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/d.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/em.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/html/some_class.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb3
-rw-r--r--activesupport/test/autoloading_fixtures/loads_constant.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/module_folder/inline_class.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/module_folder/nested_class.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/multiple_constant_file.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/prepend.rb10
-rw-r--r--activesupport/test/autoloading_fixtures/prepend/sub_class_conflict.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/raises_arbitrary_exception.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/raises_name_error.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/raises_no_method_error.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/requires_constant.rb3
-rw-r--r--activesupport/test/autoloading_fixtures/should_not_be_required.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/throws.rb2
-rw-r--r--activesupport/test/autoloading_fixtures/typo.rb3
-rw-r--r--activesupport/test/benchmarkable_test.rb24
-rw-r--r--activesupport/test/broadcast_logger_test.rb162
-rw-r--r--activesupport/test/cache/behaviors.rb9
-rw-r--r--activesupport/test/cache/behaviors/autoloading_cache_behavior.rb43
-rw-r--r--activesupport/test/cache/behaviors/cache_delete_matched_behavior.rb15
-rw-r--r--activesupport/test/cache/behaviors/cache_increment_decrement_behavior.rb27
-rw-r--r--activesupport/test/cache/behaviors/cache_store_behavior.rb353
-rw-r--r--activesupport/test/cache/behaviors/cache_store_version_behavior.rb88
-rw-r--r--activesupport/test/cache/behaviors/encoded_key_cache_behavior.rb36
-rw-r--r--activesupport/test/cache/behaviors/local_cache_behavior.rb132
-rw-r--r--activesupport/test/cache/cache_entry_test.rb37
-rw-r--r--activesupport/test/cache/cache_key_test.rb90
-rw-r--r--activesupport/test/cache/cache_store_logger_test.rb36
-rw-r--r--activesupport/test/cache/cache_store_namespace_test.rb40
-rw-r--r--activesupport/test/cache/cache_store_setting_test.rb68
-rw-r--r--activesupport/test/cache/cache_store_write_multi_test.rb62
-rw-r--r--activesupport/test/cache/local_cache_middleware_test.rb63
-rw-r--r--activesupport/test/cache/stores/file_store_test.rb131
-rw-r--r--activesupport/test/cache/stores/mem_cache_store_test.rb92
-rw-r--r--activesupport/test/cache/stores/memory_store_test.rb109
-rw-r--r--activesupport/test/cache/stores/null_store_test.rb59
-rw-r--r--activesupport/test/cache/stores/redis_cache_store_test.rb151
-rw-r--r--activesupport/test/caching_test.rb1194
-rw-r--r--activesupport/test/callback_inheritance_test.rb14
-rw-r--r--activesupport/test/callbacks_test.rb331
-rw-r--r--activesupport/test/class_cache_test.rb8
-rw-r--r--activesupport/test/clean_backtrace_test.rb19
-rw-r--r--activesupport/test/clean_logger_test.rb12
-rw-r--r--activesupport/test/concern_test.rb14
-rw-r--r--activesupport/test/concurrency/load_interlock_aware_monitor_test.rb55
-rw-r--r--activesupport/test/configurable_test.rb12
-rw-r--r--activesupport/test/constantize_test_cases.rb17
-rw-r--r--activesupport/test/core_ext/array/access_test.rb6
-rw-r--r--activesupport/test/core_ext/array/conversions_test.rb116
-rw-r--r--activesupport/test/core_ext/array/extract_options_test.rb8
-rw-r--r--activesupport/test/core_ext/array/grouping_test.rb29
-rw-r--r--activesupport/test/core_ext/array/prepend_append_test.rb6
-rw-r--r--activesupport/test/core_ext/array/wrap_test.rb6
-rw-r--r--activesupport/test/core_ext/bigdecimal_test.rb12
-rw-r--r--activesupport/test/core_ext/class/attribute_test.rb56
-rw-r--r--activesupport/test/core_ext/class_test.rb18
-rw-r--r--activesupport/test/core_ext/date_and_time_behavior.rb368
-rw-r--r--activesupport/test/core_ext/date_and_time_compatibility_test.rb192
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb233
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb278
-rw-r--r--activesupport/test/core_ext/digest/uuid_test.rb8
-rw-r--r--activesupport/test/core_ext/duration_test.rb463
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb56
-rw-r--r--activesupport/test/core_ext/file_test.rb6
-rw-r--r--activesupport/test/core_ext/hash/transform_keys_test.rb36
-rw-r--r--activesupport/test/core_ext/hash/transform_values_test.rb58
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb1200
-rw-r--r--activesupport/test/core_ext/integer_ext_test.rb14
-rw-r--r--activesupport/test/core_ext/kernel/concern_test.rb8
-rw-r--r--activesupport/test/core_ext/kernel_test.rb22
-rw-r--r--activesupport/test/core_ext/load_error_test.rb21
-rw-r--r--activesupport/test/core_ext/marshal_test.rb23
-rw-r--r--activesupport/test/core_ext/module/anonymous_test.rb8
-rw-r--r--activesupport/test/core_ext/module/attr_internal_test.rb32
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb40
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_test.rb64
-rw-r--r--activesupport/test/core_ext/module/attribute_aliasing_test.rb10
-rw-r--r--activesupport/test/core_ext/module/concerning_test.rb16
-rw-r--r--activesupport/test/core_ext/module/introspection_test.rb39
-rw-r--r--activesupport/test/core_ext/module/qualified_const_test.rb118
-rw-r--r--activesupport/test/core_ext/module/reachable_test.rb36
-rw-r--r--activesupport/test/core_ext/module/remove_method_test.rb32
-rw-r--r--activesupport/test/core_ext/module_test.rb419
-rw-r--r--activesupport/test/core_ext/name_error_test.rb6
-rw-r--r--activesupport/test/core_ext/numeric_ext_test.rb459
-rw-r--r--activesupport/test/core_ext/object/acts_like_test.rb6
-rw-r--r--activesupport/test/core_ext/object/blank_test.rb12
-rw-r--r--activesupport/test/core_ext/object/deep_dup_test.rb34
-rw-r--r--activesupport/test/core_ext/object/duplicable_test.rb28
-rw-r--r--activesupport/test/core_ext/object/inclusion_test.rb16
-rw-r--r--activesupport/test/core_ext/object/instance_variables_test.rb20
-rw-r--r--activesupport/test/core_ext/object/json_cherry_pick_test.rb10
-rw-r--r--activesupport/test/core_ext/object/json_gem_encoding_test.rb12
-rw-r--r--activesupport/test/core_ext/object/to_param_test.rb14
-rw-r--r--activesupport/test/core_ext/object/to_query_test.rb68
-rw-r--r--activesupport/test/core_ext/object/try_test.rb34
-rw-r--r--activesupport/test/core_ext/range_ext_test.rb36
-rw-r--r--activesupport/test/core_ext/regexp_ext_test.rb30
-rw-r--r--activesupport/test/core_ext/secure_random_test.rb6
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb239
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb839
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb718
-rw-r--r--activesupport/test/core_ext/uri_ext_test.rb8
-rw-r--r--activesupport/test/current_attributes_test.rb105
-rw-r--r--activesupport/test/dependencies/check_warnings.rb2
-rw-r--r--activesupport/test/dependencies/conflict.rb4
-rw-r--r--activesupport/test/dependencies/cross_site_depender.rb4
-rw-r--r--activesupport/test/dependencies/mutual_one.rb8
-rw-r--r--activesupport/test/dependencies/mutual_two.rb8
-rw-r--r--activesupport/test/dependencies/raises_exception.rb4
-rw-r--r--activesupport/test/dependencies/raises_exception_without_blame_file.rb4
-rw-r--r--activesupport/test/dependencies/requires_nonexistent0.rb4
-rw-r--r--activesupport/test/dependencies/requires_nonexistent1.rb4
-rw-r--r--activesupport/test/dependencies/service_one.rb4
-rw-r--r--activesupport/test/dependencies/service_two.rb4
-rw-r--r--activesupport/test/dependencies_test.rb218
-rw-r--r--activesupport/test/dependencies_test_helpers.rb8
-rw-r--r--activesupport/test/deprecation/method_wrappers_test.rb34
-rw-r--r--activesupport/test/deprecation/proxy_wrappers_test.rb6
-rw-r--r--activesupport/test/deprecation_test.rb126
-rw-r--r--activesupport/test/descendants_tracker_test_cases.rb40
-rw-r--r--activesupport/test/descendants_tracker_with_autoloading_test.rb10
-rw-r--r--activesupport/test/descendants_tracker_without_autoloading_test.rb8
-rw-r--r--activesupport/test/digest_test.rb27
-rw-r--r--activesupport/test/encrypted_configuration_test.rb67
-rw-r--r--activesupport/test/encrypted_file_test.rb59
-rw-r--r--activesupport/test/evented_file_update_checker_test.rb104
-rw-r--r--activesupport/test/executor_test.rb73
-rw-r--r--activesupport/test/file_update_checker_shared_tests.rb82
-rw-r--r--activesupport/test/file_update_checker_test.rb6
-rw-r--r--activesupport/test/fixtures/autoload/another_class.rb4
-rw-r--r--activesupport/test/fixtures/autoload/some_class.rb4
-rw-r--r--activesupport/test/gzip_test.rb22
-rw-r--r--activesupport/test/hash_with_indifferent_access_test.rb803
-rw-r--r--activesupport/test/i18n_test.rb46
-rw-r--r--activesupport/test/inflector_test.rb152
-rw-r--r--activesupport/test/inflector_test_cases.rb111
-rw-r--r--activesupport/test/json/decoding_test.rb130
-rw-r--r--activesupport/test/json/encoding_test.rb211
-rw-r--r--activesupport/test/json/encoding_test_cases.rb56
-rw-r--r--activesupport/test/key_generator_test.rb99
-rw-r--r--activesupport/test/lazy_load_hooks_test.rb52
-rw-r--r--activesupport/test/load_paths_test.rb16
-rw-r--r--activesupport/test/log_subscriber_test.rb8
-rw-r--r--activesupport/test/logger_test.rb84
-rw-r--r--activesupport/test/message_encryptor_test.rb198
-rw-r--r--activesupport/test/message_verifier_test.rb136
-rw-r--r--activesupport/test/messages/rotation_configuration_test.rb25
-rw-r--r--activesupport/test/metadata/shared_metadata_tests.rb93
-rw-r--r--activesupport/test/multibyte_chars_test.rb415
-rw-r--r--activesupport/test/multibyte_conformance_test.rb44
-rw-r--r--activesupport/test/multibyte_grapheme_break_conformance_test.rb54
-rw-r--r--activesupport/test/multibyte_normalization_conformance_test.rb55
-rw-r--r--activesupport/test/multibyte_proxy_test.rb6
-rw-r--r--activesupport/test/multibyte_test_helpers.rb34
-rw-r--r--activesupport/test/multibyte_unicode_database_test.rb4
-rw-r--r--activesupport/test/notifications/evented_notification_test.rb54
-rw-r--r--activesupport/test/notifications/instrumenter_test.rb12
-rw-r--r--activesupport/test/notifications_test.rb60
-rw-r--r--activesupport/test/number_helper_i18n_test.rb155
-rw-r--r--activesupport/test/number_helper_test.rb411
-rw-r--r--activesupport/test/option_merger_test.rb34
-rw-r--r--activesupport/test/ordered_hash_test.rb98
-rw-r--r--activesupport/test/ordered_options_test.rb19
-rw-r--r--activesupport/test/reloader_test.rb26
-rw-r--r--activesupport/test/rescuable_test.rb86
-rw-r--r--activesupport/test/safe_buffer_test.rb88
-rw-r--r--activesupport/test/security_utils_test.rb21
-rw-r--r--activesupport/test/share_lock_test.rb134
-rw-r--r--activesupport/test/string_inquirer_test.rb27
-rw-r--r--activesupport/test/subscriber_test.rb12
-rw-r--r--activesupport/test/tagged_logging_test.rb20
-rw-r--r--activesupport/test/test_case_test.rb180
-rw-r--r--activesupport/test/testing/constant_lookup_test.rb8
-rw-r--r--activesupport/test/testing/file_fixtures_test.rb14
-rw-r--r--activesupport/test/testing/method_call_assertions_test.rb8
-rw-r--r--activesupport/test/time_travel_test.rb149
-rw-r--r--activesupport/test/time_zone_test.rb575
-rw-r--r--activesupport/test/time_zone_test_helpers.rb8
-rw-r--r--activesupport/test/transliterate_test.rb28
-rw-r--r--activesupport/test/xml_mini/jdom_engine_test.rb167
-rw-r--r--activesupport/test/xml_mini/libxml_engine_test.rb211
-rw-r--r--activesupport/test/xml_mini/libxmlsax_engine_test.rb201
-rw-r--r--activesupport/test/xml_mini/nokogiri_engine_test.rb221
-rw-r--r--activesupport/test/xml_mini/nokogirisax_engine_test.rb222
-rw-r--r--activesupport/test/xml_mini/rexml_engine_test.rb38
-rw-r--r--activesupport/test/xml_mini/xml_mini_engine_test.rb264
-rw-r--r--activesupport/test/xml_mini_test.rb116
458 files changed, 16775 insertions, 11510 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 3e07f5a032..3f77b191f9 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,763 +1,492 @@
-* `ActiveSupport::Duration` supports weeks and hours.
+* `assert_changes` will always assert that the expression changes,
+ regardless of `from:` and `to:` argument combinations.
- [1.hour.inspect, 1.hour.value, 1.hour.parts]
- # => ["3600 seconds", 3600, [[:seconds, 3600]]] # Before
- # => ["1 hour", 3600, [[:hours, 1]]] # After
+ *Daniel Ma*
- [1.week.inspect, 1.week.value, 1.week.parts]
- # => ["7 days", 604800, [[:days, 7]]] # Before
- # => ["1 week", 604800, [[:weeks, 1]]] # After
+* Allow the hash function used to generate non-sensitive digests, such as the
+ ETag header, to be specified with `config.active_support.hash_digest_class`.
- This brings us into closer conformance with ISO8601 and relieves some
- astonishment about getting `1.hour.inspect # => 3600 seconds`.
+ The object provided must respond to `#hexdigest`, e.g. `Digest::SHA1`.
- Compatibility: The duration's `value` remains the same, so apps using
- durations are oblivious to the new time periods. Apps, libraries, and
- plugins that work with the internal `parts` hash will need to broaden
- their time period handling to cover hours & weeks.
+ *Dmitri Dolguikh*
- *Andrey Novikov*
-## Rails 5.0.0.beta4 (April 27, 2016) ##
+## Rails 5.2.0.beta2 (November 28, 2017) ##
-* Time zones: Ensure that the UTC offset reflects DST changes that occurred
- since the app started. Removes UTC offset caching, reducing performance,
- but this is still relatively quick and isn't in any hot paths.
+* No changes.
- *Alexey Shein*
-* Make `getlocal` and `getutc` always return instances of `Time` for
- `ActiveSupport::TimeWithZone` and `DateTime`. This eliminates a possible
- stack level too deep error in `to_time` where `ActiveSupport::TimeWithZone`
- was wrapping a `DateTime` instance. As a consequence of this the internal
- time value in `ActiveSupport::TimeWithZone` is now always an instance of
- `Time` in the UTC timezone, whether that's as the UTC time directly or
- a representation of the local time in the timezone. There should be no
- consequences of this internal change and if there are it's a bug due to
- leaky abstractions.
+## Rails 5.2.0.beta1 (November 27, 2017) ##
- *Andrew White*
-
-* Add `DateTime#subsec` to return the fraction of a second as a `Rational`.
-
- *Andrew White*
-
-* Add additional aliases for `DateTime#utc` to mirror the ones on
- `ActiveSupport::TimeWithZone` and `Time`.
-
- *Andrew White*
-
-* Add `DateTime#localtime` to return an instance of `Time` in the system's
- local timezone. Also aliased to `getlocal`.
-
- *Andrew White*, *Yuichiro Kaneko*
-
-* Add `Time#sec_fraction` to return the fraction of a second as a `Rational`.
-
- *Andrew White*
-
-* Add `ActiveSupport.to_time_preserves_timezone` config option to control
- how `to_time` handles timezones. In Ruby 2.4+ the behavior will change
- from converting to the local system timezone, to preserving the timezone
- of the receiver. This config option defaults to false so that apps made
- with earlier versions of Rails are not affected when upgrading, e.g:
+* Changed default behaviour of `ActiveSupport::SecurityUtils.secure_compare`,
+ to make it not leak length information even for variable length string.
- >> ENV['TZ'] = 'US/Eastern'
+ Renamed old `ActiveSupport::SecurityUtils.secure_compare` to `fixed_length_secure_compare`,
+ and started raising `ArgumentError` in case of length mismatch of passed strings.
- >> "2016-04-23T10:23:12.000Z".to_time
- => "2016-04-23T06:23:12.000-04:00"
+ *Vipul A M*
- >> ActiveSupport.to_time_preserves_timezone = true
+* Make `ActiveSupport::TimeZone.all` return only time zones that are in
+ `ActiveSupport::TimeZone::MAPPING`.
- >> "2016-04-23T10:23:12.000Z".to_time
- => "2016-04-23T10:23:12.000Z"
+ Fixes #7245.
- Fixes #24617.
+ *Chris LaRose*
- *Andrew White*
+* MemCacheStore: Support expiring counters.
-* `ActiveSupport::TimeZone.country_zones(country_code)` looks up the
- country's time zones by its two-letter ISO3166 country code, e.g.
+ Pass `expires_in: [seconds]` to `#increment` and `#decrement` options
+ to set the Memcached TTL (time-to-live) if the counter doesn't exist.
+ If the counter exists, Memcached doesn't extend its expiry when it's
+ incremented or decremented.
- >> ActiveSupport::TimeZone.country_zones(:jp).map(&:to_s)
- => ["(GMT+09:00) Osaka"]
+ ```
+ Rails.cache.increment("my_counter", 1, expires_in: 2.minutes)
+ ```
- >> ActiveSupport::TimeZone.country_zones(:uy).map(&:to_s)
- => ["(GMT-03:00) Montevideo"]
+ *Takumasa Ochi*
- *Andrey Novikov*
+* Handle `TZInfo::AmbiguousTime` errors
-* `Array#sum` compat with Ruby 2.4's native method.
+ Make `ActiveSupport::TimeWithZone` match Ruby's handling of ambiguous
+ times by choosing the later period, e.g.
- Ruby 2.4 introduces `Array#sum`, but it only supports numeric elements,
- breaking our `Enumerable#sum` which supports arbitrary `Object#+`.
- To fix, override `Array#sum` with our compatible implementation.
+ Ruby:
+ ```
+ ENV["TZ"] = "Europe/Moscow"
+ Time.local(2014, 10, 26, 1, 0, 0) # => 2014-10-26 01:00:00 +0300
+ ```
- Native Ruby 2.4:
+ Before:
+ ```
+ >> "2014-10-26 01:00:00".in_time_zone("Moscow")
+ TZInfo::AmbiguousTime: 26/10/2014 01:00 is an ambiguous local time.
+ ```
- %w[ a b ].sum
- # => TypeError: String can't be coerced into Fixnum
+ After:
+ ```
+ >> "2014-10-26 01:00:00".in_time_zone("Moscow")
+ => Sun, 26 Oct 2014 01:00:00 MSK +03:00
+ ```
- With `Enumerable#sum` shim:
+ Fixes #17395.
- %w[ a b ].sum
- # => 'ab'
+ *Andrew White*
- We tried shimming the fast path and falling back to the compatible path
- if it fails, but that ends up slower even in simple cases due to the cost
- of exception handling. Our only choice is to override the native `Array#sum`
- with our `Enumerable#sum`.
+* Redis cache store.
+
+ ```
+ # Defaults to `redis://localhost:6379/0`. Only use for dev/test.
+ config.cache_store = :redis_cache_store
+
+ # Supports all common cache store options (:namespace, :compress,
+ # :compress_threshold, :expires_in, :race_condition_ttl) and all
+ # Redis options.
+ cache_password = Rails.application.secrets.redis_cache_password
+ config.cache_store = :redis_cache_store, driver: :hiredis,
+ namespace: 'myapp-cache', compress: true, timeout: 1,
+ url: "redis://:#{cache_password}@myapp-cache-1:6379/0"
+
+ # Supports Redis::Distributed with multiple hosts
+ config.cache_store = :redis_cache_store, driver: :hiredis
+ namespace: 'myapp-cache', compress: true,
+ url: %w[
+ redis://myapp-cache-1:6379/0
+ redis://myapp-cache-1:6380/0
+ redis://myapp-cache-2:6379/0
+ redis://myapp-cache-2:6380/0
+ redis://myapp-cache-3:6379/0
+ redis://myapp-cache-3:6380/0
+ ]
+
+ # Or pass a builder block
+ config.cache_store = :redis_cache_store,
+ namespace: 'myapp-cache', compress: true,
+ redis: -> { Redis.new … }
+ ```
+
+ Deployment note: Take care to use a *dedicated Redis cache* rather
+ than pointing this at your existing Redis server. It won't cope well
+ with mixed usage patterns and it won't expire cache entries by default.
+
+ Redis cache server setup guide: https://redis.io/topics/lru-cache
*Jeremy Daer*
-* `ActiveSupport::Duration` supports ISO8601 formatting and parsing.
-
- ActiveSupport::Duration.parse('P3Y6M4DT12H30M5S')
- # => 3 years, 6 months, 4 days, 12 hours, 30 minutes, and 5 seconds
-
- (3.years + 3.days).iso8601
- # => "P3Y3D"
-
- Inspired by Arnau Siches' [ISO8601 gem](https://github.com/arnau/ISO8601/)
- and rewritten by Andrey Novikov with suggestions from Andrew White. Test
- data from the ISO8601 gem redistributed under MIT license.
-
- (Will be used to support the PostgreSQL interval data type.)
+* Cache: Enable compression by default for values > 1kB.
- *Andrey Novikov*, *Arnau Siches*, *Andrew White*
+ Compression has long been available, but opt-in and at a 16kB threshold.
+ It wasn't enabled by default due to CPU cost. Today it's cheap and typical
+ cache data is eminently compressible, such as HTML or JSON fragments.
+ Compression dramatically reduces Memcached/Redis mem usage, which means
+ the same cache servers can store more data, which means higher hit rates.
-* `Cache#fetch(key, force: true)` forces a cache miss, so it must be called
- with a block to provide a new value to cache. Fetching with `force: true`
- but without a block now raises ArgumentError.
+ To disable compression, pass `compress: false` to the initializer.
- cache.fetch('key', force: true) # => ArgumentError
-
- *Santosh Wadghule*
-
-* Fix behavior of JSON encoding for `Exception`.
-
- *namusyaka*
-
-* Make `number_to_phone` format number with regexp pattern.
-
- number_to_phone(18812345678, pattern: /(\d{3})(\d{4})(\d{4})/)
- # => 188-1234-5678
-
- *Pan Gaoyong*
-
-* Match `String#to_time`'s behaviour to that of ruby's implementation for edge cases.
-
- `nil` is now returned instead of the current date if the string provided does
- contain time information, but none that is used to build the `Time` object.
-
- Fixes #22958.
+ *Jeremy Daer*
- *Siim Liiser*
+* Allow `Range#include?` on TWZ ranges
-* Rely on the native DateTime#<=> implementation to handle non-datetime like
- objects instead of returning `nil` ourselves. This restores the ability
- of `DateTime` instances to be compared with a `Numeric` that represents an
- astronomical julian day number.
+ In #11474 we prevented TWZ ranges being iterated over which matched
+ Ruby's handling of Time ranges and as a consequence `include?`
+ stopped working with both Time ranges and TWZ ranges. However in
+ ruby/ruby@b061634 support was added for `include?` to use `cover?`
+ for 'linear' objects. Since we have no way of making Ruby consider
+ TWZ instances as 'linear' we have to override `Range#include?`.
- Fixes #24228.
+ Fixes #30799.
*Andrew White*
-* Add `String#upcase_first` method.
-
- *Glauco Custódio*, *bogdanvlviv*
-
-* Prevent `Marshal.load` from looping infinitely when trying to autoload a constant
- which resolves to a different name.
-
- *Olek Janiszewski*
-
-* Deprecate `Module.local_constants`. Please use `Module.constants(false)` instead.
-
- *Yuichiro Kaneko*
-
-* Publish `ActiveSupport::Executor` and `ActiveSupport::Reloader` APIs to allow
- components and libraries to manage, and participate in, the execution of
- application code, and the application reloading process.
-
- *Matthew Draper*
-
-
-## Rails 5.0.0.beta3 (February 24, 2016) ##
-
-* Deprecate arguments on `assert_nothing_raised`.
-
- `assert_nothing_raised` does not assert the arguments that have been passed
- in (usually a specific exception class) since the method only yields the
- block. So as not to confuse the users that the arguments have meaning, they
- are being deprecated.
-
- *Tara Scherner de la Fuente*
-
-* Make `benchmark('something', silence: true)` actually work.
-
- *DHH*
-
-* Add `#on_weekday?` method to `Date`, `Time`, and `DateTime`.
-
- `#on_weekday?` returns `true` if the receiving date/time does not fall on a Saturday
- or Sunday.
-
- *Vipul A M*
-
-* Add `Array#second_to_last` and `Array#third_to_last` methods.
-
- *Brian Christian*
-
-* Fix regression in `Hash#dig` for HashWithIndifferentAccess.
-
- *Jon Moss*
-
-
-## Rails 5.0.0.beta2 (February 01, 2016) ##
-
-* Change `number_to_currency` behavior for checking negativity.
-
- Used `to_f.negative` instead of using `to_f.phase` for checking negativity
- of a number in number_to_currency helper.
- This change works same for all cases except when number is "-0.0".
-
- -0.0.to_f.negative? => false
- -0.0.to_f.phase? => 3.14
-
- This change reverts changes from https://github.com/rails/rails/pull/6512.
- But it should be acceptable as we could not find any currency which
- supports negative zeros.
-
- *Prathamesh Sonpatki*, *Rafael Mendonça França*
-
-* Match `HashWithIndifferentAccess#default`'s behaviour with `Hash#default`.
-
- *David Cornu*
-
-* Adds `:exception_object` key to `ActiveSupport::Notifications::Instrumenter`
- payload when an exception is raised.
-
- Adds new key/value pair to payload when an exception is raised:
- e.g. `:exception_object => #<RuntimeError: FAIL>`.
-
- *Ryan T. Hosford*
-
-* Support extended grapheme clusters and UAX 29.
-
- *Adam Roben*
-
-* Add petabyte and exabyte numeric conversion.
-
- *Akshay Vishnoi*
-
-
-## Rails 5.0.0.beta1 (December 18, 2015) ##
-
-* Add thread_m/cattr_accessor/reader/writer suite of methods for declaring class and module variables that live per-thread.
- This makes it easy to declare per-thread globals that are encapsulated. Note: This is a sharp edge. A wild proliferation
- of globals is A Bad Thing. But like other sharp tools, when it's right, it's right.
-
- Here's an example of a simple event tracking system where the object being tracked needs not pass a creator that it
- doesn't need itself along:
-
- module Current
- thread_mattr_accessor :account
- thread_mattr_accessor :user
-
- def self.reset() self.account = self.user = nil end
- end
-
- class ApplicationController < ActionController::Base
- before_action :set_current
- after_action { Current.reset }
-
- private
- def set_current
- Current.account = Account.find(params[:account_id])
- Current.user = Current.account.users.find(params[:user_id])
- end
- end
-
- class MessagesController < ApplicationController
- def create
- @message = Message.create!(message_params)
- end
- end
-
- class Message < ApplicationRecord
- has_many :events
- after_create :track_created
-
- private
- def track_created
- events.create! origin: self, action: :create
- end
- end
-
- class Event < ApplicationRecord
- belongs_to :creator, class_name: 'User'
- before_validation { self.creator ||= Current.user }
- end
-
- *DHH*
+* Fix acronym support in `humanize`
+ Acronym inflections are stored with lowercase keys in the hash but
+ the match wasn't being lowercased before being looked up in the hash.
+ This shouldn't have any performance impact because before it would
+ fail to find the acronym and perform the `downcase` operation anyway.
-* Deprecated `Module#qualified_const_` in favour of the builtin Module#const_
- methods.
+ Fixes #31052.
- *Genadi Samokovarov*
-
-* Deprecate passing string to define callback.
-
- *Yuichiro Kaneko*
-
-* `ActiveSupport::Cache::Store#namespaced_key`,
- `ActiveSupport::Cache::MemCachedStore#escape_key`, and
- `ActiveSupport::Cache::FileStore#key_file_path`
- are deprecated and replaced with `normalize_key` that now calls `super`.
-
- `ActiveSupport::Cache::LocaleCache#set_cache_value` is deprecated and replaced with `write_cache_value`.
-
- *Michael Grosser*
-
-* Implements an evented file watcher to asynchronously detect changes in the
- application source code, routes, locales, etc.
-
- This watcher is disabled by default, applications my enable it in the configuration:
-
- # config/environments/development.rb
- config.file_watcher = ActiveSupport::EventedFileUpdateChecker
-
- This feature depends on the [listen](https://github.com/guard/listen) gem:
-
- group :development do
- gem 'listen', '~> 3.0.5'
- end
-
- *Puneet Agarwal* and *Xavier Noria*
-
-* Added `Time.days_in_year` to return the number of days in the given year, or the
- current year if no argument is provided.
+ *Andrew White*
- *Jon Pascoe*
+* Add same method signature for `Time#prev_year` and `Time#next_year`
+ in accordance with `Date#prev_year`, `Date#next_year`.
-* Updated `parameterize` to preserve the case of a string, optionally.
+ Allows pass argument for `Time#prev_year` and `Time#next_year`.
- Example:
+ Before:
+ ```
+ Time.new(2017, 9, 16, 17, 0).prev_year # => 2016-09-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).prev_year(1)
+ # => ArgumentError: wrong number of arguments (given 1, expected 0)
- parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth"
- parameterize("Donald E. Knuth", preserve_case: true) # => "Donald-E-Knuth"
+ Time.new(2017, 9, 16, 17, 0).next_year # => 2018-09-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).next_year(1)
+ # => ArgumentError: wrong number of arguments (given 1, expected 0)
+ ```
- *Swaathi Kakarla*
+ After:
+ ```
+ Time.new(2017, 9, 16, 17, 0).prev_year # => 2016-09-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).prev_year(1) # => 2016-09-16 17:00:00 +0300
-* `HashWithIndifferentAccess.new` respects the default value or proc on objects
- that respond to `#to_hash`. `.new_from_hash_copying_default` simply invokes `.new`.
- All calls to `.new_from_hash_copying_default` are replaced with `.new`.
+ Time.new(2017, 9, 16, 17, 0).next_year # => 2018-09-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).next_year(1) # => 2018-09-16 17:00:00 +0300
+ ```
- *Gordon Chan*
+ *bogdanvlviv*
-* Change Integer#year to return a Fixnum instead of a Float to improve
- consistency.
+* Add same method signature for `Time#prev_month` and `Time#next_month`
+ in accordance with `Date#prev_month`, `Date#next_month`.
- Integer#years returned a Float while the rest of the accompanying methods
- (days, weeks, months, etc.) return a Fixnum.
+ Allows pass argument for `Time#prev_month` and `Time#next_month`.
Before:
+ ```
+ Time.new(2017, 9, 16, 17, 0).prev_month # => 2017-08-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).prev_month(1)
+ # => ArgumentError: wrong number of arguments (given 1, expected 0)
- 1.year # => 31557600.0
+ Time.new(2017, 9, 16, 17, 0).next_month # => 2017-10-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).next_month(1)
+ # => ArgumentError: wrong number of arguments (given 1, expected 0)
+ ```
After:
+ ```
+ Time.new(2017, 9, 16, 17, 0).prev_month # => 2017-08-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).prev_month(1) # => 2017-08-16 17:00:00 +0300
- 1.year # => 31557600
-
- *Konstantinos Rousis*
-
-* Handle invalid UTF-8 strings when HTML escaping.
-
- Use `ActiveSupport::Multibyte::Unicode.tidy_bytes` to handle invalid UTF-8
- strings in `ERB::Util.unwrapped_html_escape` and `ERB::Util.html_escape_once`.
- Prevents user-entered input passed from a querystring into a form field from
- causing invalid byte sequence errors.
-
- *Grey Baker*
-
-* Update `ActiveSupport::Multibyte::Chars#slice!` to return `nil` if the
- arguments are out of bounds, to mirror the behavior of `String#slice!`
+ Time.new(2017, 9, 16, 17, 0).next_month # => 2017-10-16 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).next_month(1) # => 2017-10-16 17:00:00 +0300
+ ```
- *Gourav Tiwari*
+ *bogdanvlviv*
-* Fix `number_to_human` so that 999999999 rounds to "1 Billion" instead of
- "1000 Million".
+* Add same method signature for `Time#prev_day` and `Time#next_day`
+ in accordance with `Date#prev_day`, `Date#next_day`.
- *Max Jacobson*
+ Allows pass argument for `Time#prev_day` and `Time#next_day`.
-* Fix `ActiveSupport::Deprecation#deprecate_methods` to report using the
- current deprecator instance, where applicable.
-
- *Brandon Dunne*
+ Before:
+ ```
+ Time.new(2017, 9, 16, 17, 0).prev_day # => 2017-09-15 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).prev_day(1)
+ # => ArgumentError: wrong number of arguments (given 1, expected 0)
-* `Cache#fetch` instrumentation marks whether it was a `:hit`.
+ Time.new(2017, 9, 16, 17, 0).next_day # => 2017-09-17 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).next_day(1)
+ # => ArgumentError: wrong number of arguments (given 1, expected 0)
+ ```
- *Robin Clowers*
+ After:
+ ```
+ Time.new(2017, 9, 16, 17, 0).prev_day # => 2017-09-15 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).prev_day(1) # => 2017-09-15 17:00:00 +0300
-* `assert_difference` and `assert_no_difference` now returns the result of the
- yielded block.
+ Time.new(2017, 9, 16, 17, 0).next_day # => 2017-09-17 17:00:00 +0300
+ Time.new(2017, 9, 16, 17, 0).next_day(1) # => 2017-09-17 17:00:00 +0300
+ ```
- Example:
+ *bogdanvlviv*
- post = assert_difference -> { Post.count }, 1 do
- Post.create
- end
+* `IO#to_json` now returns the `to_s` representation, rather than
+ attempting to convert to an array. This fixes a bug where `IO#to_json`
+ would raise an `IOError` when called on an unreadable object.
- *Lucas Mazza*
+ Fixes #26132.
-* Short-circuit `blank?` on date and time values since they are never blank.
+ *Paul Kuruvilla*
- Fixes #21657.
+* Remove deprecated `halt_callback_chains_on_return_false` option.
- *Andrew White*
+ *Rafael Mendonça França*
-* Replaced deprecated `ThreadSafe::Cache` with its successor `Concurrent::Map` now that
- the thread_safe gem has been merged into concurrent-ruby.
+* Remove deprecated `:if` and `:unless` string filter for callbacks.
- *Jerry D'Antonio*
+ *Rafael Mendonça França*
-* Updated Unicode version to 8.0.0
+* `Hash#slice` now falls back to Ruby 2.5+'s built-in definition if defined.
- *Anshul Sharma*
+ *Akira Matsuda*
-* `number_to_currency` and `number_with_delimiter` now accept custom `delimiter_pattern` option
- to handle placement of delimiter, to support currency formats like INR
+* Deprecate `secrets.secret_token`.
- Example:
+ The architecture for secrets had a big upgrade between Rails 3 and Rails 4,
+ when the default changed from using `secret_token` to `secret_key_base`.
- number_to_currency(1230000, delimiter_pattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/, unit: '₹', format: "%u %n")
- # => '₹ 12,30,000.00'
+ `secret_token` has been soft deprecated in documentation for four years
+ but is still in place to support apps created before Rails 4.
+ Deprecation warnings have been added to help developers upgrade their
+ applications to `secret_key_base`.
- *Vipul A M*
+ *claudiob*, *Kasper Timm Hansen*
-* Deprecate `:prefix` option of `number_to_human_size` with no replacement.
+* Return an instance of `HashWithIndifferentAccess` from `HashWithIndifferentAccess#transform_keys`.
- *Jean Boussier*
+ *Yuji Yaginuma*
-* Fix `TimeWithZone#eql?` to properly handle `TimeWithZone` created from `DateTime`:
- twz = DateTime.now.in_time_zone
- twz.eql?(twz.dup) => true
+* Add key rotation support to `MessageEncryptor` and `MessageVerifier`
- Fixes #14178.
+ This change introduces a `rotate` method to both the `MessageEncryptor` and
+ `MessageVerifier` classes. This method accepts the same arguments and
+ options as the given classes' constructor. The `encrypt_and_verify` method
+ for `MessageEncryptor` and the `verified` method for `MessageVerifier` also
+ accept an optional keyword argument `:on_rotation` block which is called
+ when a rotated instance is used to decrypt or verify the message.
- *Roque Pinel*
+ *Michael J Coyne*
-* ActiveSupport::HashWithIndifferentAccess `select` and `reject` will now return
- enumerator if called without block.
+* Deprecate `Module#reachable?` method.
- Fixes #20095.
+ *bogdanvlviv*
- *Bernard Potocki*
+* Add `config/credentials.yml.enc` to store production app secrets.
-* Removed `ActiveSupport::Concurrency::Latch`, superseded by `Concurrent::CountDownLatch`
- from the concurrent-ruby gem.
+ Allows saving any authentication credentials for third party services
+ directly in repo encrypted with `config/master.key` or `ENV["RAILS_MASTER_KEY"]`.
- *Jerry D'Antonio*
+ This will eventually replace `Rails.application.secrets` and the encrypted
+ secrets introduced in Rails 5.1.
-* Fix not calling `#default` on `HashWithIndifferentAccess#to_hash` when only
- `default_proc` is set, which could raise.
+ *DHH*, *Kasper Timm Hansen*
- *Simon Eskildsen*
+* Add `ActiveSupport::EncryptedFile` and `ActiveSupport::EncryptedConfiguration`.
-* Fix setting `default_proc` on `HashWithIndifferentAccess#dup`.
+ Allows for stashing encrypted files or configuration directly in repo by
+ encrypting it with a key.
- *Simon Eskildsen*
+ Backs the new credentials setup above, but can also be used independently.
-* Fix a range of values for parameters of the Time#change.
+ *DHH*, *Kasper Timm Hansen*
- *Nikolay Kondratyev*
+* `Module#delegate_missing_to` now raises `DelegationError` if target is nil,
+ similar to `Module#delegate`.
-* Add `Enumerable#pluck` to get the same values from arrays as from ActiveRecord
- associations.
+ *Anton Khamets*
- Fixes #20339.
+* Update `String#camelize` to provide feedback when wrong option is passed
- *Kevin Deisz*
+ `String#camelize` was returning nil without any feedback when an
+ invalid option was passed as a parameter.
-* Add a bang version to `ActiveSupport::OrderedOptions` get methods which will raise
- an `KeyError` if the value is `.blank?`.
+ Previously:
- Before:
+ 'one_two'.camelize(true)
+ # => nil
- if (slack_url = Rails.application.secrets.slack_url).present?
- # Do something worthwhile
- else
- # Raise as important secret password is not specified
- end
+ Now:
- After:
+ 'one_two'.camelize(true)
+ # => ArgumentError: Invalid option, use either :upper or :lower.
- slack_url = Rails.application.secrets.slack_url!
+ *Ricardo Díaz*
- *Aditya Sanghi*, *Gaurish Sharma*
+* Fix modulo operations involving durations
-* Remove deprecated `Class#superclass_delegating_accessor`.
- Use `Class#class_attribute` instead.
+ Rails 5.1 introduced `ActiveSupport::Duration::Scalar` as a wrapper
+ around numeric values as a way of ensuring a duration was the outcome of
+ an expression. However, the implementation was missing support for modulo
+ operations. This support has now been added and should result in a duration
+ being returned from expressions involving modulo operations.
- *Akshay Vishnoi*
+ Prior to Rails 5.1:
-* Patch `Delegator` to work with `#try`.
+ 5.minutes % 2.minutes
+ # => 60
- Fixes #5790.
+ Now:
- *Nate Smith*
+ 5.minutes % 2.minutes
+ # => 1 minute
-* Add `Integer#positive?` and `Integer#negative?` query methods
- in the vein of `Fixnum#zero?`.
+ Fixes #29603 and #29743.
- This makes it nicer to do things like `bunch_of_numbers.select(&:positive?)`.
+ *Sayan Chakraborty*, *Andrew White*
- *DHH*
+* Fix division where a duration is the denominator
-* Encoding `ActiveSupport::TimeWithZone` to YAML now preserves the timezone information.
+ PR #29163 introduced a change in behavior when a duration was the denominator
+ in a calculation - this was incorrect as dividing by a duration should always
+ return a `Numeric`. The behavior of previous versions of Rails has been restored.
- Fixes #9183.
+ Fixes #29592.
*Andrew White*
-* Added `ActiveSupport::TimeZone#strptime` to allow parsing times as if
- from a given timezone.
-
- *Paul A Jungwirth*
-
-* `ActiveSupport::Callbacks#skip_callback` now raises an `ArgumentError` if
- an unrecognized callback is removed.
-
- *Iain Beeston*
-
-* Added `ActiveSupport::ArrayInquirer` and `Array#inquiry`.
-
- Wrapping an array in an `ArrayInquirer` gives a friendlier way to check its
- contents:
-
- variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
-
- variants.phone? # => true
- variants.tablet? # => true
- variants.desktop? # => false
-
- variants.any?(:phone, :tablet) # => true
- variants.any?(:phone, :desktop) # => true
- variants.any?(:desktop, :watch) # => false
-
- `Array#inquiry` is a shortcut for wrapping the receiving array in an
- `ArrayInquirer`.
-
- *George Claghorn*
+* Add purpose and expiry support to `ActiveSupport::MessageVerifier` &
+ `ActiveSupport::MessageEncryptor`.
-* Deprecate `alias_method_chain` in favour of `Module#prepend` introduced in
- Ruby 2.0.
+ For instance, to ensure a message is only usable for one intended purpose:
- *Kir Shatrov*
+ token = @verifier.generate("x", purpose: :shipping)
-* Added `#without` on `Enumerable` and `Array` to return a copy of an
- enumerable without the specified elements.
+ @verifier.verified(token, purpose: :shipping) # => "x"
+ @verifier.verified(token) # => nil
- *Todd Bealmear*
+ Or make it expire after a set time:
-* Fixed a problem where `String#truncate_words` would get stuck with a complex
- string.
+ @verifier.generate("x", expires_in: 1.month)
+ @verifier.generate("y", expires_at: Time.now.end_of_year)
- *Henrik Nygren*
+ Showcased with `ActiveSupport::MessageVerifier`, but works the same for
+ `ActiveSupport::MessageEncryptor`'s `encrypt_and_sign` and `decrypt_and_verify`.
-* Fixed a roundtrip problem with `AS::SafeBuffer` where primitive-like strings
- will be dumped as primitives:
+ Pull requests: #29599, #29854
- Before:
-
- YAML.load ActiveSupport::SafeBuffer.new("Hello").to_yaml # => "Hello"
- YAML.load ActiveSupport::SafeBuffer.new("true").to_yaml # => true
- YAML.load ActiveSupport::SafeBuffer.new("false").to_yaml # => false
- YAML.load ActiveSupport::SafeBuffer.new("1").to_yaml # => 1
- YAML.load ActiveSupport::SafeBuffer.new("1.1").to_yaml # => 1.1
-
- After:
-
- YAML.load ActiveSupport::SafeBuffer.new("Hello").to_yaml # => "Hello"
- YAML.load ActiveSupport::SafeBuffer.new("true").to_yaml # => "true"
- YAML.load ActiveSupport::SafeBuffer.new("false").to_yaml # => "false"
- YAML.load ActiveSupport::SafeBuffer.new("1").to_yaml # => "1"
- YAML.load ActiveSupport::SafeBuffer.new("1.1").to_yaml # => "1.1"
-
- *Godfrey Chan*
-
-* Enable `number_to_percentage` to keep the number's precision by allowing
- `:precision` to be `nil`.
-
- *Jack Xu*
-
-* `config_accessor` became a private method, as with Ruby's `attr_accessor`.
-
- *Akira Matsuda*
-
-* `AS::Testing::TimeHelpers#travel_to` now changes `DateTime.now` as well as
- `Time.now` and `Date.today`.
-
- *Yuki Nishijima*
-
-* Add `file_fixture` to `ActiveSupport::TestCase`.
- It provides a simple mechanism to access sample files in your test cases.
-
- By default file fixtures are stored in `test/fixtures/files`. This can be
- configured per test-case using the `file_fixture_path` class attribute.
-
- *Yves Senn*
-
-* Return value of yielded block in `File.atomic_write`.
-
- *Ian Ker-Seymer*
-
-* Duplicate frozen array when assigning it to a `HashWithIndifferentAccess` so
- that it doesn't raise a `RuntimeError` when calling `map!` on it in `convert_value`.
-
- Fixes #18550.
-
- *Aditya Kapoor*
+ *Assain Jaleel*
-* Add missing time zone definitions for Russian Federation and sync them
- with `zone.tab` file from tzdata version 2014j (latest).
+* Make the order of `Hash#reverse_merge!` consistent with `HashWithIndifferentAccess`.
- *Andrey Novikov*
+ *Erol Fornoles*
-* Add `SecureRandom.base58` for generation of random base58 strings.
+* Add `freeze_time` helper which freezes time to `Time.now` in tests.
- *Matthew Draper*, *Guillermo Iguaran*
+ *Prathamesh Sonpatki*
-* Add `#prev_day` and `#next_day` counterparts to `#yesterday` and
- `#tomorrow` for `Date`, `Time`, and `DateTime`.
+* Default `ActiveSupport::MessageEncryptor` to use AES 256 GCM encryption.
- *George Claghorn*
+ On for new Rails 5.2 apps. Upgrading apps can find the config as a new
+ framework default.
-* Add `same_time` option to `#next_week` and `#prev_week` for `Date`, `Time`,
- and `DateTime`.
+ *Assain Jaleel*
- *George Claghorn*
+* Cache: `write_multi`
-* Add `#on_weekend?`, `#next_weekday`, `#prev_weekday` methods to `Date`,
- `Time`, and `DateTime`.
+ Rails.cache.write_multi foo: 'bar', baz: 'qux'
- `#on_weekend?` returns `true` if the receiving date/time falls on a Saturday
- or Sunday.
+ Plus faster fetch_multi with stores that implement `write_multi_entries`.
+ Keys that aren't found may be written to the cache store in one shot
+ instead of separate writes.
- `#next_weekday` returns a new date/time representing the next day that does
- not fall on a Saturday or Sunday.
+ The default implementation simply calls `write_entry` for each entry.
+ Stores may override if they're capable of one-shot bulk writes, like
+ Redis `MSET`.
- `#prev_weekday` returns a new date/time representing the previous day that
- does not fall on a Saturday or Sunday.
-
- *George Claghorn*
+ *Jeremy Daer*
-* Change the default test order from `:sorted` to `:random`.
+* Add default option to module and class attribute accessors.
- *Rafael Mendonça França*
+ mattr_accessor :settings, default: {}
-* Remove deprecated `ActiveSupport::JSON::Encoding::CircularReferenceError`.
+ Works for `mattr_reader`, `mattr_writer`, `cattr_accessor`, `cattr_reader`,
+ and `cattr_writer` as well.
- *Rafael Mendonça França*
+ *Genadi Samokovarov*
-* Remove deprecated methods `ActiveSupport::JSON::Encoding.encode_big_decimal_as_string=`
- and `ActiveSupport::JSON::Encoding.encode_big_decimal_as_string`.
+* Add `Date#prev_occurring` and `Date#next_occurring` to return specified next/previous occurring day of week.
- *Rafael Mendonça França*
+ *Shota Iguchi*
-* Remove deprecated `ActiveSupport::SafeBuffer#prepend`.
+* Add default option to `class_attribute`.
- *Rafael Mendonça França*
+ Before:
-* Remove deprecated methods at `Kernel`.
+ class_attribute :settings
+ self.settings = {}
- `silence_stderr`, `silence_stream`, `capture` and `quietly`.
+ Now:
- *Rafael Mendonça França*
+ class_attribute :settings, default: {}
-* Remove deprecated `active_support/core_ext/big_decimal/yaml_conversions`
- file.
-
- *Rafael Mendonça França*
-
-* Remove deprecated methods `ActiveSupport::Cache::Store.instrument` and
- `ActiveSupport::Cache::Store.instrument=`.
+ *DHH*
- *Rafael Mendonça França*
+* `#singularize` and `#pluralize` now respect uncountables for the specified locale.
-* Change the way in which callback chains can be halted.
+ *Eilis Hamilton*
- The preferred method to halt a callback chain from now on is to explicitly
- `throw(:abort)`.
- In the past, callbacks could only be halted by explicitly providing a
- terminator and by having a callback match the conditions of the terminator.
+* Add `ActiveSupport::CurrentAttributes` to provide a thread-isolated attributes singleton.
+ Primary use case is keeping all the per-request attributes easily available to the whole system.
-* Add `ActiveSupport.halt_callback_chains_on_return_false`
+ *DHH*
- Setting `ActiveSupport.halt_callback_chains_on_return_false`
- to `true` will let an app support the deprecated way of halting Active Record,
- and Active Model callback chains by returning `false`.
+* Fix implicit coercion calculations with scalars and durations
- Setting the value to `false` will tell the app to ignore any `false` value
- returned by those callbacks, and only halt the chain upon `throw(:abort)`.
+ Previously, calculations where the scalar is first would be converted to a duration
+ of seconds, but this causes issues with dates being converted to times, e.g:
- When the configuration option is missing, its value is `true`, so older apps
- ported to Rails 5.0 will not break (but display a deprecation warning).
- For new Rails 5.0 apps, its value is set to `false` in an initializer, so
- these apps will support the new behavior by default.
+ Time.zone = "Beijing" # => Asia/Shanghai
+ date = Date.civil(2017, 5, 20) # => Mon, 20 May 2017
+ 2 * 1.day # => 172800 seconds
+ date + 2 * 1.day # => Mon, 22 May 2017 00:00:00 CST +08:00
- *claudiob*, *Roque Pinel*
+ Now, the `ActiveSupport::Duration::Scalar` calculation methods will try to maintain
+ the part structure of the duration where possible, e.g:
-* Changes arguments and default value of CallbackChain's `:terminator` option
+ Time.zone = "Beijing" # => Asia/Shanghai
+ date = Date.civil(2017, 5, 20) # => Mon, 20 May 2017
+ 2 * 1.day # => 2 days
+ date + 2 * 1.day # => Mon, 22 May 2017
- Chains of callbacks defined without an explicit `:terminator` option will
- now be halted as soon as a `before_` callback throws `:abort`.
+ Fixes #29160, #28970.
- Chains of callbacks defined with a `:terminator` option will maintain their
- existing behavior of halting as soon as a `before_` callback matches the
- terminator's expectation.
+ *Andrew White*
- *claudiob*
+* Add support for versioned cache entries. This enables the cache stores to recycle cache keys, greatly saving
+ on storage in cases with frequent churn. Works together with the separation of `#cache_key` and `#cache_version`
+ in Active Record and its use in Action Pack's fragment caching.
-* Deprecate `MissingSourceFile` in favor of `LoadError`.
+ *DHH*
- `MissingSourceFile` was just an alias to `LoadError` and was not being
- raised inside the framework.
+* Pass gem name and deprecation horizon to deprecation notifications.
- *Rafael Mendonça França*
+ *Willem van Bergen*
-* Add support for error dispatcher classes in `ActiveSupport::Rescuable`.
- Now it acts closer to Ruby's rescue.
+* Add support for `:offset` and `:zone` to `ActiveSupport::TimeWithZone#change`
- Example:
+ *Andrew White*
- class BaseController < ApplicationController
- module ErrorDispatcher
- def self.===(other)
- Exception === other && other.respond_to?(:status)
- end
- end
+* Add support for `:offset` to `Time#change`
- rescue_from ErrorDispatcher do |error|
- render status: error.status, json: { error: error.to_s }
- end
- end
+ Fixes #28723.
- *Genadi Samokovarov*
+ *Andrew White*
-* Add `#verified` and `#valid_message?` methods to `ActiveSupport::MessageVerifier`
+* Add `fetch_values` for `HashWithIndifferentAccess`
- Previously, the only way to decode a message with `ActiveSupport::MessageVerifier`
- was to use `#verify`, which would raise an exception on invalid messages. Now
- `#verified` can also be used, which returns `nil` on messages that cannot be
- decoded.
+ The method was originally added to `Hash` in Ruby 2.3.0.
- Previously, there was no way to check if a message's format was valid without
- attempting to decode it. `#valid_message?` is a boolean convenience method that
- checks whether the message is valid without actually decoding it.
+ *Josh Pencheon*
- *Logan Leger*
-Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activesupport/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activesupport/CHANGELOG.md) for previous changes.
diff --git a/activesupport/MIT-LICENSE b/activesupport/MIT-LICENSE
index 40235833ba..8f769c0767 100644
--- a/activesupport/MIT-LICENSE
+++ b/activesupport/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2005-2016 David Heinemeier Hansson
+Copyright (c) 2005-2018 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc
index 14ce204303..c770324be8 100644
--- a/activesupport/README.rdoc
+++ b/activesupport/README.rdoc
@@ -21,7 +21,7 @@ Source code can be downloaded as part of the Rails project on GitHub:
Active Support is released under the MIT license:
-* http://www.opensource.org/licenses/MIT
+* https://opensource.org/licenses/MIT
== Support
@@ -30,7 +30,7 @@ API documentation is at:
* http://api.rubyonrails.org
-Bug reports can be filed for the Ruby on Rails project here:
+Bug reports for the Ruby on Rails project can be filed here:
* https://github.com/rails/rails/issues
diff --git a/activesupport/Rakefile b/activesupport/Rakefile
index 33ee62aa1b..8672ab1542 100644
--- a/activesupport/Rakefile
+++ b/activesupport/Rakefile
@@ -1,13 +1,14 @@
-require 'rake/testtask'
+# frozen_string_literal: true
-task :default => :test
+require "rake/testtask"
+
+task default: :test
task :package
-task "package:clean"
Rake::TestTask.new do |t|
- t.libs << 'test'
- t.pattern = 'test/**/*_test.rb'
+ t.libs << "test"
+ t.pattern = "test/**/*_test.rb"
t.warning = true
t.verbose = true
t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
@@ -16,7 +17,7 @@ end
namespace :test do
task :isolated do
Dir.glob("test/**/*_test.rb").all? do |file|
- sh(Gem.ruby, '-w', '-Ilib:test', file)
- end or raise "Failures"
+ sh(Gem.ruby, "-w", "-Ilib:test", file)
+ end || raise("Failures")
end
end
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index c6ca969844..db801d2da2 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -1,27 +1,34 @@
-version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+# frozen_string_literal: true
+
+version = File.read(File.expand_path("../RAILS_VERSION", __dir__)).strip
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
- s.name = 'activesupport'
+ s.name = "activesupport"
s.version = version
- s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.'
- s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.'
+ s.summary = "A toolkit of support libraries and Ruby core extensions extracted from the Rails framework."
+ s.description = "A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing."
+
+ s.required_ruby_version = ">= 2.2.2"
- s.required_ruby_version = '>= 2.2.2'
+ s.license = "MIT"
- s.license = 'MIT'
+ s.author = "David Heinemeier Hansson"
+ s.email = "david@loudthinking.com"
+ s.homepage = "http://rubyonrails.org"
- s.author = 'David Heinemeier Hansson'
- s.email = 'david@loudthinking.com'
- s.homepage = 'http://rubyonrails.org'
+ s.files = Dir["CHANGELOG.md", "MIT-LICENSE", "README.rdoc", "lib/**/*"]
+ s.require_path = "lib"
- s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
- s.require_path = 'lib'
+ s.rdoc_options.concat ["--encoding", "UTF-8"]
- s.rdoc_options.concat ['--encoding', 'UTF-8']
+ s.metadata = {
+ "source_code_uri" => "https://github.com/rails/rails/tree/v#{version}/activesupport",
+ "changelog_uri" => "https://github.com/rails/rails/blob/v#{version}/activesupport/CHANGELOG.md"
+ }
- s.add_dependency 'i18n', '~> 0.7'
- s.add_dependency 'tzinfo', '~> 1.1'
- s.add_dependency 'minitest', '~> 5.1'
- s.add_dependency 'concurrent-ruby', '~> 1.0', '>= 1.0.2'
+ s.add_dependency "i18n", "~> 0.7"
+ s.add_dependency "tzinfo", "~> 1.1"
+ s.add_dependency "minitest", "~> 5.1"
+ s.add_dependency "concurrent-ruby", "~> 1.0", ">= 1.0.2"
end
diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables
index 2193533588..18199b2171 100755
--- a/activesupport/bin/generate_tables
+++ b/activesupport/bin/generate_tables
@@ -1,18 +1,19 @@
#!/usr/bin/env ruby
+# frozen_string_literal: true
begin
- $:.unshift(File.expand_path(File.dirname(__FILE__) + '/../lib'))
- require 'active_support'
+ $:.unshift(File.expand_path("../lib", __dir__))
+ require "active_support"
rescue IOError
end
-require 'open-uri'
-require 'tmpdir'
+require "open-uri"
+require "tmpdir"
+require "fileutils"
module ActiveSupport
module Multibyte
module Unicode
-
class UnicodeDatabase
def load; end
end
@@ -20,10 +21,10 @@ module ActiveSupport
class DatabaseGenerator
BASE_URI = "http://www.unicode.org/Public/#{UNICODE_VERSION}/ucd/"
SOURCES = {
- :codepoints => BASE_URI + 'UnicodeData.txt',
- :composition_exclusion => BASE_URI + 'CompositionExclusions.txt',
- :grapheme_break_property => BASE_URI + 'auxiliary/GraphemeBreakProperty.txt',
- :cp1252 => 'http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT'
+ codepoints: BASE_URI + "UnicodeData.txt",
+ composition_exclusion: BASE_URI + "CompositionExclusions.txt",
+ grapheme_break_property: BASE_URI + "auxiliary/GraphemeBreakProperty.txt",
+ cp1252: "http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT"
}
def initialize
@@ -52,9 +53,9 @@ module ActiveSupport
codepoint.code = $1.hex
codepoint.combining_class = Integer($4)
codepoint.decomp_type = $7
- codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect(&:hex)
- codepoint.uppercase_mapping = ($16=='') ? 0 : $16.hex
- codepoint.lowercase_mapping = ($17=='') ? 0 : $17.hex
+ codepoint.decomp_mapping = ($8 == "") ? nil : $8.split.collect(&:hex)
+ codepoint.uppercase_mapping = ($16 == "") ? 0 : $16.hex
+ codepoint.lowercase_mapping = ($17 == "") ? 0 : $17.hex
@ucd.codepoints[codepoint.code] = codepoint
end
@@ -62,8 +63,8 @@ module ActiveSupport
if line =~ /^([0-9A-F.]+)\s*;\s*([\w]+)\s*#/
type = $2.downcase.intern
@ucd.boundary[type] ||= []
- if $1.include? '..'
- parts = $1.split '..'
+ if $1.include? ".."
+ parts = $1.split ".."
@ucd.boundary[type] << (parts[0].hex..parts[1].hex)
else
@ucd.boundary[type] << $1.hex
@@ -85,7 +86,7 @@ module ActiveSupport
def create_composition_map
@ucd.codepoints.each do |_, cp|
- if !cp.nil? and cp.combining_class == 0 and cp.decomp_type.nil? and !cp.decomp_mapping.nil? and cp.decomp_mapping.length == 2 and @ucd.codepoints[cp.decomp_mapping[0]].combining_class == 0 and !@ucd.composition_exclusion.include?(cp.code)
+ if !cp.nil? && cp.combining_class == 0 && cp.decomp_type.nil? && !cp.decomp_mapping.nil? && cp.decomp_mapping.length == 2 && @ucd.codepoints[cp.decomp_mapping[0]].combining_class == 0 && !@ucd.composition_exclusion.include?(cp.code)
@ucd.composition_map[cp.decomp_mapping[0]] ||= {}
@ucd.composition_map[cp.decomp_mapping[0]][cp.decomp_mapping[1]] = cp.code
end
@@ -93,7 +94,7 @@ module ActiveSupport
end
def normalize_boundary_map
- @ucd.boundary.each do |k,v|
+ @ucd.boundary.each do |k, v|
if [:lf, :cr].include? k
@ucd.boundary[k] = v[0]
end
@@ -102,10 +103,11 @@ module ActiveSupport
def parse
SOURCES.each do |type, url|
- filename = File.join(Dir.tmpdir, "#{url.split('/').last}")
+ filename = File.join(Dir.tmpdir, UNICODE_VERSION, "#{url.split('/').last}")
unless File.exist?(filename)
$stderr.puts "Downloading #{url.split('/').last}"
- File.open(filename, 'wb') do |target|
+ FileUtils.mkdir_p(File.dirname(filename))
+ File.open(filename, "wb") do |target|
open(url) do |source|
source.each_line { |line| target.write line }
end
@@ -120,7 +122,7 @@ module ActiveSupport
end
def dump_to(filename)
- File.open(filename, 'wb') do |f|
+ File.open(filename, "wb") do |f|
f.write Marshal.dump([@ucd.codepoints, @ucd.composition_exclusion, @ucd.composition_map, @ucd.boundary, @ucd.cp1252])
end
end
diff --git a/activesupport/bin/test b/activesupport/bin/test
index 404cabba51..c53377cc97 100755
--- a/activesupport/bin/test
+++ b/activesupport/bin/test
@@ -1,4 +1,5 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
-require File.expand_path("../tools/test", COMPONENT_ROOT)
-exit Minitest.run(ARGV)
+# frozen_string_literal: true
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
+require_relative "../../tools/test"
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 11569add37..a4fb697669 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+
#--
-# Copyright (c) 2005-2016 David Heinemeier Hansson
+# Copyright (c) 2005-2018 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -21,7 +23,7 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-require 'securerandom'
+require "securerandom"
require "active_support/dependencies/autoload"
require "active_support/version"
require "active_support/logger"
@@ -32,6 +34,7 @@ module ActiveSupport
extend ActiveSupport::Autoload
autoload :Concern
+ autoload :CurrentAttributes
autoload :Dependencies
autoload :DescendantsTracker
autoload :ExecutionWrapper
@@ -50,6 +53,7 @@ module ActiveSupport
autoload :Callbacks
autoload :Configurable
autoload :Deprecation
+ autoload :Digest
autoload :Gzip
autoload :Inflector
autoload :JSON
@@ -79,14 +83,6 @@ module ActiveSupport
cattr_accessor :test_order # :nodoc:
- def self.halt_callback_chains_on_return_false
- Callbacks.halt_and_display_warning_on_return_false
- end
-
- def self.halt_callback_chains_on_return_false=(value)
- Callbacks.halt_and_display_warning_on_return_false = value
- end
-
def self.to_time_preserves_timezone
DateAndTime::Compatibility.preserve_timezone
end
diff --git a/activesupport/lib/active_support/all.rb b/activesupport/lib/active_support/all.rb
index f537818300..4adf446af8 100644
--- a/activesupport/lib/active_support/all.rb
+++ b/activesupport/lib/active_support/all.rb
@@ -1,3 +1,5 @@
-require 'active_support'
-require 'active_support/time'
-require 'active_support/core_ext'
+# frozen_string_literal: true
+
+require "active_support"
+require "active_support/time"
+require "active_support/core_ext"
diff --git a/activesupport/lib/active_support/array_inquirer.rb b/activesupport/lib/active_support/array_inquirer.rb
index f59ddf5403..b2b9e9c0b7 100644
--- a/activesupport/lib/active_support/array_inquirer.rb
+++ b/activesupport/lib/active_support/array_inquirer.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# Wrapping an array in an +ArrayInquirer+ gives a friendlier way to check
# its string-like contents:
@@ -9,8 +11,10 @@ module ActiveSupport
# variants.desktop? # => false
class ArrayInquirer < Array
# Passes each element of +candidates+ collection to ArrayInquirer collection.
- # The method returns true if at least one element is the same. If +candidates+
- # collection is not given, method returns true.
+ # The method returns true if any element from the ArrayInquirer collection
+ # is equal to the stringified or symbolized form of any element in the +candidates+ collection.
+ #
+ # If +candidates+ collection is not given, method returns true.
#
# variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
#
@@ -18,7 +22,7 @@ module ActiveSupport
# variants.any?(:phone, :tablet) # => true
# variants.any?('phone', 'desktop') # => true
# variants.any?(:desktop, :watch) # => false
- def any?(*candidates, &block)
+ def any?(*candidates)
if candidates.none?
super
else
@@ -30,11 +34,11 @@ module ActiveSupport
private
def respond_to_missing?(name, include_private = false)
- name[-1] == '?'
+ (name[-1] == "?") || super
end
def method_missing(name, *args)
- if name[-1] == '?'
+ if name[-1] == "?"
any?(name[0..-2])
else
super
diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb
index e161ec4cca..16dd733ddb 100644
--- a/activesupport/lib/active_support/backtrace_cleaner.rb
+++ b/activesupport/lib/active_support/backtrace_cleaner.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# Backtraces often include many lines that are not relevant for the context
# under review. This makes it hard to find the signal amongst the backtrace
@@ -12,9 +14,9 @@ module ActiveSupport
# is to exclude the output of a noisy library from the backtrace, so that you
# can focus on the rest.
#
- # bc = BacktraceCleaner.new
+ # bc = ActiveSupport::BacktraceCleaner.new
# bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix
- # bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
+ # bc.add_silencer { |line| line =~ /puma|rubygems/ } # skip any lines from puma or rubygems
# bc.clean(exception.backtrace) # perform the cleanup
#
# To reconfigure an existing BacktraceCleaner (like the default one in Rails)
@@ -59,8 +61,8 @@ module ActiveSupport
# Adds a silencer from the block provided. If the silencer returns +true+
# for a given line, it will be excluded from the clean backtrace.
#
- # # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
- # backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
+ # # Will reject all lines that include the word "puma", like "/gems/puma/server.rb" or "/app/my_puma_server/rb"
+ # backtrace_cleaner.add_silencer { |line| line =~ /puma/ }
def add_silencer(&block)
@silencers << block
end
diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb
index 3988b147ac..f481d68198 100644
--- a/activesupport/lib/active_support/benchmarkable.rb
+++ b/activesupport/lib/active_support/benchmarkable.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/benchmark'
-require 'active_support/core_ext/hash/keys'
+# frozen_string_literal: true
+
+require "active_support/core_ext/benchmark"
+require "active_support/core_ext/hash/keys"
module ActiveSupport
module Benchmarkable
@@ -39,7 +41,7 @@ module ActiveSupport
result = nil
ms = Benchmark.ms { result = options[:silence] ? logger.silence { yield } : yield }
- logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
+ logger.send(options[:level], "%s (%.1fms)" % [ message, ms ])
result
else
yield
diff --git a/activesupport/lib/active_support/builder.rb b/activesupport/lib/active_support/builder.rb
index 321e462acd..3fa7e6b26d 100644
--- a/activesupport/lib/active_support/builder.rb
+++ b/activesupport/lib/active_support/builder.rb
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+
begin
- require 'builder'
+ require "builder"
rescue LoadError => e
$stderr.puts "You don't have builder installed in your application. Please add it to your Gemfile and run bundle install"
raise e
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index bc114e0785..8301b8c7cb 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -1,29 +1,29 @@
-require 'benchmark'
-require 'zlib'
-require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/benchmark'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/numeric/bytes'
-require 'active_support/core_ext/numeric/time'
-require 'active_support/core_ext/object/to_param'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/core_ext/string/strip'
+# frozen_string_literal: true
+
+require "zlib"
+require "active_support/core_ext/array/extract_options"
+require "active_support/core_ext/array/wrap"
+require "active_support/core_ext/module/attribute_accessors"
+require "active_support/core_ext/numeric/bytes"
+require "active_support/core_ext/numeric/time"
+require "active_support/core_ext/object/to_param"
+require "active_support/core_ext/string/inflections"
module ActiveSupport
# See ActiveSupport::Cache::Store for documentation.
module Cache
- autoload :FileStore, 'active_support/cache/file_store'
- autoload :MemoryStore, 'active_support/cache/memory_store'
- autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
- autoload :NullStore, 'active_support/cache/null_store'
+ autoload :FileStore, "active_support/cache/file_store"
+ autoload :MemoryStore, "active_support/cache/memory_store"
+ autoload :MemCacheStore, "active_support/cache/mem_cache_store"
+ autoload :NullStore, "active_support/cache/null_store"
+ autoload :RedisCacheStore, "active_support/cache/redis_cache_store"
# These options mean something to all cache implementations. Individual cache
# implementations may support additional options.
UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
module Strategy
- autoload :LocalCache, 'active_support/cache/strategy/local_cache'
+ autoload :LocalCache, "active_support/cache/strategy/local_cache"
end
class << self
@@ -73,12 +73,12 @@ module ActiveSupport
# each of elements in the array will be turned into parameters/keys and
# concatenated into a single key. For example:
#
- # expand_cache_key([:foo, :bar]) # => "foo/bar"
- # expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
+ # ActiveSupport::Cache.expand_cache_key([:foo, :bar]) # => "foo/bar"
+ # ActiveSupport::Cache.expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
#
# The +key+ argument can also respond to +cache_key+ or +to_param+.
def expand_cache_key(key, namespace = nil)
- expanded_cache_key = namespace ? "#{namespace}/" : ""
+ expanded_cache_key = (namespace ? "#{namespace}/" : "").dup
if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
expanded_cache_key << "#{prefix}/"
@@ -91,16 +91,19 @@ module ActiveSupport
private
def retrieve_cache_key(key)
case
- when key.respond_to?(:cache_key) then key.cache_key
- when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
- when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
- else key.to_param
+ when key.respond_to?(:cache_key_with_version) then key.cache_key_with_version
+ when key.respond_to?(:cache_key) then key.cache_key
+ when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
+ when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
+ else key.to_param
end.to_s
end
# Obtains the specified cache store class, given the name of the +store+.
# Raises an error when the store class cannot be found.
def retrieve_store_class(store)
+ # require_relative cannot be used here because the class might be
+ # provided by another gem, like redis-activesupport for example.
require "active_support/cache/#{store}"
rescue LoadError => e
raise "Could not find cache store adapter for #{store} (#{e})"
@@ -146,14 +149,13 @@ module ActiveSupport
# cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
# @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
#
- # Caches can also store values in a compressed format to save space and
- # reduce time spent sending data. Since there is overhead, values must be
- # large enough to warrant compression. To turn on compression either pass
- # <tt>compress: true</tt> in the initializer or as an option to +fetch+
- # or +write+. To specify the threshold at which to compress values, set the
- # <tt>:compress_threshold</tt> option. The default threshold is 16K.
+ # Cached data larger than 1kB are compressed by default. To turn off
+ # compression, pass <tt>compress: false</tt> to the initializer or to
+ # individual +fetch+ or +write+ method calls. The 1kB compression
+ # threshold is configurable with the <tt>:compress_threshold</tt> option,
+ # specified in bytes.
class Store
- cattr_accessor :logger, :instance_writer => true
+ cattr_accessor :logger, instance_writer: true
attr_reader :silence, :options
alias :silence? :silence
@@ -200,18 +202,17 @@ module ActiveSupport
# You may also specify additional options via the +options+ argument.
# Setting <tt>force: true</tt> forces a cache "miss," meaning we treat
# the cache value as missing even if it's present. Passing a block is
- # required when `force` is true so this always results in a cache write.
+ # required when +force+ is true so this always results in a cache write.
#
# cache.write('today', 'Monday')
# cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday'
# cache.fetch('today', force: true) # => ArgumentError
#
- # The `:force` option is useful when you're calling some other method to
+ # The +:force+ option is useful when you're calling some other method to
# ask whether you should force a cache write. Otherwise, it's clearer to
- # just call `Cache#write`.
+ # just call <tt>Cache#write</tt>.
#
- # Setting <tt>:compress</tt> will store a large cache entry set by the call
- # in a compressed format.
+ # Setting <tt>compress: false</tt> disables compression of the cache entry.
#
# Setting <tt>:expires_in</tt> will set an expiration time on the cache.
# All caches support auto-expiring content after a specified number of
@@ -222,6 +223,10 @@ module ActiveSupport
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
# cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
#
+ # Setting <tt>:version</tt> verifies the cache stored under <tt>name</tt>
+ # is of the same version. nil is returned on mismatches despite contents.
+ # This feature is used to support recyclable cache keys.
+ #
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
# a cache entry is used very frequently and is under heavy load. If a
# cache expires and due to heavy load several different processes will try
@@ -250,14 +255,14 @@ module ActiveSupport
# sleep 60
#
# Thread.new do
- # val_1 = cache.fetch('foo', race_condition_ttl: 10) do
+ # val_1 = cache.fetch('foo', race_condition_ttl: 10.seconds) do
# sleep 1
# 'new value 1'
# end
# end
#
# Thread.new do
- # val_2 = cache.fetch('foo', race_condition_ttl: 10) do
+ # val_2 = cache.fetch('foo', race_condition_ttl: 10.seconds) do
# 'new value 2'
# end
# end
@@ -290,6 +295,7 @@ module ActiveSupport
instrument(:read, name, options) do |payload|
cached_entry = read_entry(key, options) unless options[:force]
entry = handle_expired_entry(cached_entry, key, options)
+ entry = nil if entry && entry.mismatched?(normalize_version(name, options))
payload[:super_operation] = :fetch if payload
payload[:hit] = !!entry if payload
end
@@ -300,27 +306,36 @@ module ActiveSupport
save_block_result_to_cache(name, options) { |_name| yield _name }
end
elsif options && options[:force]
- raise ArgumentError, 'Missing block: Calling `Cache#fetch` with `force: true` requires a block.'
+ raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block."
else
read(name, options)
end
end
- # Fetches data from the cache, using the given key. If there is data in
+ # Reads data from the cache, using the given key. If there is data in
# the cache with the given key, then that data is returned. Otherwise,
# +nil+ is returned.
#
+ # Note, if data was written with the <tt>:expires_in<tt> or <tt>:version</tt> options,
+ # both of these conditions are applied before the data is returned.
+ #
# Options are passed to the underlying cache implementation.
def read(name, options = nil)
options = merged_options(options)
- key = normalize_key(name, options)
+ key = normalize_key(name, options)
+ version = normalize_version(name, options)
+
instrument(:read, name, options) do |payload|
entry = read_entry(key, options)
+
if entry
if entry.expired?
delete_entry(key, options)
payload[:hit] = false if payload
nil
+ elsif entry.mismatched?(version)
+ payload[:hit] = false if payload
+ nil
else
payload[:hit] = true if payload
entry.value
@@ -344,11 +359,15 @@ module ActiveSupport
results = {}
names.each do |name|
- key = normalize_key(name, options)
- entry = read_entry(key, options)
+ key = normalize_key(name, options)
+ version = normalize_version(name, options)
+ entry = read_entry(key, options)
+
if entry
if entry.expired?
delete_entry(key, options)
+ elsif entry.mismatched?(version)
+ # Skip mismatched versions
else
results[name] = entry.value
end
@@ -357,10 +376,26 @@ module ActiveSupport
results
end
+ # Cache Storage API to write multiple values at once.
+ def write_multi(hash, options = nil)
+ options = merged_options(options)
+
+ instrument :write_multi, hash, options do |payload|
+ entries = hash.each_with_object({}) do |(name, value), memo|
+ memo[normalize_key(name, options)] = Entry.new(value, options.merge(version: normalize_version(name, options)))
+ end
+
+ write_multi_entries entries, options
+ end
+ end
+
# Fetches data from the cache, using the given keys. If there is data in
# the cache with the given keys, then that data is returned. Otherwise,
# the supplied block is called for each key for which there was no data,
# and the result will be written to the cache and returned.
+ # Therefore, you need to pass a block that returns the data to be written
+ # to the cache. If you do not want to write the cache when the cache is
+ # not found, use #read_multi.
#
# Options are passed to the underlying cache implementation.
#
@@ -374,16 +409,19 @@ module ActiveSupport
# # "unknown_key" => "Fallback value for key: unknown_key" }
#
def fetch_multi(*names)
+ raise ArgumentError, "Missing block: `Cache#fetch_multi` requires a block." unless block_given?
+
options = names.extract_options!
options = merged_options(options)
- results = read_multi(*names, options)
- names.each_with_object({}) do |name, memo|
- memo[name] = results.fetch(name) do
- value = yield name
- write(name, value, options)
- value
+ read_multi(*names, options).tap do |results|
+ writes = {}
+
+ (names - results.keys).each do |name|
+ results[name] = writes[name] = yield(name)
end
+
+ write_multi writes, options
end
end
@@ -394,7 +432,7 @@ module ActiveSupport
options = merged_options(options)
instrument(:write, name, options) do
- entry = Entry.new(value, options)
+ entry = Entry.new(value, options.merge(version: normalize_version(name, options)))
write_entry(normalize_key(name, options), entry, options)
end
end
@@ -418,7 +456,7 @@ module ActiveSupport
instrument(:exist?, name) do
entry = read_entry(normalize_key(name, options), options)
- (entry && !entry.expired?) || false
+ (entry && !entry.expired? && !entry.mismatched?(normalize_version(name, options))) || false
end
end
@@ -468,16 +506,16 @@ module ActiveSupport
raise NotImplementedError.new("#{self.class.name} does not support clear")
end
- protected
+ private
# Adds the namespace defined in the options to a pattern designed to
# match keys. Implementations that support delete_matched should call
# this method to translate a pattern that matches names into one that
# matches namespaced keys.
- def key_matcher(pattern, options)
+ def key_matcher(pattern, options) # :doc:
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
if prefix
source = pattern.source
- if source.start_with?('^')
+ if source.start_with?("^")
source = source[1, source.length]
else
source = ".*#{source[0, source.length]}"
@@ -490,25 +528,32 @@ module ActiveSupport
# Reads an entry from the cache implementation. Subclasses must implement
# this method.
- def read_entry(key, options) # :nodoc:
+ def read_entry(key, options)
raise NotImplementedError.new
end
# Writes an entry to the cache implementation. Subclasses must implement
# this method.
- def write_entry(key, entry, options) # :nodoc:
+ def write_entry(key, entry, options)
raise NotImplementedError.new
end
+ # Writes multiple entries to the cache implementation. Subclasses MAY
+ # implement this method.
+ def write_multi_entries(hash, options)
+ hash.each do |key, entry|
+ write_entry key, entry, options
+ end
+ end
+
# Deletes an entry from the cache implementation. Subclasses must
# implement this method.
- def delete_entry(key, options) # :nodoc:
+ def delete_entry(key, options)
raise NotImplementedError.new
end
- private
# Merges the default options with ones specific to a method call.
- def merged_options(call_options) # :nodoc:
+ def merged_options(call_options)
if call_options
options.merge(call_options)
else
@@ -516,50 +561,74 @@ module ActiveSupport
end
end
+ # Expands and namespaces the cache key. May be overridden by
+ # cache stores to do additional normalization.
+ def normalize_key(key, options = nil)
+ namespace_key expanded_key(key), options
+ end
+
+ # Prefix the key with a namespace string:
+ #
+ # namespace_key 'foo', namespace: 'cache'
+ # # => 'cache:foo'
+ #
+ # With a namespace block:
+ #
+ # namespace_key 'foo', namespace: -> { 'cache' }
+ # # => 'cache:foo'
+ def namespace_key(key, options = nil)
+ options = merged_options(options)
+ namespace = options[:namespace]
+
+ if namespace.respond_to?(:call)
+ namespace = namespace.call
+ end
+
+ if namespace
+ "#{namespace}:#{key}"
+ else
+ key
+ end
+ end
+
# Expands key to be a consistent string value. Invokes +cache_key+ if
# object responds to +cache_key+. Otherwise, +to_param+ method will be
# called. If the key is a Hash, then keys will be sorted alphabetically.
- def expanded_key(key) # :nodoc:
+ def expanded_key(key)
return key.cache_key.to_s if key.respond_to?(:cache_key)
case key
when Array
if key.size > 1
- key = key.collect{|element| expanded_key(element)}
+ key = key.collect { |element| expanded_key(element) }
else
key = key.first
end
when Hash
- key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
+ key = key.sort_by { |k, _| k.to_s }.collect { |k, v| "#{k}=#{v}" }
end
key.to_param
end
- # Prefixes a key with the namespace. Namespace and key will be delimited
- # with a colon.
- def normalize_key(key, options)
- key = expanded_key(key)
- namespace = options[:namespace] if options
- prefix = namespace.is_a?(Proc) ? namespace.call : namespace
- key = "#{prefix}:#{key}" if prefix
- key
+ def normalize_version(key, options = nil)
+ (options && options[:version].try(:to_param)) || expanded_version(key)
end
- def namespaced_key(*args)
- ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
- `namespaced_key` is deprecated and will be removed from Rails 5.1.
- Please use `normalize_key` which will return a fully resolved key.
- MESSAGE
- normalize_key(*args)
+ def expanded_version(key)
+ case
+ when key.respond_to?(:cache_version) then key.cache_version.to_param
+ when key.is_a?(Array) then key.map { |element| expanded_version(element) }.compact.to_param
+ when key.respond_to?(:to_a) then expanded_version(key.to_a)
+ end
end
def instrument(operation, key, options = nil)
log { "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" }
- payload = { :key => key }
+ payload = { key: key }
payload.merge!(options) if options.is_a?(Hash)
- ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
+ ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload) { yield(payload) }
end
def log
@@ -574,7 +643,7 @@ module ActiveSupport
# When an entry has a positive :race_condition_ttl defined, put the stale entry back into the cache
# for a brief period while the entry is being recalculated.
entry.expires_at = Time.now + race_ttl
- write_entry(key, entry, :expires_in => race_ttl * 2)
+ write_entry(key, entry, expires_in: race_ttl * 2)
else
delete_entry(key, options)
end
@@ -584,7 +653,7 @@ module ActiveSupport
end
def get_entry_value(entry, name, options)
- instrument(:fetch_hit, name, options) { }
+ instrument(:fetch_hit, name, options) {}
entry.value
end
@@ -598,14 +667,17 @@ module ActiveSupport
end
end
- # This class is used to represent cache entries. Cache entries have a value and an optional
- # expiration time. The expiration time is used to support the :race_condition_ttl option
- # on the cache.
+ # This class is used to represent cache entries. Cache entries have a value, an optional
+ # expiration time, and an optional version. The expiration time is used to support the :race_condition_ttl option
+ # on the cache. The version is used to support the :version option on the cache for rejecting
+ # mismatches.
#
# Since cache entries in most instances will be serialized, the internals of this class are highly optimized
# using short instance variable names that are lazily defined.
class Entry # :nodoc:
- DEFAULT_COMPRESS_LIMIT = 16.kilobytes
+ attr_reader :version
+
+ DEFAULT_COMPRESS_LIMIT = 1.kilobyte
# Creates a new cache entry for the specified value. Options supported are
# +:compress+, +:compress_threshold+, and +:expires_in+.
@@ -617,6 +689,7 @@ module ActiveSupport
@value = value
end
+ @version = options[:version]
@created_at = Time.now.to_f
@expires_in = options[:expires_in]
@expires_in = @expires_in.to_f if @expires_in
@@ -626,6 +699,10 @@ module ActiveSupport
compressed? ? uncompress(@value) : @value
end
+ def mismatched?(version)
+ @version && version && @version != version
+ end
+
# Checks if the entry is expired. The +expires_in+ parameter can override
# the value set when the entry was created.
def expired?
@@ -675,8 +752,8 @@ module ActiveSupport
private
def should_compress?(value, options)
- if value && options[:compress]
- compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
+ if value && options.fetch(:compress, true)
+ compress_threshold = options.fetch(:compress_threshold, DEFAULT_COMPRESS_LIMIT)
serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
return true if serialized_value_size >= compress_threshold
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 99c55b1aa4..a0f44aac0f 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -1,7 +1,9 @@
-require 'active_support/core_ext/marshal'
-require 'active_support/core_ext/file/atomic'
-require 'active_support/core_ext/string/conversions'
-require 'uri/common'
+# frozen_string_literal: true
+
+require "active_support/core_ext/marshal"
+require "active_support/core_ext/file/atomic"
+require "active_support/core_ext/string/conversions"
+require "uri/common"
module ActiveSupport
module Cache
@@ -16,8 +18,8 @@ module ActiveSupport
DIR_FORMATTER = "%03X"
FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
FILEPATH_MAX_SIZE = 900 # max is 1024, plus some room
- EXCLUDED_DIRS = ['.', '..'].freeze
- GITKEEP_FILES = ['.gitkeep', '.keep'].freeze
+ EXCLUDED_DIRS = [".", ".."].freeze
+ GITKEEP_FILES = [".gitkeep", ".keep"].freeze
def initialize(cache_path, options = nil)
super(options)
@@ -29,7 +31,7 @@ module ActiveSupport
# config file when using +FileStore+ because everything in that directory will be deleted.
def clear(options = nil)
root_dirs = exclude_from(cache_path, EXCLUDED_DIRS + GITKEEP_FILES)
- FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
+ FileUtils.rm_r(root_dirs.collect { |f| File.join(cache_path, f) })
rescue Errno::ENOENT
end
@@ -37,9 +39,8 @@ module ActiveSupport
def cleanup(options = nil)
options = merged_options(options)
search_dir(cache_path) do |fname|
- key = file_path_key(fname)
- entry = read_entry(key, options)
- delete_entry(key, options) if entry && entry.expired?
+ entry = read_entry(fname, options)
+ delete_entry(fname, options) if entry && entry.expired?
end
end
@@ -66,7 +67,7 @@ module ActiveSupport
end
end
- protected
+ private
def read_entry(key, options)
if File.exist?(key)
@@ -80,7 +81,7 @@ module ActiveSupport
def write_entry(key, entry, options)
return false if options[:unless_exist] && File.exist?(key)
ensure_cache_path(File.dirname(key))
- File.atomic_write(key, cache_path) {|f| Marshal.dump(entry, f)}
+ File.atomic_write(key, cache_path) { |f| Marshal.dump(entry, f) }
true
end
@@ -98,11 +99,10 @@ module ActiveSupport
end
end
- private
# Lock a file for a block so only one process can modify it at a time.
- def lock_file(file_name, &block) # :nodoc:
+ def lock_file(file_name, &block)
if File.exist?(file_name)
- File.open(file_name, 'r+') do |f|
+ File.open(file_name, "r+") do |f|
begin
f.flock File::LOCK_EX
yield
@@ -121,7 +121,7 @@ module ActiveSupport
fname = URI.encode_www_form_component(key)
if fname.size > FILEPATH_MAX_SIZE
- fname = Digest::MD5.hexdigest(key)
+ fname = ActiveSupport::Digest.hexdigest(key)
end
hash = Zlib.adler32(fname)
@@ -138,14 +138,6 @@ module ActiveSupport
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
end
- def key_file_path(key)
- ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
- `key_file_path` is deprecated and will be removed from Rails 5.1.
- Please use `normalize_key` which will return a fully resolved key or nothing.
- MESSAGE
- key
- end
-
# Translate a file path into a key.
def file_path_key(path)
fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index 2ca4b51efa..df8bc8e43e 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -1,18 +1,19 @@
+# frozen_string_literal: true
+
begin
- require 'dalli'
+ require "dalli"
rescue LoadError => e
$stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
-require 'digest/md5'
-require 'active_support/core_ext/marshal'
-require 'active_support/core_ext/array/extract_options'
+require "active_support/core_ext/marshal"
+require "active_support/core_ext/array/extract_options"
module ActiveSupport
module Cache
# A cache store implementation which stores data in Memcached:
- # http://memcached.org/
+ # https://memcached.org
#
# This is currently the most popular cache store for production websites.
#
@@ -26,24 +27,24 @@ module ActiveSupport
class MemCacheStore < Store
# Provide support for raw values in the local cache strategy.
module LocalCacheWithRaw # :nodoc:
- protected
- def read_entry(key, options)
- entry = super
- if options[:raw] && local_cache && entry
- entry = deserialize_entry(entry.value)
+ private
+ def read_entry(key, options)
+ entry = super
+ if options[:raw] && local_cache && entry
+ entry = deserialize_entry(entry.value)
+ end
+ entry
end
- entry
- end
- def write_entry(key, entry, options) # :nodoc:
- if options[:raw] && local_cache
- raw_entry = Entry.new(entry.value.to_s)
- raw_entry.expires_at = entry.expires_at
- super(key, raw_entry, options)
- else
- super
+ def write_entry(key, entry, options)
+ if options[:raw] && local_cache
+ raw_entry = Entry.new(entry.value.to_s)
+ raw_entry.expires_at = entry.expires_at
+ super(key, raw_entry, options)
+ else
+ super
+ end
end
- end
end
prepend Strategy::LocalCache
@@ -85,7 +86,7 @@ module ActiveSupport
@data = addresses.first
else
mem_cache_options = options.dup
- UNIVERSAL_OPTIONS.each{|name| mem_cache_options.delete(name)}
+ UNIVERSAL_OPTIONS.each { |name| mem_cache_options.delete(name) }
@data = self.class.build_mem_cache(*(addresses + [mem_cache_options]))
end
end
@@ -96,13 +97,19 @@ module ActiveSupport
options = names.extract_options!
options = merged_options(options)
- keys_to_names = Hash[names.map{|name| [normalize_key(name, options), name]}]
- raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
+ keys_to_names = Hash[names.map { |name| [normalize_key(name, options), name] }]
+
+ raw_values = @data.get_multi(keys_to_names.keys)
values = {}
+
raw_values.each do |key, value|
entry = deserialize_entry(value)
- values[keys_to_names[key]] = entry.value unless entry.expired?
+
+ unless entry.expired? || entry.mismatched?(normalize_version(keys_to_names[key], options))
+ values[keys_to_names[key]] = entry.value
+ end
end
+
values
end
@@ -110,11 +117,11 @@ module ActiveSupport
# operator and can only be used on values written with the :raw option.
# Calling it on a value not stored with :raw will initialize that value
# to zero.
- def increment(name, amount = 1, options = nil) # :nodoc:
+ def increment(name, amount = 1, options = nil)
options = merged_options(options)
- instrument(:increment, name, :amount => amount) do
+ instrument(:increment, name, amount: amount) do
rescue_error_with nil do
- @data.incr(normalize_key(name, options), amount)
+ @data.incr(normalize_key(name, options), amount, options[:expires_in])
end
end
end
@@ -123,11 +130,11 @@ module ActiveSupport
# operator and can only be used on values written with the :raw option.
# Calling it on a value not stored with :raw will initialize that value
# to zero.
- def decrement(name, amount = 1, options = nil) # :nodoc:
+ def decrement(name, amount = 1, options = nil)
options = merged_options(options)
- instrument(:decrement, name, :amount => amount) do
+ instrument(:decrement, name, amount: amount) do
rescue_error_with nil do
- @data.decr(normalize_key(name, options), amount)
+ @data.decr(normalize_key(name, options), amount, options[:expires_in])
end
end
end
@@ -143,14 +150,14 @@ module ActiveSupport
@data.stats
end
- protected
+ private
# Read an entry from the cache.
- def read_entry(key, options) # :nodoc:
+ def read_entry(key, options)
rescue_error_with(nil) { deserialize_entry(@data.get(key, options)) }
end
# Write an entry to the cache.
- def write_entry(key, entry, options) # :nodoc:
+ def write_entry(key, entry, options)
method = options && options[:unless_exist] ? :add : :set
value = options[:raw] ? entry.value.to_s : entry
expires_in = options[:expires_in].to_i
@@ -164,28 +171,18 @@ module ActiveSupport
end
# Delete an entry from the cache.
- def delete_entry(key, options) # :nodoc:
+ def delete_entry(key, options)
rescue_error_with(false) { @data.delete(key) }
end
- private
-
# Memcache keys are binaries. So we need to force their encoding to binary
# before applying the regular expression to ensure we are escaping all
# characters properly.
def normalize_key(key, options)
key = super.dup
key = key.force_encoding(Encoding::ASCII_8BIT)
- key = key.gsub(ESCAPE_KEY_CHARS){ |match| "%#{match.getbyte(0).to_s(16).upcase}" }
- key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
- key
- end
-
- def escape_key(key)
- ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
- `escape_key` is deprecated and will be removed from Rails 5.1.
- Please use `normalize_key` which will return a fully resolved key or nothing.
- MESSAGE
+ key = key.gsub(ESCAPE_KEY_CHARS) { |match| "%#{match.getbyte(0).to_s(16).upcase}" }
+ key = "#{key[0, 213]}:md5:#{ActiveSupport::Digest.hexdigest(key)}" if key.size > 250
key
end
diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb
index 896c28ad8b..564ac17241 100644
--- a/activesupport/lib/active_support/cache/memory_store.rb
+++ b/activesupport/lib/active_support/cache/memory_store.rb
@@ -1,10 +1,12 @@
-require 'monitor'
+# frozen_string_literal: true
+
+require "monitor"
module ActiveSupport
module Cache
# A cache store implementation which stores everything into memory in the
# same process. If you're running multiple Ruby on Rails server processes
- # (which is the case if you're using mongrel_cluster or Phusion Passenger),
+ # (which is the case if you're using Phusion Passenger or puma clustered mode),
# then this means that Rails server process instances won't be able
# to share cache data with each other and this may not be the most
# appropriate cache in that scenario.
@@ -28,6 +30,7 @@ module ActiveSupport
@pruning = false
end
+ # Delete all data stored in a given cache store.
def clear(options = nil)
synchronize do
@data.clear
@@ -39,8 +42,8 @@ module ActiveSupport
# Preemptively iterates through all stored keys and removes the ones which have expired.
def cleanup(options = nil)
options = merged_options(options)
- instrument(:cleanup, :size => @data.size) do
- keys = synchronize{ @data.keys }
+ instrument(:cleanup, size: @data.size) do
+ keys = synchronize { @data.keys }
keys.each do |key|
entry = @data[key]
delete_entry(key, options) if entry && entry.expired?
@@ -56,8 +59,8 @@ module ActiveSupport
begin
start_time = Time.now
cleanup
- instrument(:prune, target_size, :from => @cache_size) do
- keys = synchronize{ @key_access.keys.sort{|a,b| @key_access[a].to_f <=> @key_access[b].to_f} }
+ instrument(:prune, target_size, from: @cache_size) do
+ keys = synchronize { @key_access.keys.sort { |a, b| @key_access[a].to_f <=> @key_access[b].to_f } }
keys.each do |key|
delete_entry(key, options)
return if @cache_size <= target_size || (max_time && Time.now - start_time > max_time)
@@ -83,6 +86,7 @@ module ActiveSupport
modify_value(name, -amount, options)
end
+ # Deletes cache entries if the cache key matches a given pattern.
def delete_matched(matcher, options = nil)
options = merged_options(options)
instrument(:delete_matched, matcher.inspect) do
@@ -104,15 +108,15 @@ module ActiveSupport
@monitor.synchronize(&block)
end
- protected
+ private
PER_ENTRY_OVERHEAD = 240
- def cached_size(key, entry) # :nodoc:
+ def cached_size(key, entry)
key.to_s.bytesize + entry.size + PER_ENTRY_OVERHEAD
end
- def read_entry(key, options) # :nodoc:
+ def read_entry(key, options)
entry = @data[key]
synchronize do
if entry
@@ -124,7 +128,7 @@ module ActiveSupport
entry
end
- def write_entry(key, entry, options) # :nodoc:
+ def write_entry(key, entry, options)
entry.dup_value!
synchronize do
old_entry = @data[key]
@@ -141,7 +145,7 @@ module ActiveSupport
end
end
- def delete_entry(key, options) # :nodoc:
+ def delete_entry(key, options)
synchronize do
@key_access.delete(key)
entry = @data.delete(key)
@@ -150,8 +154,6 @@ module ActiveSupport
end
end
- private
-
def modify_value(name, amount, options)
synchronize do
options = merged_options(options)
diff --git a/activesupport/lib/active_support/cache/null_store.rb b/activesupport/lib/active_support/cache/null_store.rb
index 0564ce5312..1a5983db43 100644
--- a/activesupport/lib/active_support/cache/null_store.rb
+++ b/activesupport/lib/active_support/cache/null_store.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Cache
# A cache store implementation which doesn't actually store anything. Useful in
@@ -25,15 +27,15 @@ module ActiveSupport
def delete_matched(matcher, options = nil)
end
- protected
- def read_entry(key, options) # :nodoc:
+ private
+ def read_entry(key, options)
end
- def write_entry(key, entry, options) # :nodoc:
+ def write_entry(key, entry, options)
true
end
- def delete_entry(key, options) # :nodoc:
+ def delete_entry(key, options)
false
end
end
diff --git a/activesupport/lib/active_support/cache/redis_cache_store.rb b/activesupport/lib/active_support/cache/redis_cache_store.rb
new file mode 100644
index 0000000000..6cc45f5284
--- /dev/null
+++ b/activesupport/lib/active_support/cache/redis_cache_store.rb
@@ -0,0 +1,406 @@
+# frozen_string_literal: true
+
+begin
+ gem "redis", ">= 4.0.1"
+ require "redis"
+ require "redis/distributed"
+rescue LoadError
+ warn "The Redis cache store requires the redis gem, version 4.0.1 or later. Please add it to your Gemfile: `gem \"redis\", \"~> 4.0\"`"
+ raise
+end
+
+# Prefer the hiredis driver but don't require it.
+begin
+ require "redis/connection/hiredis"
+rescue LoadError
+end
+
+require "digest/sha2"
+require "active_support/core_ext/marshal"
+
+module ActiveSupport
+ module Cache
+ # Redis cache store.
+ #
+ # Deployment note: Take care to use a *dedicated Redis cache* rather
+ # than pointing this at your existing Redis server. It won't cope well
+ # with mixed usage patterns and it won't expire cache entries by default.
+ #
+ # Redis cache server setup guide: https://redis.io/topics/lru-cache
+ #
+ # * Supports vanilla Redis, hiredis, and Redis::Distributed.
+ # * Supports Memcached-like sharding across Redises with Redis::Distributed.
+ # * Fault tolerant. If the Redis server is unavailable, no exceptions are
+ # raised. Cache fetches are all misses and writes are dropped.
+ # * Local cache. Hot in-memory primary cache within block/middleware scope.
+ # * +read_multi+ and +write_multi+ support for Redis mget/mset. Use Redis::Distributed
+ # 4.0.1+ for distributed mget support.
+ # * +delete_matched+ support for Redis KEYS globs.
+ class RedisCacheStore < Store
+ # Keys are truncated with their own SHA2 digest if they exceed 1kB
+ MAX_KEY_BYTESIZE = 1024
+
+ DEFAULT_REDIS_OPTIONS = {
+ connect_timeout: 20,
+ read_timeout: 1,
+ write_timeout: 1,
+ reconnect_attempts: 0,
+ }
+
+ DEFAULT_ERROR_HANDLER = -> (method:, returning:, exception:) do
+ if logger
+ logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.message}" }
+ end
+ end
+
+ DELETE_GLOB_LUA = "for i, name in ipairs(redis.call('KEYS', ARGV[1])) do redis.call('DEL', name); end"
+ private_constant :DELETE_GLOB_LUA
+
+ # Support raw values in the local cache strategy.
+ module LocalCacheWithRaw # :nodoc:
+ private
+ def read_entry(key, options)
+ entry = super
+ if options[:raw] && local_cache && entry
+ entry = deserialize_entry(entry.value)
+ end
+ entry
+ end
+
+ def write_entry(key, entry, options)
+ if options[:raw] && local_cache
+ raw_entry = Entry.new(entry.value.to_s)
+ raw_entry.expires_at = entry.expires_at
+ super(key, raw_entry, options)
+ else
+ super
+ end
+ end
+
+ def write_multi_entries(entries, options)
+ if options[:raw] && local_cache
+ raw_entries = entries.map do |key, entry|
+ raw_entry = Entry.new(entry.value.to_s)
+ raw_entry.expires_at = entry.expires_at
+ end.to_h
+
+ super(raw_entries, options)
+ else
+ super
+ end
+ end
+ end
+
+ prepend Strategy::LocalCache
+ prepend LocalCacheWithRaw
+
+ class << self
+ # Factory method to create a new Redis instance.
+ #
+ # Handles four options: :redis block, :redis instance, single :url
+ # string, and multiple :url strings.
+ #
+ # Option Class Result
+ # :redis Proc -> options[:redis].call
+ # :redis Object -> options[:redis]
+ # :url String -> Redis.new(url: …)
+ # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …])
+ #
+ def build_redis(redis: nil, url: nil, **redis_options) #:nodoc:
+ urls = Array(url)
+
+ if redis.respond_to?(:call)
+ redis.call
+ elsif redis
+ redis
+ elsif urls.size > 1
+ build_redis_distributed_client urls: urls, **redis_options
+ else
+ build_redis_client url: urls.first, **redis_options
+ end
+ end
+
+ private
+ def build_redis_distributed_client(urls:, **redis_options)
+ ::Redis::Distributed.new([], DEFAULT_REDIS_OPTIONS.merge(redis_options)).tap do |dist|
+ urls.each { |u| dist.add_node url: u }
+ end
+ end
+
+ def build_redis_client(url:, **redis_options)
+ ::Redis.new DEFAULT_REDIS_OPTIONS.merge(redis_options.merge(url: url))
+ end
+ end
+
+ attr_reader :redis_options
+ attr_reader :max_key_bytesize
+
+ # Creates a new Redis cache store.
+ #
+ # Handles three options: block provided to instantiate, single URL
+ # provided, and multiple URLs provided.
+ #
+ # :redis Proc -> options[:redis].call
+ # :url String -> Redis.new(url: …)
+ # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …])
+ #
+ # No namespace is set by default. Provide one if the Redis cache
+ # server is shared with other apps: <tt>namespace: 'myapp-cache'<tt>.
+ #
+ # Compression is enabled by default with a 1kB threshold, so cached
+ # values larger than 1kB are automatically compressed. Disable by
+ # passing <tt>cache: false</tt> or change the threshold by passing
+ # <tt>compress_threshold: 4.kilobytes</tt>.
+ #
+ # No expiry is set on cache entries by default. Redis is expected to
+ # be configured with an eviction policy that automatically deletes
+ # least-recently or -frequently used keys when it reaches max memory.
+ # See https://redis.io/topics/lru-cache for cache server setup.
+ #
+ # Race condition TTL is not set by default. This can be used to avoid
+ # "thundering herd" cache writes when hot cache entries are expired.
+ # See <tt>ActiveSupport::Cache::Store#fetch</tt> for more.
+ def initialize(namespace: nil, compress: true, compress_threshold: 1.kilobyte, expires_in: nil, race_condition_ttl: nil, error_handler: DEFAULT_ERROR_HANDLER, **redis_options)
+ @redis_options = redis_options
+
+ @max_key_bytesize = MAX_KEY_BYTESIZE
+ @error_handler = error_handler
+
+ super namespace: namespace,
+ compress: compress, compress_threshold: compress_threshold,
+ expires_in: expires_in, race_condition_ttl: race_condition_ttl
+ end
+
+ def redis
+ @redis ||= self.class.build_redis(**redis_options)
+ end
+
+ def inspect
+ instance = @redis || @redis_options
+ "<##{self.class} options=#{options.inspect} redis=#{instance.inspect}>"
+ end
+
+ # Cache Store API implementation.
+ #
+ # Read multiple values at once. Returns a hash of requested keys ->
+ # fetched values.
+ def read_multi(*names)
+ if mget_capable?
+ read_multi_mget(*names)
+ else
+ super
+ end
+ end
+
+ # Cache Store API implementation.
+ #
+ # Supports Redis KEYS glob patterns:
+ #
+ # h?llo matches hello, hallo and hxllo
+ # h*llo matches hllo and heeeello
+ # h[ae]llo matches hello and hallo, but not hillo
+ # h[^e]llo matches hallo, hbllo, ... but not hello
+ # h[a-b]llo matches hallo and hbllo
+ #
+ # Use \ to escape special characters if you want to match them verbatim.
+ #
+ # See https://redis.io/commands/KEYS for more.
+ #
+ # Failsafe: Raises errors.
+ def delete_matched(matcher, options = nil)
+ instrument :delete_matched, matcher do
+ case matcher
+ when String
+ redis.eval DELETE_GLOB_LUA, [], [namespace_key(matcher, options)]
+ else
+ raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}"
+ end
+ end
+ end
+
+ # Cache Store API implementation.
+ #
+ # Increment a cached value. This method uses the Redis incr atomic
+ # operator and can only be used on values written with the :raw option.
+ # Calling it on a value not stored with :raw will initialize that value
+ # to zero.
+ #
+ # Failsafe: Raises errors.
+ def increment(name, amount = 1, options = nil)
+ instrument :increment, name, amount: amount do
+ redis.incrby normalize_key(name, options), amount
+ end
+ end
+
+ # Cache Store API implementation.
+ #
+ # Decrement a cached value. This method uses the Redis decr atomic
+ # operator and can only be used on values written with the :raw option.
+ # Calling it on a value not stored with :raw will initialize that value
+ # to zero.
+ #
+ # Failsafe: Raises errors.
+ def decrement(name, amount = 1, options = nil)
+ instrument :decrement, name, amount: amount do
+ redis.decrby normalize_key(name, options), amount
+ end
+ end
+
+ # Cache Store API implementation.
+ #
+ # Removes expired entries. Handled natively by Redis least-recently-/
+ # least-frequently-used expiry, so manual cleanup is not supported.
+ def cleanup(options = nil)
+ super
+ end
+
+ # Clear the entire cache on all Redis servers. Safe to use on
+ # shared servers if the cache is namespaced.
+ #
+ # Failsafe: Raises errors.
+ def clear(options = nil)
+ failsafe :clear do
+ if namespace = merged_options(options)[namespace]
+ delete_matched "*", namespace: namespace
+ else
+ redis.flushdb
+ end
+ end
+ end
+
+ def mget_capable? #:nodoc:
+ set_redis_capabilities unless defined? @mget_capable
+ @mget_capable
+ end
+
+ def mset_capable? #:nodoc:
+ set_redis_capabilities unless defined? @mset_capable
+ @mset_capable
+ end
+
+ private
+ def set_redis_capabilities
+ case redis
+ when Redis::Distributed
+ @mget_capable = true
+ @mset_capable = false
+ else
+ @mget_capable = true
+ @mset_capable = true
+ end
+ end
+
+ # Store provider interface:
+ # Read an entry from the cache.
+ def read_entry(key, options = nil)
+ failsafe :read_entry do
+ deserialize_entry redis.get(key)
+ end
+ end
+
+ def read_multi_mget(*names)
+ options = names.extract_options!
+ options = merged_options(options)
+
+ keys = names.map { |name| normalize_key(name, options) }
+ values = redis.mget(*keys)
+
+ names.zip(values).each_with_object({}) do |(name, value), results|
+ if value
+ entry = deserialize_entry(value)
+ unless entry.nil? || entry.expired? || entry.mismatched?(normalize_version(name, options))
+ results[name] = entry.value
+ end
+ end
+ end
+ end
+
+ # Write an entry to the cache.
+ #
+ # Requires Redis 2.6.12+ for extended SET options.
+ def write_entry(key, entry, unless_exist: false, raw: false, expires_in: nil, race_condition_ttl: nil, **options)
+ value = raw ? entry.value.to_s : serialize_entry(entry)
+
+ # If race condition TTL is in use, ensure that cache entries
+ # stick around a bit longer after they would have expired
+ # so we can purposefully serve stale entries.
+ if race_condition_ttl && expires_in && expires_in > 0 && !raw
+ expires_in += 5.minutes
+ end
+
+ failsafe :write_entry do
+ if unless_exist || expires_in
+ modifiers = {}
+ modifiers[:nx] = unless_exist
+ modifiers[:px] = (1000 * expires_in.to_f).ceil if expires_in
+
+ redis.set key, value, modifiers
+ else
+ redis.set key, value
+ end
+ end
+ end
+
+ # Delete an entry from the cache.
+ def delete_entry(key, options)
+ failsafe :delete_entry, returning: false do
+ redis.del key
+ end
+ end
+
+ # Nonstandard store provider API to write multiple values at once.
+ def write_multi_entries(entries, expires_in: nil, **options)
+ if entries.any?
+ if mset_capable? && expires_in.nil?
+ failsafe :write_multi_entries do
+ redis.mapped_mset(entries)
+ end
+ else
+ super
+ end
+ end
+ end
+
+ # Truncate keys that exceed 1kB.
+ def normalize_key(key, options)
+ truncate_key super
+ end
+
+ def truncate_key(key)
+ if key.bytesize > max_key_bytesize
+ suffix = ":sha2:#{Digest::SHA2.hexdigest(key)}"
+ truncate_at = max_key_bytesize - suffix.bytesize
+ "#{key.byteslice(0, truncate_at)}#{suffix}"
+ else
+ key
+ end
+ end
+
+ def deserialize_entry(raw_value)
+ if raw_value
+ entry = Marshal.load(raw_value) rescue raw_value
+ entry.is_a?(Entry) ? entry : Entry.new(entry)
+ end
+ end
+
+ def serialize_entry(entry)
+ Marshal.dump(entry)
+ end
+
+ def failsafe(method, returning: nil)
+ yield
+ rescue ::Redis::BaseConnectionError => e
+ handle_exception exception: e, method: method, returning: returning
+ returning
+ end
+
+ def handle_exception(exception:, method:, returning:)
+ if @error_handler
+ @error_handler.(method: method, exception: exception, returning: returning)
+ end
+ rescue => failsafe
+ warn "RedisCacheStore ignored exception in handle_exception: #{failsafe.class}: #{failsafe.message}\n #{failsafe.backtrace.join("\n ")}"
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index 1c678dc2af..aaa9638fa8 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -1,6 +1,8 @@
-require 'active_support/core_ext/object/duplicable'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/per_thread_registry'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/duplicable"
+require "active_support/core_ext/string/inflections"
+require "active_support/per_thread_registry"
module ActiveSupport
module Cache
@@ -9,7 +11,7 @@ module ActiveSupport
# duration of a block. Repeated calls to the cache for the same key will hit the
# in-memory cache for faster access.
module LocalCache
- autoload :Middleware, 'active_support/cache/strategy/local_cache_middleware'
+ autoload :Middleware, "active_support/cache/strategy/local_cache_middleware"
# Class for storing and registering the local caches.
class LocalCacheRegistry # :nodoc:
@@ -70,6 +72,7 @@ module ActiveSupport
def with_local_cache
use_temporary_local_cache(LocalStore.new) { yield }
end
+
# Middleware class can be inserted as a Rack handler to be local cache for the
# duration of request.
def middleware
@@ -86,26 +89,26 @@ module ActiveSupport
def cleanup(options = nil) # :nodoc:
return super unless cache = local_cache
- cache.clear(options)
+ cache.clear
super
end
def increment(name, amount = 1, options = nil) # :nodoc:
return super unless local_cache
- value = bypass_local_cache{super}
+ value = bypass_local_cache { super }
write_cache_value(name, value, options)
value
end
def decrement(name, amount = 1, options = nil) # :nodoc:
return super unless local_cache
- value = bypass_local_cache{super}
+ value = bypass_local_cache { super }
write_cache_value(name, value, options)
value
end
- protected
- def read_entry(key, options) # :nodoc:
+ private
+ def read_entry(key, options)
if cache = local_cache
cache.fetch_entry(key) { super }
else
@@ -113,25 +116,22 @@ module ActiveSupport
end
end
- def write_entry(key, entry, options) # :nodoc:
- local_cache.write_entry(key, entry, options) if local_cache
+ def write_entry(key, entry, options)
+ if options[:unless_exist]
+ local_cache.delete_entry(key, options) if local_cache
+ else
+ local_cache.write_entry(key, entry, options) if local_cache
+ end
+
super
end
- def delete_entry(key, options) # :nodoc:
+ def delete_entry(key, options)
local_cache.delete_entry(key, options) if local_cache
super
end
- def set_cache_value(value, name, amount, options) # :nodoc:
- ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
- `set_cache_value` is deprecated and will be removed from Rails 5.1.
- Please use `write_cache_value` instead.
- MESSAGE
- write_cache_value name, value, options
- end
-
- def write_cache_value(name, value, options) # :nodoc:
+ def write_cache_value(name, value, options)
name = normalize_key(name, options)
cache = local_cache
cache.mute do
@@ -143,10 +143,8 @@ module ActiveSupport
end
end
- private
-
def local_cache_key
- @local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
+ @local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, "_").to_sym
end
def local_cache
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb b/activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb
index a6f24b1a3c..62542bdb22 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb
@@ -1,11 +1,12 @@
-require 'rack/body_proxy'
-require 'rack/utils'
+# frozen_string_literal: true
+
+require "rack/body_proxy"
+require "rack/utils"
module ActiveSupport
module Cache
module Strategy
module LocalCache
-
#--
# This class wraps up local storage for middlewares. Only the middleware method should
# construct them.
@@ -13,9 +14,9 @@ module ActiveSupport
attr_reader :name, :local_cache_key
def initialize(name, local_cache_key)
- @name = name
+ @name = name
@local_cache_key = local_cache_key
- @app = nil
+ @app = nil
end
def new(app)
@@ -29,13 +30,13 @@ module ActiveSupport
response[2] = ::Rack::BodyProxy.new(response[2]) do
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
end
+ cleanup_on_body_close = true
response
rescue Rack::Utils::InvalidParameterError
- LocalCacheRegistry.set_cache_for(local_cache_key, nil)
[400, {}, []]
- rescue Exception
- LocalCacheRegistry.set_cache_for(local_cache_key, nil)
- raise
+ ensure
+ LocalCacheRegistry.set_cache_for(local_cache_key, nil) unless
+ cleanup_on_body_close
end
end
end
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 904d3f0eb0..0ed4681b7d 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -1,13 +1,14 @@
-require 'active_support/concern'
-require 'active_support/descendants_tracker'
-require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/kernel/reporting'
-require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/string/filters'
-require 'active_support/deprecation'
-require 'thread'
+# frozen_string_literal: true
+
+require "active_support/concern"
+require "active_support/descendants_tracker"
+require "active_support/core_ext/array/extract_options"
+require "active_support/core_ext/class/attribute"
+require "active_support/core_ext/kernel/reporting"
+require "active_support/core_ext/kernel/singleton_class"
+require "active_support/core_ext/string/filters"
+require "active_support/deprecation"
+require "thread"
module ActiveSupport
# Callbacks are code hooks that are run at key points in an object's life cycle.
@@ -63,16 +64,11 @@ module ActiveSupport
included do
extend ActiveSupport::DescendantsTracker
+ class_attribute :__callbacks, instance_writer: false, default: {}
end
CALLBACK_FILTER_TYPES = [:before, :after, :around]
- # If true, Active Record and Active Model callbacks returning +false+ will
- # halt the entire callback chain and display a deprecation message.
- # If false, callback chains will only be halted by calling +throw :abort+.
- # Defaults to +true+.
- mattr_accessor(:halt_and_display_warning_on_return_false, instance_writer: false) { true }
-
# Runs the callbacks for the given event.
#
# Calls the before and around callbacks in the order they were set, yields
@@ -86,706 +82,764 @@ module ActiveSupport
# run_callbacks :save do
# save
# end
- def run_callbacks(kind, &block)
- send "_run_#{kind}_callbacks", &block
- end
-
- private
+ #
+ #--
+ #
+ # As this method is used in many places, and often wraps large portions of
+ # user code, it has an additional design goal of minimizing its impact on
+ # the visible call stack. An exception from inside a :before or :after
+ # callback can be as noisy as it likes -- but when control has passed
+ # smoothly through and into the supplied block, we want as little evidence
+ # as possible that we were here.
+ def run_callbacks(kind)
+ callbacks = __callbacks[kind.to_sym]
- def __run_callbacks__(callbacks, &block)
if callbacks.empty?
yield if block_given?
else
- runner = callbacks.compile
- e = Filters::Environment.new(self, false, nil, block)
- runner.call(e).value
- end
- end
-
- # A hook invoked every time a before callback is halted.
- # This can be overridden in AS::Callback implementors in order
- # to provide better debugging/logging.
- def halted_callback_hook(filter)
- end
+ env = Filters::Environment.new(self, false, nil)
+ next_sequence = callbacks.compile
+
+ invoke_sequence = Proc.new do
+ skipped = nil
+ while true
+ current = next_sequence
+ current.invoke_before(env)
+ if current.final?
+ env.value = !env.halted && (!block_given? || yield)
+ elsif current.skip?(env)
+ (skipped ||= []) << current
+ next_sequence = next_sequence.nested
+ next
+ else
+ next_sequence = next_sequence.nested
+ begin
+ target, block, method, *arguments = current.expand_call_template(env, invoke_sequence)
+ target.send(method, *arguments, &block)
+ ensure
+ next_sequence = current
+ end
+ end
+ current.invoke_after(env)
+ skipped.pop.invoke_after(env) while skipped && skipped.first
+ break env.value
+ end
+ end
- module Conditionals # :nodoc:
- class Value
- def initialize(&block)
- @block = block
+ # Common case: no 'around' callbacks defined
+ if next_sequence.final?
+ next_sequence.invoke_before(env)
+ env.value = !env.halted && (!block_given? || yield)
+ next_sequence.invoke_after(env)
+ env.value
+ else
+ invoke_sequence.call
end
- def call(target, value); @block.call(value); end
end
end
- module Filters
- Environment = Struct.new(:target, :halted, :value, :run_block)
+ private
- class End
- def call(env)
- block = env.run_block
- env.value = !env.halted && (!block || block.call)
- env
- end
+ # A hook invoked every time a before callback is halted.
+ # This can be overridden in ActiveSupport::Callbacks implementors in order
+ # to provide better debugging/logging.
+ def halted_callback_hook(filter)
end
- ENDING = End.new
- class Before
- def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter)
- halted_lambda = chain_config[:terminator]
-
- if user_conditions.any?
- halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
- else
- halting(callback_sequence, user_callback, halted_lambda, filter)
+ module Conditionals # :nodoc:
+ class Value
+ def initialize(&block)
+ @block = block
end
+ def call(target, value); @block.call(value); end
end
+ end
- def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
- callback_sequence.before do |env|
- target = env.target
- value = env.value
- halted = env.halted
+ module Filters
+ Environment = Struct.new(:target, :halted, :value)
- if !halted && user_conditions.all? { |c| c.call(target, value) }
- result_lambda = -> { user_callback.call target, value }
- env.halted = halted_lambda.call(target, result_lambda)
- if env.halted
- target.send :halted_callback_hook, filter
- end
+ class Before
+ def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter)
+ halted_lambda = chain_config[:terminator]
+
+ if user_conditions.any?
+ halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
+ else
+ halting(callback_sequence, user_callback, halted_lambda, filter)
end
+ end
- env
+ def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
+ callback_sequence.before do |env|
+ target = env.target
+ value = env.value
+ halted = env.halted
+
+ if !halted && user_conditions.all? { |c| c.call(target, value) }
+ result_lambda = -> { user_callback.call target, value }
+ env.halted = halted_lambda.call(target, result_lambda)
+ if env.halted
+ target.send :halted_callback_hook, filter
+ end
+ end
+
+ env
+ end
end
- end
- private_class_method :halting_and_conditional
+ private_class_method :halting_and_conditional
- def self.halting(callback_sequence, user_callback, halted_lambda, filter)
- callback_sequence.before do |env|
- target = env.target
- value = env.value
- halted = env.halted
+ def self.halting(callback_sequence, user_callback, halted_lambda, filter)
+ callback_sequence.before do |env|
+ target = env.target
+ value = env.value
+ halted = env.halted
- unless halted
- result_lambda = -> { user_callback.call target, value }
- env.halted = halted_lambda.call(target, result_lambda)
+ unless halted
+ result_lambda = -> { user_callback.call target, value }
+ env.halted = halted_lambda.call(target, result_lambda)
- if env.halted
- target.send :halted_callback_hook, filter
+ if env.halted
+ target.send :halted_callback_hook, filter
+ end
end
- end
- env
+ env
+ end
end
+ private_class_method :halting
end
- private_class_method :halting
- end
- class After
- def self.build(callback_sequence, user_callback, user_conditions, chain_config)
- if chain_config[:skip_after_callbacks_if_terminated]
- if user_conditions.any?
- halting_and_conditional(callback_sequence, user_callback, user_conditions)
+ class After
+ def self.build(callback_sequence, user_callback, user_conditions, chain_config)
+ if chain_config[:skip_after_callbacks_if_terminated]
+ if user_conditions.any?
+ halting_and_conditional(callback_sequence, user_callback, user_conditions)
+ else
+ halting(callback_sequence, user_callback)
+ end
else
- halting(callback_sequence, user_callback)
+ if user_conditions.any?
+ conditional callback_sequence, user_callback, user_conditions
+ else
+ simple callback_sequence, user_callback
+ end
end
- else
- if user_conditions.any?
- conditional callback_sequence, user_callback, user_conditions
- else
- simple callback_sequence, user_callback
+ end
+
+ def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
+ callback_sequence.after do |env|
+ target = env.target
+ value = env.value
+ halted = env.halted
+
+ if !halted && user_conditions.all? { |c| c.call(target, value) }
+ user_callback.call target, value
+ end
+
+ env
end
end
- end
+ private_class_method :halting_and_conditional
- def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
- callback_sequence.after do |env|
- target = env.target
- value = env.value
- halted = env.halted
+ def self.halting(callback_sequence, user_callback)
+ callback_sequence.after do |env|
+ unless env.halted
+ user_callback.call env.target, env.value
+ end
- if !halted && user_conditions.all? { |c| c.call(target, value) }
- user_callback.call target, value
+ env
end
+ end
+ private_class_method :halting
+
+ def self.conditional(callback_sequence, user_callback, user_conditions)
+ callback_sequence.after do |env|
+ target = env.target
+ value = env.value
- env
+ if user_conditions.all? { |c| c.call(target, value) }
+ user_callback.call target, value
+ end
+
+ env
+ end
end
- end
- private_class_method :halting_and_conditional
+ private_class_method :conditional
- def self.halting(callback_sequence, user_callback)
- callback_sequence.after do |env|
- unless env.halted
+ def self.simple(callback_sequence, user_callback)
+ callback_sequence.after do |env|
user_callback.call env.target, env.value
+
+ env
end
+ end
+ private_class_method :simple
+ end
+ end
- env
+ class Callback #:nodoc:#
+ def self.build(chain, filter, kind, options)
+ if filter.is_a?(String)
+ raise ArgumentError, <<-MSG.squish
+ Passing string to define a callback is not supported. See the `.set_callback`
+ documentation to see supported values.
+ MSG
end
+
+ new chain.name, filter, kind, options, chain.config
end
- private_class_method :halting
- def self.conditional(callback_sequence, user_callback, user_conditions)
- callback_sequence.after do |env|
- target = env.target
- value = env.value
+ attr_accessor :kind, :name
+ attr_reader :chain_config
+
+ def initialize(name, filter, kind, options, chain_config)
+ @chain_config = chain_config
+ @name = name
+ @kind = kind
+ @filter = filter
+ @key = compute_identifier filter
+ @if = check_conditionals(Array(options[:if]))
+ @unless = check_conditionals(Array(options[:unless]))
+ end
- if user_conditions.all? { |c| c.call(target, value) }
- user_callback.call target, value
- end
+ def filter; @key; end
+ def raw_filter; @filter; end
- env
- end
+ def merge_conditional_options(chain, if_option:, unless_option:)
+ options = {
+ if: @if.dup,
+ unless: @unless.dup
+ }
+
+ options[:if].concat Array(unless_option)
+ options[:unless].concat Array(if_option)
+
+ self.class.build chain, @filter, @kind, options
end
- private_class_method :conditional
- def self.simple(callback_sequence, user_callback)
- callback_sequence.after do |env|
- user_callback.call env.target, env.value
+ def matches?(_kind, _filter)
+ @kind == _kind && filter == _filter
+ end
- env
+ def duplicates?(other)
+ case @filter
+ when Symbol
+ matches?(other.kind, other.filter)
+ else
+ false
end
end
- private_class_method :simple
- end
- class Around
- def self.build(callback_sequence, user_callback, user_conditions, chain_config)
- if user_conditions.any?
- halting_and_conditional(callback_sequence, user_callback, user_conditions)
- else
- halting(callback_sequence, user_callback)
+ # Wraps code with filter
+ def apply(callback_sequence)
+ user_conditions = conditions_lambdas
+ user_callback = CallTemplate.build(@filter, self)
+
+ case kind
+ when :before
+ Filters::Before.build(callback_sequence, user_callback.make_lambda, user_conditions, chain_config, @filter)
+ when :after
+ Filters::After.build(callback_sequence, user_callback.make_lambda, user_conditions, chain_config)
+ when :around
+ callback_sequence.around(user_callback, user_conditions)
end
end
- def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
- callback_sequence.around do |env, &run|
- target = env.target
- value = env.value
- halted = env.halted
+ def current_scopes
+ Array(chain_config[:scope]).map { |s| public_send(s) }
+ end
- if !halted && user_conditions.all? { |c| c.call(target, value) }
- user_callback.call(target, value) {
- run.call.value
- }
- env
- else
- run.call
+ private
+ def check_conditionals(conditionals)
+ if conditionals.any? { |c| c.is_a?(String) }
+ raise ArgumentError, <<-MSG.squish
+ Passing string to be evaluated in :if and :unless conditional
+ options is not supported. Pass a symbol for an instance method,
+ or a lambda, proc or block, instead.
+ MSG
end
- end
- end
- private_class_method :halting_and_conditional
- def self.halting(callback_sequence, user_callback)
- callback_sequence.around do |env, &run|
- target = env.target
- value = env.value
+ conditionals
+ end
- if env.halted
- run.call
+ def compute_identifier(filter)
+ case filter
+ when ::Proc
+ filter.object_id
else
- user_callback.call(target, value) {
- run.call.value
- }
- env
+ filter
end
end
- end
- private_class_method :halting
+
+ def conditions_lambdas
+ @if.map { |c| CallTemplate.build(c, self).make_lambda } +
+ @unless.map { |c| CallTemplate.build(c, self).inverted_lambda }
+ end
end
- end
- class Callback #:nodoc:#
- def self.build(chain, filter, kind, options)
- if filter.is_a?(String)
- ActiveSupport::Deprecation.warn(<<-MSG.squish)
- Passing string to define callback is deprecated and will be removed
- in Rails 5.1 without replacement.
- MSG
+ # A future invocation of user-supplied code (either as a callback,
+ # or a condition filter).
+ class CallTemplate # :nodoc:
+ def initialize(target, method, arguments, block)
+ @override_target = target
+ @method_name = method
+ @arguments = arguments
+ @override_block = block
end
- new chain.name, filter, kind, options, chain.config
- end
+ # Return the parts needed to make this call, with the given
+ # input values.
+ #
+ # Returns an array of the form:
+ #
+ # [target, block, method, *arguments]
+ #
+ # This array can be used as such:
+ #
+ # target.send(method, *arguments, &block)
+ #
+ # The actual invocation is left up to the caller to minimize
+ # call stack pollution.
+ def expand(target, value, block)
+ result = @arguments.map { |arg|
+ case arg
+ when :value; value
+ when :target; target
+ when :block; block || raise(ArgumentError)
+ end
+ }
- attr_accessor :kind, :name
- attr_reader :chain_config
-
- def initialize(name, filter, kind, options, chain_config)
- @chain_config = chain_config
- @name = name
- @kind = kind
- @filter = filter
- @key = compute_identifier filter
- @if = Array(options[:if])
- @unless = Array(options[:unless])
- end
+ result.unshift @method_name
+ result.unshift @override_block || block
+ result.unshift @override_target || target
- def filter; @key; end
- def raw_filter; @filter; end
+ # target, block, method, *arguments = result
+ # target.send(method, *arguments, &block)
+ result
+ end
- def merge_conditional_options(chain, if_option:, unless_option:)
- options = {
- :if => @if.dup,
- :unless => @unless.dup
- }
+ # Return a lambda that will make this call when given the input
+ # values.
+ def make_lambda
+ lambda do |target, value, &block|
+ target, block, method, *arguments = expand(target, value, block)
+ target.send(method, *arguments, &block)
+ end
+ end
- options[:if].concat Array(unless_option)
- options[:unless].concat Array(if_option)
+ # Return a lambda that will make this call when given the input
+ # values, but then return the boolean inverse of that result.
+ def inverted_lambda
+ lambda do |target, value, &block|
+ target, block, method, *arguments = expand(target, value, block)
+ ! target.send(method, *arguments, &block)
+ end
+ end
- self.class.build chain, @filter, @kind, options
- end
+ # Filters support:
+ #
+ # Symbols:: A method to call.
+ # Procs:: A proc to call with the object.
+ # Objects:: An object with a <tt>before_foo</tt> method on it to call.
+ #
+ # All of these objects are converted into a CallTemplate and handled
+ # the same after this point.
+ def self.build(filter, callback)
+ case filter
+ when Symbol
+ new(nil, filter, [], nil)
+ when Conditionals::Value
+ new(filter, :call, [:target, :value], nil)
+ when ::Proc
+ if filter.arity > 1
+ new(nil, :instance_exec, [:target, :block], filter)
+ elsif filter.arity > 0
+ new(nil, :instance_exec, [:target], filter)
+ else
+ new(nil, :instance_exec, [], filter)
+ end
+ else
+ method_to_call = callback.current_scopes.join("_")
- def matches?(_kind, _filter)
- @kind == _kind && filter == _filter
+ new(filter, method_to_call, [:target], nil)
+ end
+ end
end
- def duplicates?(other)
- case @filter
- when Symbol, String
- matches?(other.kind, other.filter)
- else
- false
+ # Execute before and after filters in a sequence instead of
+ # chaining them with nested lambda calls, see:
+ # https://github.com/rails/rails/issues/18011
+ class CallbackSequence # :nodoc:
+ def initialize(nested = nil, call_template = nil, user_conditions = nil)
+ @nested = nested
+ @call_template = call_template
+ @user_conditions = user_conditions
+
+ @before = []
+ @after = []
end
- end
- # Wraps code with filter
- def apply(callback_sequence)
- user_conditions = conditions_lambdas
- user_callback = make_lambda @filter
+ def before(&before)
+ @before.unshift(before)
+ self
+ end
- case kind
- when :before
- Filters::Before.build(callback_sequence, user_callback, user_conditions, chain_config, @filter)
- when :after
- Filters::After.build(callback_sequence, user_callback, user_conditions, chain_config)
- when :around
- Filters::Around.build(callback_sequence, user_callback, user_conditions, chain_config)
+ def after(&after)
+ @after.push(after)
+ self
end
- end
- private
+ def around(call_template, user_conditions)
+ CallbackSequence.new(self, call_template, user_conditions)
+ end
- def invert_lambda(l)
- lambda { |*args, &blk| !l.call(*args, &blk) }
- end
+ def skip?(arg)
+ arg.halted || !@user_conditions.all? { |c| c.call(arg.target, arg.value) }
+ end
- # Filters support:
- #
- # Symbols:: A method to call.
- # Strings:: Some content to evaluate.
- # Procs:: A proc to call with the object.
- # Objects:: An object with a <tt>before_foo</tt> method on it to call.
- #
- # All of these objects are converted into a lambda and handled
- # the same after this point.
- def make_lambda(filter)
- case filter
- when Symbol
- lambda { |target, _, &blk| target.send filter, &blk }
- when String
- l = eval "lambda { |value| #{filter} }"
- lambda { |target, value| target.instance_exec(value, &l) }
- when Conditionals::Value then filter
- when ::Proc
- if filter.arity > 1
- return lambda { |target, _, &block|
- raise ArgumentError unless block
- target.instance_exec(target, block, &filter)
- }
- end
-
- if filter.arity <= 0
- lambda { |target, _| target.instance_exec(&filter) }
- else
- lambda { |target, _| target.instance_exec(target, &filter) }
- end
- else
- scopes = Array(chain_config[:scope])
- method_to_call = scopes.map{ |s| public_send(s) }.join("_")
+ def nested
+ @nested
+ end
- lambda { |target, _, &blk|
- filter.public_send method_to_call, target, &blk
- }
+ def final?
+ !@call_template
end
- end
- def compute_identifier(filter)
- case filter
- when String, ::Proc
- filter.object_id
- else
- filter
+ def expand_call_template(arg, block)
+ @call_template.expand(arg.target, arg.value, block)
end
- end
- def conditions_lambdas
- @if.map { |c| make_lambda c } +
- @unless.map { |c| invert_lambda make_lambda c }
- end
- end
+ def invoke_before(arg)
+ @before.each { |b| b.call(arg) }
+ end
- # Execute before and after filters in a sequence instead of
- # chaining them with nested lambda calls, see:
- # https://github.com/rails/rails/issues/18011
- class CallbackSequence
- def initialize(&call)
- @call = call
- @before = []
- @after = []
+ def invoke_after(arg)
+ @after.each { |a| a.call(arg) }
+ end
end
- def before(&before)
- @before.unshift(before)
- self
- end
+ class CallbackChain #:nodoc:#
+ include Enumerable
- def after(&after)
- @after.push(after)
- self
- end
+ attr_reader :name, :config
- def around(&around)
- CallbackSequence.new do |arg|
- around.call(arg) {
- self.call(arg)
- }
+ def initialize(name, config)
+ @name = name
+ @config = {
+ scope: [:kind],
+ terminator: default_terminator
+ }.merge!(config)
+ @chain = []
+ @callbacks = nil
+ @mutex = Mutex.new
end
- end
- def call(arg)
- @before.each { |b| b.call(arg) }
- value = @call.call(arg)
- @after.each { |a| a.call(arg) }
- value
- end
- end
+ def each(&block); @chain.each(&block); end
+ def index(o); @chain.index(o); end
+ def empty?; @chain.empty?; end
- # An Array with a compile method.
- class CallbackChain #:nodoc:#
- include Enumerable
-
- attr_reader :name, :config
-
- def initialize(name, config)
- @name = name
- @config = {
- scope: [:kind],
- terminator: default_terminator
- }.merge!(config)
- @chain = []
- @callbacks = nil
- @mutex = Mutex.new
- end
+ def insert(index, o)
+ @callbacks = nil
+ @chain.insert(index, o)
+ end
- def each(&block); @chain.each(&block); end
- def index(o); @chain.index(o); end
- def empty?; @chain.empty?; end
+ def delete(o)
+ @callbacks = nil
+ @chain.delete(o)
+ end
- def insert(index, o)
- @callbacks = nil
- @chain.insert(index, o)
- end
+ def clear
+ @callbacks = nil
+ @chain.clear
+ self
+ end
- def delete(o)
- @callbacks = nil
- @chain.delete(o)
- end
+ def initialize_copy(other)
+ @callbacks = nil
+ @chain = other.chain.dup
+ @mutex = Mutex.new
+ end
- def clear
- @callbacks = nil
- @chain.clear
- self
- end
+ def compile
+ @callbacks || @mutex.synchronize do
+ final_sequence = CallbackSequence.new
+ @callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback|
+ callback.apply callback_sequence
+ end
+ end
+ end
- def initialize_copy(other)
- @callbacks = nil
- @chain = other.chain.dup
- @mutex = Mutex.new
- end
+ def append(*callbacks)
+ callbacks.each { |c| append_one(c) }
+ end
- def compile
- @callbacks || @mutex.synchronize do
- final_sequence = CallbackSequence.new { |env| Filters::ENDING.call(env) }
- @callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback|
- callback.apply callback_sequence
- end
+ def prepend(*callbacks)
+ callbacks.each { |c| prepend_one(c) }
end
- end
- def append(*callbacks)
- callbacks.each { |c| append_one(c) }
- end
+ protected
+ def chain; @chain; end
- def prepend(*callbacks)
- callbacks.each { |c| prepend_one(c) }
- end
+ private
- protected
- def chain; @chain; end
+ def append_one(callback)
+ @callbacks = nil
+ remove_duplicates(callback)
+ @chain.push(callback)
+ end
- private
+ def prepend_one(callback)
+ @callbacks = nil
+ remove_duplicates(callback)
+ @chain.unshift(callback)
+ end
- def append_one(callback)
- @callbacks = nil
- remove_duplicates(callback)
- @chain.push(callback)
- end
+ def remove_duplicates(callback)
+ @callbacks = nil
+ @chain.delete_if { |c| callback.duplicates?(c) }
+ end
- def prepend_one(callback)
- @callbacks = nil
- remove_duplicates(callback)
- @chain.unshift(callback)
+ def default_terminator
+ Proc.new do |target, result_lambda|
+ terminate = true
+ catch(:abort) do
+ result_lambda.call
+ terminate = false
+ end
+ terminate
+ end
+ end
end
- def remove_duplicates(callback)
- @callbacks = nil
- @chain.delete_if { |c| callback.duplicates?(c) }
- end
+ module ClassMethods
+ def normalize_callback_params(filters, block) # :nodoc:
+ type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
+ options = filters.extract_options!
+ filters.unshift(block) if block
+ [type, filters, options.dup]
+ end
- def default_terminator
- Proc.new do |target, result_lambda|
- terminate = true
- catch(:abort) do
- result_lambda.call if result_lambda.is_a?(Proc)
- terminate = false
+ # This is used internally to append, prepend and skip callbacks to the
+ # CallbackChain.
+ def __update_callbacks(name) #:nodoc:
+ ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target|
+ chain = target.get_callbacks name
+ yield target, chain.dup
end
- terminate
end
- end
- end
- module ClassMethods
- def normalize_callback_params(filters, block) # :nodoc:
- type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
- options = filters.extract_options!
- filters.unshift(block) if block
- [type, filters, options.dup]
- end
+ # Install a callback for the given event.
+ #
+ # set_callback :save, :before, :before_method
+ # set_callback :save, :after, :after_method, if: :condition
+ # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
+ #
+ # The second argument indicates whether the callback is to be run +:before+,
+ # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
+ # means the first example above can also be written as:
+ #
+ # set_callback :save, :before_method
+ #
+ # The callback can be specified as a symbol naming an instance method; as a
+ # proc, lambda, or block; or as an object that responds to a certain method
+ # determined by the <tt>:scope</tt> argument to +define_callbacks+.
+ #
+ # If a proc, lambda, or block is given, its body is evaluated in the context
+ # of the current object. It can also optionally accept the current object as
+ # an argument.
+ #
+ # Before and around callbacks are called in the order that they are set;
+ # after callbacks are called in the reverse order.
+ #
+ # Around callbacks can access the return value from the event, if it
+ # wasn't halted, from the +yield+ call.
+ #
+ # ===== Options
+ #
+ # * <tt>:if</tt> - A symbol or an array of symbols, each naming an instance
+ # method or a proc; the callback will be called only when they all return
+ # a true value.
+ # * <tt>:unless</tt> - A symbol or an array of symbols, each naming an
+ # instance method or a proc; the callback will be called only when they
+ # all return a false value.
+ # * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
+ # existing chain rather than appended.
+ def set_callback(name, *filter_list, &block)
+ type, filters, options = normalize_callback_params(filter_list, block)
+
+ self_chain = get_callbacks name
+ mapped = filters.map do |filter|
+ Callback.build(self_chain, filter, type, options)
+ end
- # This is used internally to append, prepend and skip callbacks to the
- # CallbackChain.
- def __update_callbacks(name) #:nodoc:
- ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target|
- chain = target.get_callbacks name
- yield target, chain.dup
+ __update_callbacks(name) do |target, chain|
+ options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
+ target.set_callbacks name, chain
+ end
end
- end
- # Install a callback for the given event.
- #
- # set_callback :save, :before, :before_method
- # set_callback :save, :after, :after_method, if: :condition
- # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
- #
- # The second argument indicates whether the callback is to be run +:before+,
- # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
- # means the first example above can also be written as:
- #
- # set_callback :save, :before_method
- #
- # The callback can be specified as a symbol naming an instance method; as a
- # proc, lambda, or block; as a string to be instance evaluated(deprecated); or as an
- # object that responds to a certain method determined by the <tt>:scope</tt>
- # argument to +define_callbacks+.
- #
- # If a proc, lambda, or block is given, its body is evaluated in the context
- # of the current object. It can also optionally accept the current object as
- # an argument.
- #
- # Before and around callbacks are called in the order that they are set;
- # after callbacks are called in the reverse order.
- #
- # Around callbacks can access the return value from the event, if it
- # wasn't halted, from the +yield+ call.
- #
- # ===== Options
- #
- # * <tt>:if</tt> - A symbol, a string or an array of symbols and strings,
- # each naming an instance method or a proc; the callback will be called
- # only when they all return a true value.
- # * <tt>:unless</tt> - A symbol, a string or an array of symbols and
- # strings, each naming an instance method or a proc; the callback will
- # be called only when they all return a false value.
- # * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
- # existing chain rather than appended.
- def set_callback(name, *filter_list, &block)
- type, filters, options = normalize_callback_params(filter_list, block)
- self_chain = get_callbacks name
- mapped = filters.map do |filter|
- Callback.build(self_chain, filter, type, options)
- end
-
- __update_callbacks(name) do |target, chain|
- options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
- target.set_callbacks name, chain
- end
- end
+ # Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
+ # <tt>:unless</tt> options may be passed in order to control when the
+ # callback is skipped.
+ #
+ # class Writer < Person
+ # skip_callback :validate, :before, :check_membership, if: -> { age > 18 }
+ # end
+ #
+ # An <tt>ArgumentError</tt> will be raised if the callback has not
+ # already been set (unless the <tt>:raise</tt> option is set to <tt>false</tt>).
+ def skip_callback(name, *filter_list, &block)
+ type, filters, options = normalize_callback_params(filter_list, block)
+
+ options[:raise] = true unless options.key?(:raise)
+
+ __update_callbacks(name) do |target, chain|
+ filters.each do |filter|
+ callback = chain.find { |c| c.matches?(type, filter) }
+
+ if !callback && options[:raise]
+ raise ArgumentError, "#{type.to_s.capitalize} #{name} callback #{filter.inspect} has not been defined"
+ end
- # Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
- # <tt>:unless</tt> options may be passed in order to control when the
- # callback is skipped.
- #
- # class Writer < Person
- # skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
- # end
- #
- # An <tt>ArgumentError</tt> will be raised if the callback has not
- # already been set (unless the <tt>:raise</tt> option is set to <tt>false</tt>).
- def skip_callback(name, *filter_list, &block)
- type, filters, options = normalize_callback_params(filter_list, block)
- options[:raise] = true unless options.key?(:raise)
-
- __update_callbacks(name) do |target, chain|
- filters.each do |filter|
- callback = chain.find {|c| c.matches?(type, filter) }
-
- if !callback && options[:raise]
- raise ArgumentError, "#{type.to_s.capitalize} #{name} callback #{filter.inspect} has not been defined"
- end
+ if callback && (options.key?(:if) || options.key?(:unless))
+ new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless])
+ chain.insert(chain.index(callback), new_callback)
+ end
- if callback && (options.key?(:if) || options.key?(:unless))
- new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless])
- chain.insert(chain.index(callback), new_callback)
+ chain.delete(callback)
end
-
- chain.delete(callback)
+ target.set_callbacks name, chain
end
- target.set_callbacks name, chain
end
- end
- # Remove all set callbacks for the given event.
- def reset_callbacks(name)
- callbacks = get_callbacks name
+ # Remove all set callbacks for the given event.
+ def reset_callbacks(name)
+ callbacks = get_callbacks name
- ActiveSupport::DescendantsTracker.descendants(self).each do |target|
- chain = target.get_callbacks(name).dup
- callbacks.each { |c| chain.delete(c) }
- target.set_callbacks name, chain
- end
-
- self.set_callbacks name, callbacks.dup.clear
- end
+ ActiveSupport::DescendantsTracker.descendants(self).each do |target|
+ chain = target.get_callbacks(name).dup
+ callbacks.each { |c| chain.delete(c) }
+ target.set_callbacks name, chain
+ end
- # Define sets of events in the object life cycle that support callbacks.
- #
- # define_callbacks :validate
- # define_callbacks :initialize, :save, :destroy
- #
- # ===== Options
- #
- # * <tt>:terminator</tt> - Determines when a before filter will halt the
- # callback chain, preventing following before and around callbacks from
- # being called and the event from being triggered.
- # This should be a lambda to be executed.
- # The current object and the result lambda of the callback will be provided
- # to the terminator lambda.
- #
- # define_callbacks :validate, terminator: ->(target, result_lambda) { result_lambda.call == false }
- #
- # In this example, if any before validate callbacks returns +false+,
- # any successive before and around callback is not executed.
- #
- # The default terminator halts the chain when a callback throws +:abort+.
- #
- # * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
- # callbacks should be terminated by the <tt>:terminator</tt> option. By
- # default after callbacks are executed no matter if callback chain was
- # terminated or not. This option makes sense only when <tt>:terminator</tt>
- # option is specified.
- #
- # * <tt>:scope</tt> - Indicates which methods should be executed when an
- # object is used as a callback.
- #
- # class Audit
- # def before(caller)
- # puts 'Audit: before is called'
- # end
- #
- # def before_save(caller)
- # puts 'Audit: before_save is called'
- # end
- # end
- #
- # class Account
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- # set_callback :save, :before, Audit.new
- #
- # def save
- # run_callbacks :save do
- # puts 'save in main'
- # end
- # end
- # end
- #
- # In the above case whenever you save an account the method
- # <tt>Audit#before</tt> will be called. On the other hand
- #
- # define_callbacks :save, scope: [:kind, :name]
- #
- # would trigger <tt>Audit#before_save</tt> instead. That's constructed
- # by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
- # case "kind" is "before" and "name" is "save". In this context +:kind+
- # and +:name+ have special meanings: +:kind+ refers to the kind of
- # callback (before/after/around) and +:name+ refers to the method on
- # which callbacks are being defined.
- #
- # A declaration like
- #
- # define_callbacks :save, scope: [:name]
- #
- # would call <tt>Audit#save</tt>.
- #
- # NOTE: +method_name+ passed to `define_model_callbacks` must not end with
- # `!`, `?` or `=`.
- def define_callbacks(*names)
- options = names.extract_options!
-
- names.each do |name|
- class_attribute "_#{name}_callbacks", instance_writer: false
- set_callbacks name, CallbackChain.new(name, options)
-
- module_eval <<-RUBY, __FILE__, __LINE__ + 1
- def _run_#{name}_callbacks(&block)
- __run_callbacks__(_#{name}_callbacks, &block)
- end
- RUBY
+ set_callbacks(name, callbacks.dup.clear)
end
- end
- protected
+ # Define sets of events in the object life cycle that support callbacks.
+ #
+ # define_callbacks :validate
+ # define_callbacks :initialize, :save, :destroy
+ #
+ # ===== Options
+ #
+ # * <tt>:terminator</tt> - Determines when a before filter will halt the
+ # callback chain, preventing following before and around callbacks from
+ # being called and the event from being triggered.
+ # This should be a lambda to be executed.
+ # The current object and the result lambda of the callback will be provided
+ # to the terminator lambda.
+ #
+ # define_callbacks :validate, terminator: ->(target, result_lambda) { result_lambda.call == false }
+ #
+ # In this example, if any before validate callbacks returns +false+,
+ # any successive before and around callback is not executed.
+ #
+ # The default terminator halts the chain when a callback throws +:abort+.
+ #
+ # * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
+ # callbacks should be terminated by the <tt>:terminator</tt> option. By
+ # default after callbacks are executed no matter if callback chain was
+ # terminated or not. This option makes sense only when <tt>:terminator</tt>
+ # option is specified.
+ #
+ # * <tt>:scope</tt> - Indicates which methods should be executed when an
+ # object is used as a callback.
+ #
+ # class Audit
+ # def before(caller)
+ # puts 'Audit: before is called'
+ # end
+ #
+ # def before_save(caller)
+ # puts 'Audit: before_save is called'
+ # end
+ # end
+ #
+ # class Account
+ # include ActiveSupport::Callbacks
+ #
+ # define_callbacks :save
+ # set_callback :save, :before, Audit.new
+ #
+ # def save
+ # run_callbacks :save do
+ # puts 'save in main'
+ # end
+ # end
+ # end
+ #
+ # In the above case whenever you save an account the method
+ # <tt>Audit#before</tt> will be called. On the other hand
+ #
+ # define_callbacks :save, scope: [:kind, :name]
+ #
+ # would trigger <tt>Audit#before_save</tt> instead. That's constructed
+ # by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
+ # case "kind" is "before" and "name" is "save". In this context +:kind+
+ # and +:name+ have special meanings: +:kind+ refers to the kind of
+ # callback (before/after/around) and +:name+ refers to the method on
+ # which callbacks are being defined.
+ #
+ # A declaration like
+ #
+ # define_callbacks :save, scope: [:name]
+ #
+ # would call <tt>Audit#save</tt>.
+ #
+ # ===== Notes
+ #
+ # +names+ passed to +define_callbacks+ must not end with
+ # <tt>!</tt>, <tt>?</tt> or <tt>=</tt>.
+ #
+ # Calling +define_callbacks+ multiple times with the same +names+ will
+ # overwrite previous callbacks registered with +set_callback+.
+ def define_callbacks(*names)
+ options = names.extract_options!
+
+ names.each do |name|
+ name = name.to_sym
+
+ set_callbacks name, CallbackChain.new(name, options)
+
+ module_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def _run_#{name}_callbacks(&block)
+ run_callbacks #{name.inspect}, &block
+ end
- def get_callbacks(name) # :nodoc:
- send "_#{name}_callbacks"
- end
+ def self._#{name}_callbacks
+ get_callbacks(#{name.inspect})
+ end
- def set_callbacks(name, callbacks) # :nodoc:
- send "_#{name}_callbacks=", callbacks
- end
+ def self._#{name}_callbacks=(value)
+ set_callbacks(#{name.inspect}, value)
+ end
- def deprecated_false_terminator # :nodoc:
- Proc.new do |target, result_lambda|
- terminate = true
- catch(:abort) do
- result = result_lambda.call if result_lambda.is_a?(Proc)
- if Callbacks.halt_and_display_warning_on_return_false && result == false
- display_deprecation_warning_for_false_terminator
- else
- terminate = false
- end
+ def _#{name}_callbacks
+ __callbacks[#{name.inspect}]
+ end
+ RUBY
end
- terminate
end
- end
- private
+ protected
+
+ def get_callbacks(name) # :nodoc:
+ __callbacks[name.to_sym]
+ end
- def display_deprecation_warning_for_false_terminator
- ActiveSupport::Deprecation.warn(<<-MSG.squish)
- Returning `false` in Active Record and Active Model callbacks will not implicitly halt a callback chain in Rails 5.1.
- To explicitly halt the callback chain, please use `throw :abort` instead.
- MSG
+ def set_callbacks(name, callbacks) # :nodoc:
+ self.__callbacks = __callbacks.merge(name.to_sym => callbacks)
+ end
end
- end
end
end
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
index 0403eb70ca..b0a0d845e5 100644
--- a/activesupport/lib/active_support/concern.rb
+++ b/activesupport/lib/active_support/concern.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# A typical module looks like this:
#
@@ -111,7 +113,7 @@ module ActiveSupport
def append_features(base)
if base.instance_variable_defined?(:@_dependencies)
base.instance_variable_get(:@_dependencies) << self
- return false
+ false
else
return false if base < self
@_dependencies.each { |dep| base.include(dep) }
diff --git a/activesupport/lib/active_support/concurrency/latch.rb b/activesupport/lib/active_support/concurrency/latch.rb
deleted file mode 100644
index 4abe5ece6f..0000000000
--- a/activesupport/lib/active_support/concurrency/latch.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-require 'concurrent/atomic/count_down_latch'
-
-module ActiveSupport
- module Concurrency
- class Latch < Concurrent::CountDownLatch
-
- def initialize(count = 1)
- ActiveSupport::Deprecation.warn("ActiveSupport::Concurrency::Latch is deprecated. Please use Concurrent::CountDownLatch instead.")
- super(count)
- end
-
- alias_method :release, :count_down
-
- def await
- wait(nil)
- end
- end
- end
-end
diff --git a/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb b/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb
new file mode 100644
index 0000000000..a8455c0048
--- /dev/null
+++ b/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+require "monitor"
+
+module ActiveSupport
+ module Concurrency
+ # A monitor that will permit dependency loading while blocked waiting for
+ # the lock.
+ class LoadInterlockAwareMonitor < Monitor
+ # Enters an exclusive section, but allows dependency loading while blocked
+ def mon_enter
+ mon_try_enter ||
+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super }
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/concurrency/share_lock.rb b/activesupport/lib/active_support/concurrency/share_lock.rb
index 89e63aefd4..f18ccf1c88 100644
--- a/activesupport/lib/active_support/concurrency/share_lock.rb
+++ b/activesupport/lib/active_support/concurrency/share_lock.rb
@@ -1,5 +1,7 @@
-require 'thread'
-require 'monitor'
+# frozen_string_literal: true
+
+require "thread"
+require "monitor"
module ActiveSupport
module Concurrency
@@ -13,6 +15,37 @@ module ActiveSupport
# we need exclusive locks to be reentrant, and we need to be able
# to upgrade share locks to exclusive.
+ def raw_state # :nodoc:
+ synchronize do
+ threads = @sleeping.keys | @sharing.keys | @waiting.keys
+ threads |= [@exclusive_thread] if @exclusive_thread
+
+ data = {}
+
+ threads.each do |thread|
+ purpose, compatible = @waiting[thread]
+
+ data[thread] = {
+ thread: thread,
+ sharing: @sharing[thread],
+ exclusive: @exclusive_thread == thread,
+ purpose: purpose,
+ compatible: compatible,
+ waiting: !!@waiting[thread],
+ sleeper: @sleeping[thread],
+ }
+ end
+
+ # NB: Yields while holding our *internal* synchronize lock,
+ # which is supposed to be used only for a few instructions at
+ # a time. This allows the caller to inspect additional state
+ # without things changing out from underneath, but would have
+ # disastrous effects upon normal operation. Fortunately, this
+ # method is only intended to be called when things have
+ # already gone wrong.
+ yield data
+ end
+ end
def initialize
super()
@@ -21,6 +54,7 @@ module ActiveSupport
@sharing = Hash.new(0)
@waiting = {}
+ @sleeping = {}
@exclusive_thread = nil
@exclusive_depth = 0
end
@@ -46,7 +80,7 @@ module ActiveSupport
return false if no_wait
yield_shares(purpose: purpose, compatible: compatible, block_share: true) do
- @cv.wait_while { busy_for_exclusive?(purpose) }
+ wait_for(:start_exclusive) { busy_for_exclusive?(purpose) }
end
end
@exclusive_thread = Thread.current
@@ -69,7 +103,7 @@ module ActiveSupport
if eligible_waiters?(compatible)
yield_shares(compatible: compatible, block_share: true) do
- @cv.wait_while { @exclusive_thread || eligible_waiters?(compatible) }
+ wait_for(:stop_exclusive) { @exclusive_thread || eligible_waiters?(compatible) }
end
end
@cv.broadcast
@@ -84,11 +118,11 @@ module ActiveSupport
elsif @waiting[Thread.current]
# We're nested inside a +yield_shares+ call: we'll resume as
# soon as there isn't an exclusive lock in our way
- @cv.wait_while { @exclusive_thread }
+ wait_for(:start_sharing) { @exclusive_thread }
else
# This is an initial / outermost share call: any outstanding
# requests for an exclusive lock get to go first
- @cv.wait_while { busy_for_sharing?(false) }
+ wait_for(:start_sharing) { busy_for_sharing?(false) }
end
@sharing[Thread.current] += 1
end
@@ -153,7 +187,7 @@ module ActiveSupport
yield
ensure
synchronize do
- @cv.wait_while { @exclusive_thread && @exclusive_thread != Thread.current }
+ wait_for(:yield_shares) { @exclusive_thread && @exclusive_thread != Thread.current }
if previous_wait
@waiting[Thread.current] = previous_wait
@@ -167,20 +201,27 @@ module ActiveSupport
private
- # Must be called within synchronize
- def busy_for_exclusive?(purpose)
- busy_for_sharing?(purpose) ||
- @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0)
- end
+ # Must be called within synchronize
+ def busy_for_exclusive?(purpose)
+ busy_for_sharing?(purpose) ||
+ @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0)
+ end
- def busy_for_sharing?(purpose)
- (@exclusive_thread && @exclusive_thread != Thread.current) ||
- @waiting.any? { |t, (_, c)| t != Thread.current && !c.include?(purpose) }
- end
+ def busy_for_sharing?(purpose)
+ (@exclusive_thread && @exclusive_thread != Thread.current) ||
+ @waiting.any? { |t, (_, c)| t != Thread.current && !c.include?(purpose) }
+ end
- def eligible_waiters?(compatible)
- @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } }
- end
+ def eligible_waiters?(compatible)
+ @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } }
+ end
+
+ def wait_for(method)
+ @sleeping[Thread.current] = method
+ @cv.wait_while { yield }
+ ensure
+ @sleeping.delete Thread.current
+ end
end
end
end
diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb
index 8256c325af..4d6f7819bb 100644
--- a/activesupport/lib/active_support/configurable.rb
+++ b/activesupport/lib/active_support/configurable.rb
@@ -1,6 +1,9 @@
-require 'active_support/concern'
-require 'active_support/ordered_options'
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "active_support/concern"
+require "active_support/ordered_options"
+require "active_support/core_ext/array/extract_options"
+require "active_support/core_ext/regexp"
module ActiveSupport
# Configurable provides a <tt>config</tt> method to store and retrieve
@@ -107,7 +110,7 @@ module ActiveSupport
options = names.extract_options!
names.each do |name|
- raise NameError.new('invalid config attribute name') unless name =~ /\A[_A-Za-z]\w*\z/
+ raise NameError.new("invalid config attribute name") unless /\A[_A-Za-z]\w*\z/.match?(name)
reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
@@ -145,4 +148,3 @@ module ActiveSupport
end
end
end
-
diff --git a/activesupport/lib/active_support/core_ext.rb b/activesupport/lib/active_support/core_ext.rb
index 52706c3d7a..f590605d84 100644
--- a/activesupport/lib/active_support/core_ext.rb
+++ b/activesupport/lib/active_support/core_ext.rb
@@ -1,4 +1,5 @@
-DEPRECATED_FILES = ["#{File.dirname(__FILE__)}/core_ext/struct.rb"]
-(Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"] - DEPRECATED_FILES).each do |path|
+# frozen_string_literal: true
+
+Dir.glob(File.expand_path("core_ext/*.rb", __dir__)).each do |path|
require path
end
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
index 7551551bd7..6d83b76882 100644
--- a/activesupport/lib/active_support/core_ext/array.rb
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -1,7 +1,9 @@
-require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/array/access'
-require 'active_support/core_ext/array/conversions'
-require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/array/grouping'
-require 'active_support/core_ext/array/prepend_and_append'
-require 'active_support/core_ext/array/inquiry'
+# frozen_string_literal: true
+
+require "active_support/core_ext/array/wrap"
+require "active_support/core_ext/array/access"
+require "active_support/core_ext/array/conversions"
+require "active_support/core_ext/array/extract_options"
+require "active_support/core_ext/array/grouping"
+require "active_support/core_ext/array/prepend_and_append"
+require "active_support/core_ext/array/inquiry"
diff --git a/activesupport/lib/active_support/core_ext/array/access.rb b/activesupport/lib/active_support/core_ext/array/access.rb
index 37d833887a..b7ff7a3907 100644
--- a/activesupport/lib/active_support/core_ext/array/access.rb
+++ b/activesupport/lib/active_support/core_ext/array/access.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Array
# Returns the tail of the array from +position+.
#
@@ -31,10 +33,10 @@ class Array
#
# people = ["David", "Rafael", "Aaron", "Todd"]
# people.without "Aaron", "Todd"
- # => ["David", "Rafael"]
+ # # => ["David", "Rafael"]
#
- # Note: This is an optimization of `Enumerable#without` that uses `Array#-`
- # instead of `Array#reject` for performance reasons.
+ # Note: This is an optimization of <tt>Enumerable#without</tt> that uses <tt>Array#-</tt>
+ # instead of <tt>Array#reject</tt> for performance reasons.
def without(*elements)
self - elements
end
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index 8718b7e1e5..ea688ed2ea 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -1,8 +1,10 @@
-require 'active_support/xml_mini'
-require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/core_ext/object/to_param'
-require 'active_support/core_ext/object/to_query'
+# frozen_string_literal: true
+
+require "active_support/xml_mini"
+require "active_support/core_ext/hash/keys"
+require "active_support/core_ext/string/inflections"
+require "active_support/core_ext/object/to_param"
+require "active_support/core_ext/object/to_query"
class Array
# Converts the array to a comma-separated sentence where the last element is
@@ -60,9 +62,9 @@ class Array
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
default_connectors = {
- :words_connector => ', ',
- :two_words_connector => ' and ',
- :last_word_connector => ', and '
+ words_connector: ", ",
+ two_words_connector: " and ",
+ last_word_connector: ", and "
}
if defined?(I18n)
i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
@@ -72,7 +74,7 @@ class Array
case length
when 0
- ''
+ ""
when 1
"#{self[0]}"
when 2
@@ -92,9 +94,9 @@ class Array
case format
when :db
if empty?
- 'null'
+ "null"
else
- collect(&:id).join(',')
+ collect(&:id).join(",")
end
else
to_default_s
@@ -179,7 +181,7 @@ class Array
# </messages>
#
def to_xml(options = {})
- require 'active_support/builder' unless defined?(Builder)
+ require "active_support/builder" unless defined?(Builder)
options = options.dup
options[:indent] ||= 2
@@ -187,9 +189,9 @@ class Array
options[:root] ||= \
if first.class != Hash && all? { |e| e.is_a?(first.class) }
underscored = ActiveSupport::Inflector.underscore(first.class.name)
- ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
+ ActiveSupport::Inflector.pluralize(underscored).tr("/", "_")
else
- 'objects'
+ "objects"
end
builder = options[:builder]
@@ -197,7 +199,7 @@ class Array
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
children = options.delete(:children) || root.singularize
- attributes = options[:skip_types] ? {} : { type: 'array' }
+ attributes = options[:skip_types] ? {} : { type: "array" }
if empty?
builder.tag!(root, attributes)
diff --git a/activesupport/lib/active_support/core_ext/array/extract_options.rb b/activesupport/lib/active_support/core_ext/array/extract_options.rb
index 9008a0df2a..8c7cb2e780 100644
--- a/activesupport/lib/active_support/core_ext/array/extract_options.rb
+++ b/activesupport/lib/active_support/core_ext/array/extract_options.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Hash
# By default, only instances of Hash itself are extractable.
# Subclasses of Hash may implement this method and return
diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb
index 34af83d1ab..67e760bc4b 100644
--- a/activesupport/lib/active_support/core_ext/array/grouping.rb
+++ b/activesupport/lib/active_support/core_ext/array/grouping.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Array
# Splits or iterates over the array in groups of size +number+,
# padding any remaining slots with +fill_with+ unless it is +false+.
@@ -89,24 +91,19 @@ class Array
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
def split(value = nil)
+ arr = dup
+ result = []
if block_given?
- inject([[]]) do |results, element|
- if yield(element)
- results << []
- else
- results.last << element
- end
-
- results
+ while (idx = arr.index { |i| yield i })
+ result << arr.shift(idx)
+ arr.shift
end
else
- arr = self.dup
- result = []
while (idx = arr.index(value))
result << arr.shift(idx)
arr.shift
end
- result << arr
end
+ result << arr
end
end
diff --git a/activesupport/lib/active_support/core_ext/array/inquiry.rb b/activesupport/lib/active_support/core_ext/array/inquiry.rb
index e8f44cc378..92c61bf201 100644
--- a/activesupport/lib/active_support/core_ext/array/inquiry.rb
+++ b/activesupport/lib/active_support/core_ext/array/inquiry.rb
@@ -1,4 +1,6 @@
-require 'active_support/array_inquirer'
+# frozen_string_literal: true
+
+require "active_support/array_inquirer"
class Array
# Wraps the array in an +ArrayInquirer+ object, which gives a friendlier way
diff --git a/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb b/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb
index f8d48b69df..661971d7cd 100644
--- a/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb
+++ b/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
class Array
# The human way of thinking about adding stuff to the end of a list is with append.
- alias_method :append, :<<
+ alias_method :append, :push unless [].respond_to?(:append)
# The human way of thinking about adding stuff to the beginning of a list is with prepend.
- alias_method :prepend, :unshift
-end \ No newline at end of file
+ alias_method :prepend, :unshift unless [].respond_to?(:prepend)
+end
diff --git a/activesupport/lib/active_support/core_ext/array/wrap.rb b/activesupport/lib/active_support/core_ext/array/wrap.rb
index b611d34c27..d62f97edbf 100644
--- a/activesupport/lib/active_support/core_ext/array/wrap.rb
+++ b/activesupport/lib/active_support/core_ext/array/wrap.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Array
# Wraps its argument in an array unless it is already an array (or array-like).
#
diff --git a/activesupport/lib/active_support/core_ext/benchmark.rb b/activesupport/lib/active_support/core_ext/benchmark.rb
index eb25b2bc44..641b58c8b8 100644
--- a/activesupport/lib/active_support/core_ext/benchmark.rb
+++ b/activesupport/lib/active_support/core_ext/benchmark.rb
@@ -1,4 +1,6 @@
-require 'benchmark'
+# frozen_string_literal: true
+
+require "benchmark"
class << Benchmark
# Benchmark realtime in milliseconds.
diff --git a/activesupport/lib/active_support/core_ext/big_decimal.rb b/activesupport/lib/active_support/core_ext/big_decimal.rb
index 8143113cfa..9e6a9d6331 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal.rb
@@ -1 +1,3 @@
-require 'active_support/core_ext/big_decimal/conversions'
+# frozen_string_literal: true
+
+require "active_support/core_ext/big_decimal/conversions"
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
index 22fc7ecf92..52bd229416 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -1,12 +1,12 @@
-require 'bigdecimal'
-require 'bigdecimal/util'
+# frozen_string_literal: true
+
+require "bigdecimal"
+require "bigdecimal/util"
module ActiveSupport
module BigDecimalWithDefaultFormat #:nodoc:
- DEFAULT_STRING_FORMAT = 'F'
-
- def to_s(format = nil)
- super(format || DEFAULT_STRING_FORMAT)
+ def to_s(format = "F")
+ super(format)
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/class.rb b/activesupport/lib/active_support/core_ext/class.rb
index ef903d59b5..1c110fd07b 100644
--- a/activesupport/lib/active_support/core_ext/class.rb
+++ b/activesupport/lib/active_support/core_ext/class.rb
@@ -1,2 +1,4 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/class/subclasses'
+# frozen_string_literal: true
+
+require "active_support/core_ext/class/attribute"
+require "active_support/core_ext/class/subclasses"
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb
index 802d988af2..7928efb871 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -1,11 +1,23 @@
-require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/module/remove_method'
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "active_support/core_ext/kernel/singleton_class"
+require "active_support/core_ext/module/redefine_method"
+require "active_support/core_ext/array/extract_options"
class Class
# Declare a class-level attribute whose value is inheritable by subclasses.
# Subclasses can change their own value and it will not impact parent class.
#
+ # ==== Options
+ #
+ # * <tt>:instance_reader</tt> - Sets the instance reader method (defaults to true).
+ # * <tt>:instance_writer</tt> - Sets the instance writer method (defaults to true).
+ # * <tt>:instance_accessor</tt> - Sets both instance methods (defaults to true).
+ # * <tt>:instance_predicate</tt> - Sets a predicate method (defaults to true).
+ # * <tt>:default</tt> - Sets a default value for the attribute (defaults to nil).
+ #
+ # ==== Examples
+ #
# class Base
# class_attribute :setting
# end
@@ -20,14 +32,14 @@ class Class
# Base.setting # => true
#
# In the above case as long as Subclass does not assign a value to setting
- # by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
+ # by performing <tt>Subclass.setting = _something_</tt>, <tt>Subclass.setting</tt>
# would read value assigned to parent class. Once Subclass assigns a value then
# the value assigned by Subclass would be returned.
#
# This matches normal Ruby method inheritance: think of writing an attribute
# on a subclass as overriding the reader method. However, you need to be aware
# when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
- # In such cases, you don't want to do changes in places but use setters:
+ # In such cases, you don't want to do changes in place. Instead use setters:
#
# Base.setting = []
# Base.setting # => []
@@ -68,32 +80,35 @@ class Class
# object.setting = false # => NoMethodError
#
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
+ #
+ # To set a default value for the attribute, pass <tt>default:</tt>, like so:
+ #
+ # class_attribute :settings, default: {}
def class_attribute(*attrs)
options = attrs.extract_options!
- instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
- instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
+ instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
+ instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
instance_predicate = options.fetch(:instance_predicate, true)
+ default_value = options.fetch(:default, nil)
attrs.each do |name|
- remove_possible_singleton_method(name)
+ singleton_class.silence_redefinition_of_method(name)
define_singleton_method(name) { nil }
- remove_possible_singleton_method("#{name}?")
+ singleton_class.silence_redefinition_of_method("#{name}?")
define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
ivar = "@#{name}"
- remove_possible_singleton_method("#{name}=")
+ singleton_class.silence_redefinition_of_method("#{name}=")
define_singleton_method("#{name}=") do |val|
singleton_class.class_eval do
- remove_possible_method(name)
- define_method(name) { val }
+ redefine_method(name) { val }
end
if singleton_class?
class_eval do
- remove_possible_method(name)
- define_method(name) do
+ redefine_method(name) do
if instance_variable_defined? ivar
instance_variable_get ivar
else
@@ -106,8 +121,7 @@ class Class
end
if instance_reader
- remove_possible_method name
- define_method(name) do
+ redefine_method(name) do
if instance_variable_defined?(ivar)
instance_variable_get ivar
else
@@ -115,13 +129,17 @@ class Class
end
end
- remove_possible_method "#{name}?"
- define_method("#{name}?") { !!public_send(name) } if instance_predicate
+ redefine_method("#{name}?") { !!public_send(name) } if instance_predicate
end
if instance_writer
- remove_possible_method "#{name}="
- attr_writer name
+ redefine_method("#{name}=") do |val|
+ instance_variable_set ivar, val
+ end
+ end
+
+ unless default_value.nil?
+ self.send("#{name}=", default_value)
end
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 84d5e95e7a..a77354e153 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
@@ -1,4 +1,6 @@
+# frozen_string_literal: true
+
# cattr_* became mattr_* aliases in 7dfbd91b0780fbd6a1dd9bfbc176e10894871d2d,
# but we keep this around for libraries that directly require it knowing they
# want cattr_*. No need to deprecate.
-require 'active_support/core_ext/module/attribute_accessors'
+require "active_support/core_ext/module/attribute_accessors"
diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb
index b0f9a8be34..75e65337b7 100644
--- a/activesupport/lib/active_support/core_ext/class/subclasses.rb
+++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb
@@ -1,20 +1,33 @@
-require 'active_support/core_ext/module/anonymous'
-require 'active_support/core_ext/module/reachable'
+# frozen_string_literal: true
class Class
begin
# Test if this Ruby supports each_object against singleton_class
ObjectSpace.each_object(Numeric.singleton_class) {}
- def descendants # :nodoc:
+ # Returns an array with all classes that are < than its receiver.
+ #
+ # class C; end
+ # C.descendants # => []
+ #
+ # class B < C; end
+ # C.descendants # => [B]
+ #
+ # class A < B; end
+ # C.descendants # => [B, A]
+ #
+ # class D < C; end
+ # C.descendants # => [B, A, D]
+ def descendants
descendants = []
ObjectSpace.each_object(singleton_class) do |k|
+ next if k.singleton_class?
descendants.unshift k unless k == self
end
descendants
end
rescue StandardError # JRuby 9.0.4.0 and earlier
- def descendants # :nodoc:
+ def descendants
descendants = []
ObjectSpace.each_object(Class) do |k|
descendants.unshift k if k < self
@@ -26,8 +39,6 @@ class Class
# Returns an array with the direct children of +self+.
#
- # Integer.subclasses # => [Fixnum, Bignum]
- #
# class Foo; end
# class Bar < Foo; end
# class Baz < Bar; end
diff --git a/activesupport/lib/active_support/core_ext/date.rb b/activesupport/lib/active_support/core_ext/date.rb
index 7f0f4639a2..cce73f2db2 100644
--- a/activesupport/lib/active_support/core_ext/date.rb
+++ b/activesupport/lib/active_support/core_ext/date.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/date/acts_like'
-require 'active_support/core_ext/date/blank'
-require 'active_support/core_ext/date/calculations'
-require 'active_support/core_ext/date/conversions'
-require 'active_support/core_ext/date/zones'
+# frozen_string_literal: true
+
+require "active_support/core_ext/date/acts_like"
+require "active_support/core_ext/date/blank"
+require "active_support/core_ext/date/calculations"
+require "active_support/core_ext/date/conversions"
+require "active_support/core_ext/date/zones"
diff --git a/activesupport/lib/active_support/core_ext/date/acts_like.rb b/activesupport/lib/active_support/core_ext/date/acts_like.rb
index cd90cee236..c8077f3774 100644
--- a/activesupport/lib/active_support/core_ext/date/acts_like.rb
+++ b/activesupport/lib/active_support/core_ext/date/acts_like.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/object/acts_like'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/acts_like"
class Date
# Duck-types as a Date-like class. See Object#acts_like?.
diff --git a/activesupport/lib/active_support/core_ext/date/blank.rb b/activesupport/lib/active_support/core_ext/date/blank.rb
index 71627b6a6f..e6271c79b3 100644
--- a/activesupport/lib/active_support/core_ext/date/blank.rb
+++ b/activesupport/lib/active_support/core_ext/date/blank.rb
@@ -1,4 +1,6 @@
-require 'date'
+# frozen_string_literal: true
+
+require "date"
class Date #:nodoc:
# No Date is blank:
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index d589b67bf7..1cd7acb05d 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -1,9 +1,11 @@
-require 'date'
-require 'active_support/duration'
-require 'active_support/core_ext/object/acts_like'
-require 'active_support/core_ext/date/zones'
-require 'active_support/core_ext/time/zones'
-require 'active_support/core_ext/date_and_time/calculations'
+# frozen_string_literal: true
+
+require "date"
+require "active_support/duration"
+require "active_support/core_ext/object/acts_like"
+require "active_support/core_ext/date/zones"
+require "active_support/core_ext/time/zones"
+require "active_support/core_ext/date_and_time/calculations"
class Date
include DateAndTime::Calculations
@@ -129,11 +131,11 @@ class Date
options.fetch(:day, day)
)
end
-
+
# Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there.
def compare_with_coercion(other)
if other.is_a?(Time)
- self.to_datetime <=> other
+ to_datetime <=> other
else
compare_without_coercion(other)
end
diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb
index 9a6d7bb415..870119dc7f 100644
--- a/activesupport/lib/active_support/core_ext/date/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date/conversions.rb
@@ -1,30 +1,24 @@
-require 'date'
-require 'active_support/inflector/methods'
-require 'active_support/core_ext/date/zones'
-require 'active_support/core_ext/module/remove_method'
+# frozen_string_literal: true
+
+require "date"
+require "active_support/inflector/methods"
+require "active_support/core_ext/date/zones"
+require "active_support/core_ext/module/redefine_method"
class Date
DATE_FORMATS = {
- :short => '%e %b',
- :long => '%B %e, %Y',
- :db => '%Y-%m-%d',
- :number => '%Y%m%d',
- :long_ordinal => lambda { |date|
+ short: "%d %b",
+ long: "%B %d, %Y",
+ db: "%Y-%m-%d",
+ number: "%Y%m%d",
+ long_ordinal: lambda { |date|
day_format = ActiveSupport::Inflector.ordinalize(date.day)
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
},
- :rfc822 => '%e %b %Y',
- :iso8601 => lambda { |date| date.iso8601 }
+ rfc822: "%d %b %Y",
+ iso8601: lambda { |date| date.iso8601 }
}
- # Ruby 1.9 has Date#to_time which converts to localtime only.
- remove_method :to_time
-
- # Ruby 1.9 has Date#xmlschema which converts to a string without the time
- # component. This removal may generate an issue on FreeBSD, that's why we
- # need to use remove_possible_method here
- remove_possible_method :xmlschema
-
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
#
# This method is aliased to <tt>to_s</tt>.
@@ -65,11 +59,13 @@ class Date
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
def readable_inspect
- strftime('%a, %d %b %Y')
+ strftime("%a, %d %b %Y")
end
alias_method :default_inspect, :inspect
alias_method :inspect, :readable_inspect
+ silence_redefinition_of_method :to_time
+
# Converts a Date instance to a Time, where the time is set to the beginning of the day.
# The timezone can be either :local or :utc (default :local).
#
@@ -79,11 +75,16 @@ class Date
# date.to_time(:local) # => 2007-11-10 00:00:00 0800
#
# date.to_time(:utc) # => 2007-11-10 00:00:00 UTC
+ #
+ # NOTE: The :local timezone is Ruby's *process* timezone, i.e. ENV['TZ'].
+ # If the *application's* timezone is needed, then use +in_time_zone+ instead.
def to_time(form = :local)
raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form)
::Time.send(form, year, month, day)
end
+ silence_redefinition_of_method :xmlschema
+
# Returns a string which represents the time in used time zone as DateTime
# defined by XML Schema:
#
diff --git a/activesupport/lib/active_support/core_ext/date/zones.rb b/activesupport/lib/active_support/core_ext/date/zones.rb
index d109b430db..2dcf97cff8 100644
--- a/activesupport/lib/active_support/core_ext/date/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date/zones.rb
@@ -1,5 +1,7 @@
-require 'date'
-require 'active_support/core_ext/date_and_time/zones'
+# frozen_string_literal: true
+
+require "date"
+require "active_support/core_ext/date_and_time/zones"
class Date
include DateAndTime::Zones
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
index 4da7fdd159..f6cb1a384c 100644
--- a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
@@ -1,15 +1,17 @@
-require 'active_support/core_ext/object/try'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/try"
module DateAndTime
module Calculations
DAYS_INTO_WEEK = {
- :monday => 0,
- :tuesday => 1,
- :wednesday => 2,
- :thursday => 3,
- :friday => 4,
- :saturday => 5,
- :sunday => 6
+ monday: 0,
+ tuesday: 1,
+ wednesday: 2,
+ thursday: 3,
+ friday: 4,
+ saturday: 5,
+ sunday: 6
}
WEEKEND_DAYS = [ 6, 0 ]
@@ -18,9 +20,9 @@ module DateAndTime
advance(days: -1)
end
- # Returns a new date/time representing the previous day.
- def prev_day
- advance(days: -1)
+ # Returns a new date/time the specified number of days ago.
+ def prev_day(days = 1)
+ advance(days: -days)
end
# Returns a new date/time representing tomorrow.
@@ -28,9 +30,9 @@ module DateAndTime
advance(days: 1)
end
- # Returns a new date/time representing the next day.
- def next_day
- advance(days: 1)
+ # Returns a new date/time the specified number of days in the future.
+ def next_day(days = 1)
+ advance(days: days)
end
# Returns true if the date/time is today.
@@ -60,42 +62,42 @@ module DateAndTime
# Returns a new date/time the specified number of days ago.
def days_ago(days)
- advance(:days => -days)
+ advance(days: -days)
end
# Returns a new date/time the specified number of days in the future.
def days_since(days)
- advance(:days => days)
+ advance(days: days)
end
# Returns a new date/time the specified number of weeks ago.
def weeks_ago(weeks)
- advance(:weeks => -weeks)
+ advance(weeks: -weeks)
end
# Returns a new date/time the specified number of weeks in the future.
def weeks_since(weeks)
- advance(:weeks => weeks)
+ advance(weeks: weeks)
end
# Returns a new date/time the specified number of months ago.
def months_ago(months)
- advance(:months => -months)
+ advance(months: -months)
end
# Returns a new date/time the specified number of months in the future.
def months_since(months)
- advance(:months => months)
+ advance(months: months)
end
# Returns a new date/time the specified number of years ago.
def years_ago(years)
- advance(:years => -years)
+ advance(years: -years)
end
# Returns a new date/time the specified number of years in the future.
def years_since(years)
- advance(:years => years)
+ advance(years: years)
end
# Returns a new date/time at the start of the month.
@@ -108,7 +110,7 @@ module DateAndTime
# now = DateTime.current # => Thu, 18 Jun 2015 15:23:13 +0000
# now.beginning_of_month # => Mon, 01 Jun 2015 00:00:00 +0000
def beginning_of_month
- first_hour(change(:day => 1))
+ first_hour(change(day: 1))
end
alias :at_beginning_of_month :beginning_of_month
@@ -123,7 +125,7 @@ module DateAndTime
# now.beginning_of_quarter # => Wed, 01 Jul 2015 00:00:00 +0000
def beginning_of_quarter
first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
- beginning_of_month.change(:month => first_quarter_month)
+ beginning_of_month.change(month: first_quarter_month)
end
alias :at_beginning_of_quarter :beginning_of_quarter
@@ -138,7 +140,7 @@ module DateAndTime
# now.end_of_quarter # => Wed, 30 Sep 2015 23:59:59 +0000
def end_of_quarter
last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month }
- beginning_of_month.change(:month => last_quarter_month).end_of_month
+ beginning_of_month.change(month: last_quarter_month).end_of_month
end
alias :at_end_of_quarter :end_of_quarter
@@ -152,7 +154,7 @@ module DateAndTime
# now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000
# now.beginning_of_year # => Thu, 01 Jan 2015 00:00:00 +0000
def beginning_of_year
- change(:month => 1).beginning_of_month
+ change(month: 1).beginning_of_month
end
alias :at_beginning_of_year :beginning_of_year
@@ -186,9 +188,9 @@ module DateAndTime
end
end
- # Short-hand for months_since(1).
- def next_month
- months_since(1)
+ # Returns a new date/time the specified number of months in the future.
+ def next_month(months = 1)
+ advance(months: months)
end
# Short-hand for months_since(3)
@@ -196,9 +198,9 @@ module DateAndTime
months_since(3)
end
- # Short-hand for years_since(1).
- def next_year
- years_since(1)
+ # Returns a new date/time the specified number of years in the future.
+ def next_year(years = 1)
+ advance(years: years)
end
# Returns a new date/time representing the given day in the previous week.
@@ -221,11 +223,15 @@ module DateAndTime
end
alias_method :last_weekday, :prev_weekday
+ # Returns a new date/time the specified number of months ago.
+ def prev_month(months = 1)
+ advance(months: -months)
+ end
+
# Short-hand for months_ago(1).
- def prev_month
+ def last_month
months_ago(1)
end
- alias_method :last_month, :prev_month
# Short-hand for months_ago(3).
def prev_quarter
@@ -233,11 +239,15 @@ module DateAndTime
end
alias_method :last_quarter, :prev_quarter
+ # Returns a new date/time the specified number of years ago.
+ def prev_year(years = 1)
+ advance(years: -years)
+ end
+
# Short-hand for years_ago(1).
- def prev_year
+ def last_year
years_ago(1)
end
- alias_method :last_year, :prev_year
# Returns the number of days to the start of the week on the given day.
# Week is assumed to start on +start_day+, default is
@@ -290,12 +300,17 @@ module DateAndTime
# Returns a new date/time representing the end of the year.
# DateTime objects will have a time set to 23:59:59.
def end_of_year
- change(:month => 12).end_of_month
+ change(month: 12).end_of_month
end
alias :at_end_of_year :end_of_year
+ # Returns a Range representing the whole day of the current date/time.
+ def all_day
+ beginning_of_day..end_of_day
+ end
+
# Returns a Range representing the whole week of the current date/time.
- # Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set.
+ # Week starts on start_day, default is <tt>Date.beginning_of_week</tt> or <tt>config.beginning_of_week</tt> when set.
def all_week(start_day = Date.beginning_of_week)
beginning_of_week(start_day)..end_of_week(start_day)
end
@@ -315,6 +330,30 @@ module DateAndTime
beginning_of_year..end_of_year
end
+ # Returns a new date/time representing the next occurrence of the specified day of week.
+ #
+ # today = Date.today # => Thu, 14 Dec 2017
+ # today.next_occurring(:monday) # => Mon, 18 Dec 2017
+ # today.next_occurring(:thursday) # => Thu, 21 Dec 2017
+ def next_occurring(day_of_week)
+ current_day_number = wday != 0 ? wday - 1 : 6
+ from_now = DAYS_INTO_WEEK.fetch(day_of_week) - current_day_number
+ from_now += 7 unless from_now > 0
+ advance(days: from_now)
+ end
+
+ # Returns a new date/time representing the previous occurrence of the specified day of week.
+ #
+ # today = Date.today # => Thu, 14 Dec 2017
+ # today.prev_occurring(:monday) # => Mon, 11 Dec 2017
+ # today.prev_occurring(:thursday) # => Thu, 07 Dec 2017
+ def prev_occurring(day_of_week)
+ current_day_number = wday != 0 ? wday - 1 : 6
+ ago = current_day_number - DAYS_INTO_WEEK.fetch(day_of_week)
+ ago += 7 unless ago > 0
+ advance(days: -ago)
+ end
+
private
def first_hour(date_or_time)
date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time
@@ -329,7 +368,7 @@ module DateAndTime
end
def copy_time_to(other)
- other.change(hour: hour, min: min, sec: sec, usec: try(:usec))
+ other.change(hour: hour, min: min, sec: sec, nsec: try(:nsec))
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb b/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb
index 19e596a144..d33c36ef73 100644
--- a/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb
+++ b/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/module/attribute_accessors'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/attribute_accessors"
module DateAndTime
module Compatibility
@@ -9,10 +11,6 @@ module DateAndTime
# of the receiver. For backwards compatibility we're overriding
# this behavior, but new apps will have an initializer that sets
# this to true, because the new behavior is preferred.
- mattr_accessor(:preserve_timezone, instance_writer: false) { false }
-
- def to_time
- preserve_timezone ? getlocal(utc_offset) : getlocal
- end
+ mattr_accessor :preserve_timezone, instance_writer: false, default: false
end
end
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
index e2432c8f8a..894fd9b76d 100644
--- a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module DateAndTime
module Zones
# Returns the simultaneous time in <tt>Time.zone</tt> if a zone is given or
@@ -22,19 +24,18 @@ module DateAndTime
if time_zone
time_with_zone(time, time_zone)
else
- time || self.to_time
+ time || to_time
end
end
private
- def time_with_zone(time, zone)
- if time
- ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
- else
- ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
+ def time_with_zone(time, zone)
+ if time
+ ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
+ else
+ ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
+ end
end
- end
end
end
-
diff --git a/activesupport/lib/active_support/core_ext/date_time.rb b/activesupport/lib/active_support/core_ext/date_time.rb
index 86177488c0..790dbeec1b 100644
--- a/activesupport/lib/active_support/core_ext/date_time.rb
+++ b/activesupport/lib/active_support/core_ext/date_time.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/date_time/acts_like'
-require 'active_support/core_ext/date_time/blank'
-require 'active_support/core_ext/date_time/calculations'
-require 'active_support/core_ext/date_time/compatibility'
-require 'active_support/core_ext/date_time/conversions'
+# frozen_string_literal: true
+
+require "active_support/core_ext/date_time/acts_like"
+require "active_support/core_ext/date_time/blank"
+require "active_support/core_ext/date_time/calculations"
+require "active_support/core_ext/date_time/compatibility"
+require "active_support/core_ext/date_time/conversions"
diff --git a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
index 8fbbe0d3e9..5dccdfe219 100644
--- a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
@@ -1,5 +1,7 @@
-require 'date'
-require 'active_support/core_ext/object/acts_like'
+# frozen_string_literal: true
+
+require "date"
+require "active_support/core_ext/object/acts_like"
class DateTime
# Duck-types as a Date-like class. See Object#acts_like?.
diff --git a/activesupport/lib/active_support/core_ext/date_time/blank.rb b/activesupport/lib/active_support/core_ext/date_time/blank.rb
index 56981b75fb..a52c8bc150 100644
--- a/activesupport/lib/active_support/core_ext/date_time/blank.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/blank.rb
@@ -1,4 +1,6 @@
-require 'date'
+# frozen_string_literal: true
+
+require "date"
class DateTime #:nodoc:
# No DateTime is ever blank:
diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
index 9e89a33491..e61b23f842 100644
--- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -1,4 +1,6 @@
-require 'date'
+# frozen_string_literal: true
+
+require "date"
class DateTime
class << self
@@ -47,13 +49,23 @@ class DateTime
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
def change(options)
+ if new_nsec = options[:nsec]
+ raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
+ new_fraction = Rational(new_nsec, 1000000000)
+ else
+ new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
+ new_fraction = Rational(new_usec, 1000000)
+ end
+
+ raise ArgumentError, "argument out of range" if new_fraction >= 1
+
::DateTime.civil(
options.fetch(:year, year),
options.fetch(:month, month),
options.fetch(:day, day),
options.fetch(:hour, hour),
options.fetch(:min, options[:hour] ? 0 : min),
- options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec + sec_fraction),
+ options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) + new_fraction,
options.fetch(:offset, offset),
options.fetch(:start, start)
)
@@ -75,7 +87,7 @@ class DateTime
end
d = to_date.advance(options)
- datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
+ datetime_advanced_by_date = change(year: d.year, month: d.month, day: d.day)
seconds_to_advance = \
options.fetch(:seconds, 0) +
options.fetch(:minutes, 0) * 60 +
@@ -104,7 +116,7 @@ class DateTime
# Returns a new DateTime representing the start of the day (0:00).
def beginning_of_day
- change(:hour => 0)
+ change(hour: 0)
end
alias :midnight :beginning_of_day
alias :at_midnight :beginning_of_day
@@ -112,7 +124,7 @@ class DateTime
# Returns a new DateTime representing the middle of the day (12:00)
def middle_of_day
- change(:hour => 12)
+ change(hour: 12)
end
alias :midday :middle_of_day
alias :noon :middle_of_day
@@ -122,31 +134,31 @@ class DateTime
# Returns a new DateTime representing the end of the day (23:59:59).
def end_of_day
- change(:hour => 23, :min => 59, :sec => 59)
+ change(hour: 23, min: 59, sec: 59, usec: Rational(999999999, 1000))
end
alias :at_end_of_day :end_of_day
# Returns a new DateTime representing the start of the hour (hh:00:00).
def beginning_of_hour
- change(:min => 0)
+ change(min: 0)
end
alias :at_beginning_of_hour :beginning_of_hour
# Returns a new DateTime representing the end of the hour (hh:59:59).
def end_of_hour
- change(:min => 59, :sec => 59)
+ change(min: 59, sec: 59, usec: Rational(999999999, 1000))
end
alias :at_end_of_hour :end_of_hour
# Returns a new DateTime representing the start of the minute (hh:mm:00).
def beginning_of_minute
- change(:sec => 0)
+ change(sec: 0)
end
alias :at_beginning_of_minute :beginning_of_minute
# Returns a new DateTime representing the end of the minute (hh:mm:59).
def end_of_minute
- change(:sec => 59)
+ change(sec: 59, usec: Rational(999999999, 1000))
end
alias :at_end_of_minute :end_of_minute
diff --git a/activesupport/lib/active_support/core_ext/date_time/compatibility.rb b/activesupport/lib/active_support/core_ext/date_time/compatibility.rb
index 03e4a2adfa..7600a067cc 100644
--- a/activesupport/lib/active_support/core_ext/date_time/compatibility.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/compatibility.rb
@@ -1,5 +1,18 @@
-require 'active_support/core_ext/date_and_time/compatibility'
+# frozen_string_literal: true
+
+require "active_support/core_ext/date_and_time/compatibility"
+require "active_support/core_ext/module/redefine_method"
class DateTime
- prepend DateAndTime::Compatibility
+ include DateAndTime::Compatibility
+
+ silence_redefinition_of_method :to_time
+
+ # Either return an instance of +Time+ with the same UTC offset
+ # as +self+ or an instance of +Time+ representing the same time
+ # in the local system timezone depending on the setting of
+ # on the setting of +ActiveSupport.to_time_preserves_timezone+.
+ def to_time
+ preserve_timezone ? getlocal(utc_offset) : getlocal
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
index f59d05b214..29725c89f7 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -1,8 +1,10 @@
-require 'date'
-require 'active_support/inflector/methods'
-require 'active_support/core_ext/time/conversions'
-require 'active_support/core_ext/date_time/calculations'
-require 'active_support/values/time_zone'
+# frozen_string_literal: true
+
+require "date"
+require "active_support/inflector/methods"
+require "active_support/core_ext/time/conversions"
+require "active_support/core_ext/date_time/calculations"
+require "active_support/values/time_zone"
class DateTime
# Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
@@ -64,7 +66,7 @@ class DateTime
# # => Sun, 01 Jan 2012 00:00:00 +0300
# DateTime.civil_from_format :local, 2012, 12, 17
# # => Mon, 17 Dec 2012 00:00:00 +0000
- def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
+ def self.civil_from_format(utc_or_local, year, month = 1, day = 1, hour = 0, min = 0, sec = 0)
if utc_or_local.to_sym == :local
offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
else
@@ -95,11 +97,11 @@ class DateTime
private
- def offset_in_seconds
- (offset * 86400).to_i
- end
+ def offset_in_seconds
+ (offset * 86400).to_i
+ end
- def seconds_since_unix_epoch
- (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
- end
+ def seconds_since_unix_epoch
+ (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/digest/uuid.rb b/activesupport/lib/active_support/core_ext/digest/uuid.rb
index 593c51bba2..6e949a2d72 100644
--- a/activesupport/lib/active_support/core_ext/digest/uuid.rb
+++ b/activesupport/lib/active_support/core_ext/digest/uuid.rb
@@ -1,4 +1,6 @@
-require 'securerandom'
+# frozen_string_literal: true
+
+require "securerandom"
module Digest
module UUID
@@ -12,7 +14,7 @@ module Digest
# Using Digest::MD5 generates version 3 UUIDs; Digest::SHA1 generates version 5 UUIDs.
# uuid_from_hash always generates the same UUID for a given name and namespace combination.
#
- # See RFC 4122 for details of UUID at: http://www.ietf.org/rfc/rfc4122.txt
+ # See RFC 4122 for details of UUID at: https://www.ietf.org/rfc/rfc4122.txt
def self.uuid_from_hash(hash_class, uuid_namespace, name)
if hash_class == Digest::MD5
version = 3
@@ -26,7 +28,7 @@ module Digest
hash.update(uuid_namespace)
hash.update(name)
- ary = hash.digest.unpack('NnnnnN')
+ ary = hash.digest.unpack("NnnnnN")
ary[2] = (ary[2] & 0x0FFF) | (version << 12)
ary[3] = (ary[3] & 0x3FFF) | 0x8000
@@ -35,12 +37,12 @@ module Digest
# Convenience method for uuid_from_hash using Digest::MD5.
def self.uuid_v3(uuid_namespace, name)
- self.uuid_from_hash(Digest::MD5, uuid_namespace, name)
+ uuid_from_hash(Digest::MD5, uuid_namespace, name)
end
# Convenience method for uuid_from_hash using Digest::SHA1.
def self.uuid_v5(uuid_namespace, name)
- self.uuid_from_hash(Digest::SHA1, uuid_namespace, name)
+ uuid_from_hash(Digest::SHA1, uuid_namespace, name)
end
# Convenience method for SecureRandom.uuid.
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index eae964bc2e..17733d955c 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -1,40 +1,66 @@
+# frozen_string_literal: true
+
module Enumerable
- # Calculates a sum from the elements.
- #
- # payments.sum { |p| p.price * p.tax_rate }
- # payments.sum(&:price)
- #
- # The latter is a shortcut for:
- #
- # payments.inject(0) { |sum, p| sum + p.price }
- #
- # It can also calculate the sum without the use of a block.
+ # Enumerable#sum was added in Ruby 2.4, but it only works with Numeric elements
+ # when we omit an identity.
#
- # [5, 15, 10].sum # => 30
- # ['foo', 'bar'].sum # => "foobar"
- # [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
- #
- # The default sum of an empty list is zero. You can override this default:
- #
- # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
- def sum(identity = nil, &block)
- if block_given?
- map(&block).sum(identity)
- else
- sum = identity ? inject(identity, :+) : inject(:+)
- sum || identity || 0
+ # We tried shimming it to attempt the fast native method, rescue TypeError,
+ # and fall back to the compatible implementation, but that's much slower than
+ # just calling the compat method in the first place.
+ if Enumerable.instance_methods(false).include?(:sum) && !((?a..?b).sum rescue false)
+ # We can't use Refinements here because Refinements with Module which will be prepended
+ # doesn't work well https://bugs.ruby-lang.org/issues/13446
+ alias :_original_sum_with_required_identity :sum
+ private :_original_sum_with_required_identity
+ # Calculates a sum from the elements.
+ #
+ # payments.sum { |p| p.price * p.tax_rate }
+ # payments.sum(&:price)
+ #
+ # The latter is a shortcut for:
+ #
+ # payments.inject(0) { |sum, p| sum + p.price }
+ #
+ # It can also calculate the sum without the use of a block.
+ #
+ # [5, 15, 10].sum # => 30
+ # ['foo', 'bar'].sum # => "foobar"
+ # [[1, 2], [3, 1, 5]].sum # => [1, 2, 3, 1, 5]
+ #
+ # The default sum of an empty list is zero. You can override this default:
+ #
+ # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
+ def sum(identity = nil, &block)
+ if identity
+ _original_sum_with_required_identity(identity, &block)
+ elsif block_given?
+ map(&block).sum(identity)
+ else
+ inject(:+) || 0
+ end
+ end
+ else
+ def sum(identity = nil, &block)
+ if block_given?
+ map(&block).sum(identity)
+ else
+ sum = identity ? inject(identity, :+) : inject(:+)
+ sum || identity || 0
+ end
end
end
# Convert an enumerable to a hash.
#
# people.index_by(&:login)
- # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
+ # # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
- # => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
+ # # => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
def index_by
if block_given?
- Hash[map { |elem| [yield(elem), elem] }]
+ result = {}
+ each { |elem| result[yield(elem)] = elem }
+ result
else
to_enum(:index_by) { size if respond_to?(:size) }
end
@@ -65,10 +91,10 @@ module Enumerable
# Returns a copy of the enumerable without the specified elements.
#
# ["David", "Rafael", "Aaron", "Todd"].without "Aaron", "Todd"
- # => ["David", "Rafael"]
+ # # => ["David", "Rafael"]
#
# {foo: 1, bar: 2, baz: 3}.without :bar
- # => {foo: 1, baz: 3}
+ # # => {foo: 1, baz: 3}
def without(*elements)
reject { |element| elements.include?(element) }
end
@@ -76,10 +102,10 @@ module Enumerable
# Convert an enumerable to an array based on the given key.
#
# [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
- # => ["David", "Rafael", "Aaron"]
+ # # => ["David", "Rafael", "Aaron"]
#
# [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name)
- # => [[1, "David"], [2, "Rafael"]]
+ # # => [[1, "David"], [2, "Rafael"]]
def pluck(*keys)
if keys.many?
map { |element| keys.map { |key| element[key] } }
@@ -113,12 +139,21 @@ end
# and fall back to the compatible implementation, but that's much slower than
# just calling the compat method in the first place.
if Array.instance_methods(false).include?(:sum) && !(%w[a].sum rescue false)
- class Array
- remove_method :sum
+ # Using Refinements here in order not to expose our internal method
+ using Module.new {
+ refine Array do
+ alias :orig_sum :sum
+ end
+ }
- def sum(*args) #:nodoc:
- # Use Enumerable#sum instead.
- super
+ class Array
+ def sum(init = nil, &block) #:nodoc:
+ if init.is_a?(Numeric) || first.is_a?(Numeric)
+ init ||= 0
+ orig_sum(init, &block)
+ else
+ super
+ end
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/file.rb b/activesupport/lib/active_support/core_ext/file.rb
index dc24afbe7f..64553bfa4e 100644
--- a/activesupport/lib/active_support/core_ext/file.rb
+++ b/activesupport/lib/active_support/core_ext/file.rb
@@ -1 +1,3 @@
-require 'active_support/core_ext/file/atomic'
+# frozen_string_literal: true
+
+require "active_support/core_ext/file/atomic"
diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb
index 463fd78412..8e288833b6 100644
--- a/activesupport/lib/active_support/core_ext/file/atomic.rb
+++ b/activesupport/lib/active_support/core_ext/file/atomic.rb
@@ -1,4 +1,6 @@
-require 'fileutils'
+# frozen_string_literal: true
+
+require "fileutils"
class File
# Write to a file atomically. Useful for situations where you don't
@@ -17,7 +19,7 @@ class File
# file.write('hello')
# end
def self.atomic_write(file_name, temp_dir = dirname(file_name))
- require 'tempfile' unless defined?(Tempfile)
+ require "tempfile" unless defined?(Tempfile)
Tempfile.open(".#{basename(file_name)}", temp_dir) do |temp_file|
temp_file.binmode
@@ -53,11 +55,11 @@ class File
# Private utility method.
def self.probe_stat_in(dir) #:nodoc:
basename = [
- '.permissions_check',
+ ".permissions_check",
Thread.current.object_id,
Process.pid,
rand(1000000)
- ].join('.')
+ ].join(".")
file_name = join(dir, basename)
FileUtils.touch(file_name)
diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb
index af4d1da0eb..e19aeaa983 100644
--- a/activesupport/lib/active_support/core_ext/hash.rb
+++ b/activesupport/lib/active_support/core_ext/hash.rb
@@ -1,9 +1,11 @@
-require 'active_support/core_ext/hash/compact'
-require 'active_support/core_ext/hash/conversions'
-require 'active_support/core_ext/hash/deep_merge'
-require 'active_support/core_ext/hash/except'
-require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/hash/reverse_merge'
-require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/hash/transform_values'
+# frozen_string_literal: true
+
+require "active_support/core_ext/hash/compact"
+require "active_support/core_ext/hash/conversions"
+require "active_support/core_ext/hash/deep_merge"
+require "active_support/core_ext/hash/except"
+require "active_support/core_ext/hash/indifferent_access"
+require "active_support/core_ext/hash/keys"
+require "active_support/core_ext/hash/reverse_merge"
+require "active_support/core_ext/hash/slice"
+require "active_support/core_ext/hash/transform_values"
diff --git a/activesupport/lib/active_support/core_ext/hash/compact.rb b/activesupport/lib/active_support/core_ext/hash/compact.rb
index 5dc9a05ec7..d6364dd9f3 100644
--- a/activesupport/lib/active_support/core_ext/hash/compact.rb
+++ b/activesupport/lib/active_support/core_ext/hash/compact.rb
@@ -1,20 +1,29 @@
+# frozen_string_literal: true
+
class Hash
- # Returns a hash with non +nil+ values.
- #
- # hash = { a: true, b: false, c: nil}
- # hash.compact # => { a: true, b: false}
- # hash # => { a: true, b: false, c: nil}
- # { c: nil }.compact # => {}
- def compact
- self.select { |_, value| !value.nil? }
+ unless Hash.instance_methods(false).include?(:compact)
+ # Returns a hash with non +nil+ values.
+ #
+ # hash = { a: true, b: false, c: nil }
+ # hash.compact # => { a: true, b: false }
+ # hash # => { a: true, b: false, c: nil }
+ # { c: nil }.compact # => {}
+ # { c: true }.compact # => { c: true }
+ def compact
+ select { |_, value| !value.nil? }
+ end
end
- # Replaces current hash with non +nil+ values.
- #
- # hash = { a: true, b: false, c: nil}
- # hash.compact! # => { a: true, b: false}
- # hash # => { a: true, b: false}
- def compact!
- self.reject! { |_, value| value.nil? }
+ unless Hash.instance_methods(false).include?(:compact!)
+ # Replaces current hash with non +nil+ values.
+ # Returns +nil+ if no changes were made, otherwise returns the hash.
+ #
+ # hash = { a: true, b: false, c: nil }
+ # hash.compact! # => { a: true, b: false }
+ # hash # => { a: true, b: false }
+ # { c: true }.compact! # => nil
+ def compact!
+ reject! { |_, value| value.nil? }
+ end
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 dd5ebe6d8d..11d28d12a1 100644
--- a/activesupport/lib/active_support/core_ext/hash/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -1,11 +1,13 @@
-require 'active_support/xml_mini'
-require 'active_support/time'
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/object/to_param'
-require 'active_support/core_ext/object/to_query'
-require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/hash/reverse_merge'
-require 'active_support/core_ext/string/inflections'
+# frozen_string_literal: true
+
+require "active_support/xml_mini"
+require "active_support/time"
+require "active_support/core_ext/object/blank"
+require "active_support/core_ext/object/to_param"
+require "active_support/core_ext/object/to_query"
+require "active_support/core_ext/array/wrap"
+require "active_support/core_ext/hash/reverse_merge"
+require "active_support/core_ext/string/inflections"
class Hash
# Returns a string containing an XML representation of its receiver:
@@ -55,8 +57,7 @@ class Hash
#
# XML_TYPE_NAMES = {
# "Symbol" => "symbol",
- # "Fixnum" => "integer",
- # "Bignum" => "integer",
+ # "Integer" => "integer",
# "BigDecimal" => "decimal",
# "Float" => "float",
# "TrueClass" => "boolean",
@@ -72,11 +73,11 @@ class Hash
# configure your own builder with the <tt>:builder</tt> option. The method also accepts
# options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
def to_xml(options = {})
- require 'active_support/builder' unless defined?(Builder)
+ require "active_support/builder" unless defined?(Builder)
options = options.dup
options[:indent] ||= 2
- options[:root] ||= 'hash'
+ options[:root] ||= "hash"
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
builder = options[:builder]
@@ -160,36 +161,36 @@ module ActiveSupport
private
def normalize_keys(params)
case params
- when Hash
- Hash[params.map { |k,v| [k.to_s.tr('-', '_'), normalize_keys(v)] } ]
- when Array
- params.map { |v| normalize_keys(v) }
+ when Hash
+ Hash[params.map { |k, v| [k.to_s.tr("-", "_"), normalize_keys(v)] } ]
+ when Array
+ params.map { |v| normalize_keys(v) }
else
- params
+ params
end
end
def deep_to_h(value)
case value
- when Hash
- process_hash(value)
- when Array
- process_array(value)
- when String
- value
+ when Hash
+ process_hash(value)
+ when Array
+ process_array(value)
+ when String
+ value
else
- raise "can't typecast #{value.class.name} - #{value.inspect}"
+ raise "can't typecast #{value.class.name} - #{value.inspect}"
end
end
def process_hash(value)
- if value.include?('type') && !value['type'].is_a?(Hash) && @disallowed_types.include?(value['type'])
- raise DisallowedType, value['type']
+ if value.include?("type") && !value["type"].is_a?(Hash) && @disallowed_types.include?(value["type"])
+ raise DisallowedType, value["type"]
end
if become_array?(value)
- _, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
- if entries.nil? || value['__content__'].try(:empty?)
+ _, entries = Array.wrap(value.detect { |k, v| not v.is_a?(String) })
+ if entries.nil? || value["__content__"].try(:empty?)
[]
else
case entries
@@ -205,28 +206,28 @@ module ActiveSupport
process_content(value)
elsif become_empty_string?(value)
- ''
+ ""
elsif become_hash?(value)
- xml_value = Hash[value.map { |k,v| [k, deep_to_h(v)] }]
+ xml_value = Hash[value.map { |k, v| [k, deep_to_h(v)] }]
# Turn { files: { file: #<StringIO> } } into { files: #<StringIO> } so it is compatible with
# how multipart uploaded files from HTML appear
- xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value
+ xml_value["file"].is_a?(StringIO) ? xml_value["file"] : xml_value
end
end
def become_content?(value)
- value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 || value['__content__'].present?))
+ value["type"] == "file" || (value["__content__"] && (value.keys.size == 1 || value["__content__"].present?))
end
def become_array?(value)
- value['type'] == 'array'
+ value["type"] == "array"
end
def become_empty_string?(value)
# { "string" => true }
# No tests fail when the second term is removed.
- value['type'] == 'string' && value['nil'] != 'true'
+ value["type"] == "string" && value["nil"] != "true"
end
def become_hash?(value)
@@ -235,19 +236,19 @@ module ActiveSupport
def nothing?(value)
# blank or nil parsed values are represented by nil
- value.blank? || value['nil'] == 'true'
+ value.blank? || value["nil"] == "true"
end
def garbage?(value)
# If the type is the only element which makes it then
# this still makes the value nil, except if type is
# an XML node(where type['value'] is a Hash)
- value['type'] && !value['type'].is_a?(::Hash) && value.size == 1
+ value["type"] && !value["type"].is_a?(::Hash) && value.size == 1
end
def process_content(value)
- content = value['__content__']
- if parser = ActiveSupport::XmlMini::PARSING[value['type']]
+ content = value["__content__"]
+ if parser = ActiveSupport::XmlMini::PARSING[value["type"]]
parser.arity == 1 ? parser.call(content) : parser.call(content, value)
else
content
@@ -258,6 +259,5 @@ module ActiveSupport
value.map! { |i| deep_to_h(i) }
value.length > 1 ? value : value.first
end
-
end
end
diff --git a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb
index 9c9faf67ea..9bc50b7bc6 100644
--- a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb
+++ b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Hash
# Returns a new hash with +self+ and +other_hash+ merged recursively.
#
@@ -19,20 +21,14 @@ class Hash
# Same as +deep_merge+, but modifies +self+.
def deep_merge!(other_hash, &block)
- other_hash.each_pair do |current_key, other_value|
- this_value = self[current_key]
-
- self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash)
- this_value.deep_merge(other_value, &block)
+ merge!(other_hash) do |key, this_val, other_val|
+ if this_val.is_a?(Hash) && other_val.is_a?(Hash)
+ this_val.deep_merge(other_val, &block)
+ elsif block_given?
+ block.call(key, this_val, other_val)
else
- if block_given? && key?(current_key)
- block.call(current_key, this_value, other_value)
- else
- other_value
- end
+ other_val
end
end
-
- self
end
end
diff --git a/activesupport/lib/active_support/core_ext/hash/except.rb b/activesupport/lib/active_support/core_ext/hash/except.rb
index 2f6d38c1f6..6258610c98 100644
--- a/activesupport/lib/active_support/core_ext/hash/except.rb
+++ b/activesupport/lib/active_support/core_ext/hash/except.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Hash
# Returns a hash that includes everything except given keys.
# hash = { a: true, b: false, c: nil }
diff --git a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
index 6df7b4121b..a38f33f128 100644
--- a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
+++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
@@ -1,7 +1,8 @@
-require 'active_support/hash_with_indifferent_access'
+# frozen_string_literal: true
-class Hash
+require "active_support/hash_with_indifferent_access"
+class Hash
# Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
#
# { a: 1 }.with_indifferent_access['a'] # => 1
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index 1bfa18aeee..bdf196ec3d 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Hash
# Returns a new hash with all keys converted using the +block+ operation.
#
@@ -16,7 +18,7 @@ class Hash
result[yield(key)] = self[key]
end
result
- end
+ end unless method_defined? :transform_keys
# Destructively converts all keys using the +block+ operations.
# Same as +transform_keys+ but modifies +self+.
@@ -26,7 +28,7 @@ class Hash
self[yield(key)] = delete(key)
end
self
- end
+ end unless method_defined? :transform_keys!
# Returns a new hash with all keys converted to strings.
#
@@ -52,14 +54,14 @@ class Hash
# hash.symbolize_keys
# # => {:name=>"Rob", :age=>"28"}
def symbolize_keys
- transform_keys{ |key| key.to_sym rescue key }
+ transform_keys { |key| key.to_sym rescue key }
end
alias_method :to_options, :symbolize_keys
# Destructively converts all keys to symbols, as long as they respond
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
def symbolize_keys!
- transform_keys!{ |key| key.to_sym rescue key }
+ transform_keys! { |key| key.to_sym rescue key }
end
alias_method :to_options!, :symbolize_keys!
@@ -128,14 +130,14 @@ class Hash
# hash.deep_symbolize_keys
# # => {:person=>{:name=>"Rob", :age=>"28"}}
def deep_symbolize_keys
- deep_transform_keys{ |key| key.to_sym rescue key }
+ deep_transform_keys { |key| key.to_sym rescue key }
end
# Destructively converts all keys to symbols, as long as they respond
# to +to_sym+. This includes the keys from the root hash and from all
# nested hashes and arrays.
def deep_symbolize_keys!
- deep_transform_keys!{ |key| key.to_sym rescue key }
+ deep_transform_keys! { |key| key.to_sym rescue key }
end
private
@@ -147,7 +149,7 @@ class Hash
result[yield(key)] = _deep_transform_keys_in_object(value, &block)
end
when Array
- object.map {|e| _deep_transform_keys_in_object(e, &block) }
+ object.map { |e| _deep_transform_keys_in_object(e, &block) }
else
object
end
@@ -162,7 +164,7 @@ class Hash
end
object
when Array
- object.map! {|e| _deep_transform_keys_in_object!(e, &block)}
+ object.map! { |e| _deep_transform_keys_in_object!(e, &block) }
else
object
end
diff --git a/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
index fbb482435d..ef8d592829 100644
--- a/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
+++ b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Hash
# Merges the caller into +other_hash+. For example,
#
@@ -12,11 +14,12 @@ class Hash
def reverse_merge(other_hash)
other_hash.merge(self)
end
+ alias_method :with_defaults, :reverse_merge
# Destructive +reverse_merge+.
def reverse_merge!(other_hash)
- # right wins if there is no left
- merge!( other_hash ){|key,left,right| left }
+ replace(reverse_merge(other_hash))
end
alias_method :reverse_update, :reverse_merge!
+ alias_method :with_defaults!, :reverse_merge!
end
diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb
index 1d5f38231a..2bd0a56ea4 100644
--- a/activesupport/lib/active_support/core_ext/hash/slice.rb
+++ b/activesupport/lib/active_support/core_ext/hash/slice.rb
@@ -1,11 +1,13 @@
+# frozen_string_literal: true
+
class Hash
- # Slices a hash to include only the given keys. Returns a hash containing
+ # Slices a hash to include only the given keys. Returns a hash containing
# the given keys.
- #
+ #
# { a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b)
# # => {:a=>1, :b=>2}
- #
- # This is useful for limiting an options hash to valid keys before
+ #
+ # This is useful for limiting an options hash to valid keys before
# passing to a method:
#
# def search(criteria = {})
@@ -19,9 +21,8 @@ class Hash
# valid_keys = [:mass, :velocity, :time]
# search(options.slice(*valid_keys))
def slice(*keys)
- keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
- keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
- end
+ keys.each_with_object(Hash.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
+ end unless method_defined?(:slice)
# Replaces the hash with only the given keys.
# Returns a hash containing the removed key/value pairs.
@@ -29,7 +30,6 @@ class Hash
# { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
# # => {:c=>3, :d=>4}
def slice!(*keys)
- keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
omit = slice(*self.keys - keys)
hash = slice(*keys)
hash.default = default
diff --git a/activesupport/lib/active_support/core_ext/hash/transform_values.rb b/activesupport/lib/active_support/core_ext/hash/transform_values.rb
index 7d507ac998..4b19c9fc1f 100644
--- a/activesupport/lib/active_support/core_ext/hash/transform_values.rb
+++ b/activesupport/lib/active_support/core_ext/hash/transform_values.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Hash
# Returns a new hash with the results of running +block+ once for every value.
# The keys are unchanged.
@@ -16,7 +18,7 @@ class Hash
result[key] = yield(value)
end
result
- end
+ end unless method_defined? :transform_values
# Destructively converts all values using the +block+ operations.
# Same as +transform_values+ but modifies +self+.
@@ -25,5 +27,6 @@ class Hash
each do |key, value|
self[key] = yield(value)
end
- end
+ end unless method_defined? :transform_values!
+ # TODO: Remove this file when supporting only Ruby 2.4+.
end
diff --git a/activesupport/lib/active_support/core_ext/integer.rb b/activesupport/lib/active_support/core_ext/integer.rb
index a44a1b4c74..d22701306a 100644
--- a/activesupport/lib/active_support/core_ext/integer.rb
+++ b/activesupport/lib/active_support/core_ext/integer.rb
@@ -1,3 +1,5 @@
-require 'active_support/core_ext/integer/multiple'
-require 'active_support/core_ext/integer/inflections'
-require 'active_support/core_ext/integer/time'
+# frozen_string_literal: true
+
+require "active_support/core_ext/integer/multiple"
+require "active_support/core_ext/integer/inflections"
+require "active_support/core_ext/integer/time"
diff --git a/activesupport/lib/active_support/core_ext/integer/inflections.rb b/activesupport/lib/active_support/core_ext/integer/inflections.rb
index 56f2ed5985..aef3266f28 100644
--- a/activesupport/lib/active_support/core_ext/integer/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/integer/inflections.rb
@@ -1,4 +1,6 @@
-require 'active_support/inflector'
+# frozen_string_literal: true
+
+require "active_support/inflector"
class Integer
# Ordinalize turns a number into an ordinal string used to denote the
diff --git a/activesupport/lib/active_support/core_ext/integer/multiple.rb b/activesupport/lib/active_support/core_ext/integer/multiple.rb
index c668c7c2eb..e7606662d3 100644
--- a/activesupport/lib/active_support/core_ext/integer/multiple.rb
+++ b/activesupport/lib/active_support/core_ext/integer/multiple.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Integer
# Check whether the integer is evenly divisible by the argument.
#
diff --git a/activesupport/lib/active_support/core_ext/integer/time.rb b/activesupport/lib/active_support/core_ext/integer/time.rb
index 87185b024f..5efb89cf9f 100644
--- a/activesupport/lib/active_support/core_ext/integer/time.rb
+++ b/activesupport/lib/active_support/core_ext/integer/time.rb
@@ -1,29 +1,22 @@
-require 'active_support/duration'
-require 'active_support/core_ext/numeric/time'
+# frozen_string_literal: true
+
+require "active_support/duration"
+require "active_support/core_ext/numeric/time"
class Integer
- # Enables the use of time calculations and declarations, like <tt>45.minutes +
- # 2.hours + 4.years</tt>.
- #
- # These methods use Time#advance for precise date calculations when using
- # <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
- # results from a Time object.
- #
- # # equivalent to Time.now.advance(months: 1)
- # 1.month.from_now
+ # Returns a Duration instance matching the number of months provided.
#
- # # equivalent to Time.now.advance(years: 2)
- # 2.years.from_now
- #
- # # equivalent to Time.now.advance(months: 4, years: 5)
- # (4.months + 5.years).from_now
+ # 2.months # => 2 months
def months
- ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
+ ActiveSupport::Duration.months(self)
end
alias :month :months
+ # Returns a Duration instance matching the number of years provided.
+ #
+ # 2.years # => 2 years
def years
- ActiveSupport::Duration.new(self * 365.25.days.to_i, [[:years, self]])
+ ActiveSupport::Duration.years(self)
end
alias :year :years
end
diff --git a/activesupport/lib/active_support/core_ext/kernel.rb b/activesupport/lib/active_support/core_ext/kernel.rb
index 364ed9d65f..0f4356fbdd 100644
--- a/activesupport/lib/active_support/core_ext/kernel.rb
+++ b/activesupport/lib/active_support/core_ext/kernel.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/kernel/agnostics'
-require 'active_support/core_ext/kernel/concern'
-require 'active_support/core_ext/kernel/reporting'
-require 'active_support/core_ext/kernel/singleton_class'
+# frozen_string_literal: true
+
+require "active_support/core_ext/kernel/agnostics"
+require "active_support/core_ext/kernel/concern"
+require "active_support/core_ext/kernel/reporting"
+require "active_support/core_ext/kernel/singleton_class"
diff --git a/activesupport/lib/active_support/core_ext/kernel/agnostics.rb b/activesupport/lib/active_support/core_ext/kernel/agnostics.rb
index 64837d87aa..403b5f31f0 100644
--- a/activesupport/lib/active_support/core_ext/kernel/agnostics.rb
+++ b/activesupport/lib/active_support/core_ext/kernel/agnostics.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Object
# Makes backticks behave (somewhat more) similarly on all platforms.
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
diff --git a/activesupport/lib/active_support/core_ext/kernel/concern.rb b/activesupport/lib/active_support/core_ext/kernel/concern.rb
index 18bcc01fa4..0b2baed780 100644
--- a/activesupport/lib/active_support/core_ext/kernel/concern.rb
+++ b/activesupport/lib/active_support/core_ext/kernel/concern.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/module/concerning'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/concerning"
module Kernel
module_function
diff --git a/activesupport/lib/active_support/core_ext/kernel/debugger.rb b/activesupport/lib/active_support/core_ext/kernel/debugger.rb
deleted file mode 100644
index 1fde3db070..0000000000
--- a/activesupport/lib/active_support/core_ext/kernel/debugger.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("This file is deprecated and will be removed in Rails 5.1 with no replacement.")
diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
index d0197af95f..9155bd6c10 100644
--- a/activesupport/lib/active_support/core_ext/kernel/reporting.rb
+++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
module Kernel
module_function
- # Sets $VERBOSE to nil for the duration of the block and back to its original
+ # Sets $VERBOSE to +nil+ for the duration of the block and back to its original
# value afterwards.
#
# silence_warnings do
diff --git a/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb b/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb
index 9bbf1bbd73..6715eba80a 100644
--- a/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb
+++ b/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module Kernel
# class_eval on an object acts like singleton_class.class_eval.
def class_eval(*args, &block)
diff --git a/activesupport/lib/active_support/core_ext/load_error.rb b/activesupport/lib/active_support/core_ext/load_error.rb
index 60732eb41a..750f858fcc 100644
--- a/activesupport/lib/active_support/core_ext/load_error.rb
+++ b/activesupport/lib/active_support/core_ext/load_error.rb
@@ -1,30 +1,9 @@
-require 'active_support/deprecation/proxy_wrappers'
+# frozen_string_literal: true
class LoadError
- REGEXPS = [
- /^no such file to load -- (.+)$/i,
- /^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
- /^Missing API definition file in (.+)$/i,
- /^cannot load such file -- (.+)$/i,
- ]
-
- unless method_defined?(:path)
- # Returns the path which was unable to be loaded.
- def path
- @path ||= begin
- REGEXPS.find do |regex|
- message =~ regex
- end
- $1
- end
- end
- end
-
# Returns true if the given path name (except perhaps for the ".rb"
# extension) is the missing file which caused the exception to be raised.
def is_missing?(location)
- location.sub(/\.rb$/, ''.freeze) == path.sub(/\.rb$/, ''.freeze)
+ location.sub(/\.rb$/, "".freeze) == path.sub(/\.rb$/, "".freeze)
end
end
-
-MissingSourceFile = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('MissingSourceFile', 'LoadError')
diff --git a/activesupport/lib/active_support/core_ext/marshal.rb b/activesupport/lib/active_support/core_ext/marshal.rb
index edfc8296fe..0c72cd7b47 100644
--- a/activesupport/lib/active_support/core_ext/marshal.rb
+++ b/activesupport/lib/active_support/core_ext/marshal.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
module ActiveSupport
module MarshalWithAutoloading # :nodoc:
- def load(source)
- super(source)
+ def load(source, proc = nil)
+ super(source, proc)
rescue ArgumentError, NameError => exc
if exc.message.match(%r|undefined class/module (.+?)(?:::)?\z|)
# try loading the class/module
diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb
index ef038331c2..d91e3fba6a 100644
--- a/activesupport/lib/active_support/core_ext/module.rb
+++ b/activesupport/lib/active_support/core_ext/module.rb
@@ -1,12 +1,14 @@
-require 'active_support/core_ext/module/aliasing'
-require 'active_support/core_ext/module/introspection'
-require 'active_support/core_ext/module/anonymous'
-require 'active_support/core_ext/module/reachable'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/module/attribute_accessors_per_thread'
-require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/concerning'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/module/deprecation'
-require 'active_support/core_ext/module/remove_method'
-require 'active_support/core_ext/module/qualified_const'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/aliasing"
+require "active_support/core_ext/module/introspection"
+require "active_support/core_ext/module/anonymous"
+require "active_support/core_ext/module/reachable"
+require "active_support/core_ext/module/attribute_accessors"
+require "active_support/core_ext/module/attribute_accessors_per_thread"
+require "active_support/core_ext/module/attr_internal"
+require "active_support/core_ext/module/concerning"
+require "active_support/core_ext/module/delegation"
+require "active_support/core_ext/module/deprecation"
+require "active_support/core_ext/module/redefine_method"
+require "active_support/core_ext/module/remove_method"
diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb
index b6934b9c54..6f64d11627 100644
--- a/activesupport/lib/active_support/core_ext/module/aliasing.rb
+++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb
@@ -1,52 +1,6 @@
-class Module
- # NOTE: This method is deprecated. Please use <tt>Module#prepend</tt> that
- # comes with Ruby 2.0 or newer instead.
- #
- # Encapsulates the common pattern of:
- #
- # alias_method :foo_without_feature, :foo
- # alias_method :foo, :foo_with_feature
- #
- # With this, you simply do:
- #
- # alias_method_chain :foo, :feature
- #
- # And both aliases are set up for you.
- #
- # Query and bang methods (foo?, foo!) keep the same punctuation:
- #
- # alias_method_chain :foo?, :feature
- #
- # is equivalent to
- #
- # alias_method :foo_without_feature?, :foo?
- # alias_method :foo?, :foo_with_feature?
- #
- # so you can safely chain foo, foo?, foo! and/or foo= with the same feature.
- def alias_method_chain(target, feature)
- ActiveSupport::Deprecation.warn("alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super.")
-
- # Strip out punctuation on predicates, bang or writer methods since
- # e.g. target?_without_feature is not a valid method name.
- aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
- yield(aliased_target, punctuation) if block_given?
-
- with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
- without_method = "#{aliased_target}_without_#{feature}#{punctuation}"
-
- alias_method without_method, target
- alias_method target, with_method
-
- case
- when public_method_defined?(without_method)
- public target
- when protected_method_defined?(without_method)
- protected target
- when private_method_defined?(without_method)
- private target
- end
- end
+# frozen_string_literal: true
+class Module
# Allows you to make aliases for attributes, which includes
# getter, setter, and a predicate.
#
@@ -65,6 +19,9 @@ class Module
# e.subject = "Megastars"
# e.title # => "Megastars"
def alias_attribute(new_name, old_name)
+ # The following reader methods use an explicit `self` receiver in order to
+ # support aliases that start with an uppercase letter. Otherwise, they would
+ # be resolved as constants instead.
module_eval <<-STR, __FILE__, __LINE__ + 1
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
diff --git a/activesupport/lib/active_support/core_ext/module/anonymous.rb b/activesupport/lib/active_support/core_ext/module/anonymous.rb
index 510c9a5430..d1c86b8722 100644
--- a/activesupport/lib/active_support/core_ext/module/anonymous.rb
+++ b/activesupport/lib/active_support/core_ext/module/anonymous.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Module
# A module may or may not have a name.
#
diff --git a/activesupport/lib/active_support/core_ext/module/attr_internal.rb b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
index 93fb598650..7801f6d181 100644
--- a/activesupport/lib/active_support/core_ext/module/attr_internal.rb
+++ b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
@@ -1,12 +1,14 @@
+# frozen_string_literal: true
+
class Module
# Declares an attribute reader backed by an internally-named instance variable.
def attr_internal_reader(*attrs)
- attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
+ attrs.each { |attr_name| attr_internal_define(attr_name, :reader) }
end
# Declares an attribute writer backed by an internally-named instance variable.
def attr_internal_writer(*attrs)
- attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
+ attrs.each { |attr_name| attr_internal_define(attr_name, :writer) }
end
# Declares an attribute reader and writer backed by an internally-named instance
@@ -18,7 +20,7 @@ class Module
alias_method :attr_internal, :attr_internal_accessor
class << self; attr_accessor :attr_internal_naming_format end
- self.attr_internal_naming_format = '@_%s'
+ self.attr_internal_naming_format = "@_%s"
private
def attr_internal_ivar_name(attr)
@@ -26,7 +28,7 @@ class Module
end
def attr_internal_define(attr_name, type)
- internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
+ internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, "")
# use native attr_* methods as they are faster on some Ruby implementations
send("attr_#{type}", internal_name)
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
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 567ac825e9..580baffa2b 100644
--- a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
@@ -1,4 +1,7 @@
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "active_support/core_ext/array/extract_options"
+require "active_support/core_ext/regexp"
# Extends the module object with class/module and instance accessors for
# class/module attributes, just like the native attr* accessors for instance
@@ -6,7 +9,8 @@ require 'active_support/core_ext/array/extract_options'
class Module
# Defines a class attribute and creates a class and instance reader methods.
# The underlying class variable is set to +nil+, if it is not previously
- # defined.
+ # defined. All class and instance methods created will be public, even if
+ # this method is called with a private or protected access modifier.
#
# module HairColors
# mattr_reader :hair_colors
@@ -36,13 +40,10 @@ class Module
#
# Person.new.hair_colors # => NoMethodError
#
- #
- # Also, you can pass a block to set up the attribute with a default value.
+ # You can set a default value for the attribute.
#
# module HairColors
- # mattr_reader :hair_colors do
- # [:brown, :black, :blonde, :red]
- # end
+ # mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red]
# end
#
# class Person
@@ -50,10 +51,9 @@ class Module
# end
#
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
- def mattr_reader(*syms)
- options = syms.extract_options!
+ def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
syms.each do |sym|
- raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /\A[_A-Za-z]\w*\z/
+ raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym)
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@#{sym} = nil unless defined? @@#{sym}
@@ -62,20 +62,24 @@ class Module
end
EOS
- unless options[:instance_reader] == false || options[:instance_accessor] == false
+ if instance_reader && instance_accessor
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
@@#{sym}
end
EOS
end
- class_variable_set("@@#{sym}", yield) if block_given?
+
+ sym_default_value = (block_given? && default.nil?) ? yield : default
+ class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil?
end
end
alias :cattr_reader :mattr_reader
# Defines a class attribute and creates a class and instance writer methods to
- # allow assignment to the attribute.
+ # allow assignment to the attribute. All class and instance methods created
+ # will be public, even if this method is called with a private or protected
+ # access modifier.
#
# module HairColors
# mattr_writer :hair_colors
@@ -103,12 +107,10 @@ class Module
#
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
#
- # Also, you can pass a block to set up the attribute with a default value.
+ # You can set a default value for the attribute.
#
# module HairColors
- # mattr_writer :hair_colors do
- # [:brown, :black, :blonde, :red]
- # end
+ # mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red]
# end
#
# class Person
@@ -116,10 +118,9 @@ class Module
# end
#
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
- def mattr_writer(*syms)
- options = syms.extract_options!
+ def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil)
syms.each do |sym|
- raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /\A[_A-Za-z]\w*\z/
+ raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym)
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@#{sym} = nil unless defined? @@#{sym}
@@ -128,19 +129,23 @@ class Module
end
EOS
- unless options[:instance_writer] == false || options[:instance_accessor] == false
+ if instance_writer && instance_accessor
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}=(obj)
@@#{sym} = obj
end
EOS
end
- send("#{sym}=", yield) if block_given?
+
+ sym_default_value = (block_given? && default.nil?) ? yield : default
+ send("#{sym}=", sym_default_value) unless sym_default_value.nil?
end
end
alias :cattr_writer :mattr_writer
# Defines both class and instance accessors for class attributes.
+ # All class and instance methods created will be public, even if
+ # this method is called with a private or protected access modifier.
#
# module HairColors
# mattr_accessor :hair_colors
@@ -191,12 +196,10 @@ class Module
# Person.new.hair_colors = [:brown] # => NoMethodError
# Person.new.hair_colors # => NoMethodError
#
- # Also you can pass a block to set up the attribute with a default value.
+ # You can set a default value for the attribute.
#
# module HairColors
- # mattr_accessor :hair_colors do
- # [:brown, :black, :blonde, :red]
- # end
+ # mattr_accessor :hair_colors, default: [:brown, :black, :blonde, :red]
# end
#
# class Person
@@ -204,9 +207,9 @@ class Module
# end
#
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
- def mattr_accessor(*syms, &blk)
- mattr_reader(*syms, &blk)
- mattr_writer(*syms)
+ def mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
+ mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default, &blk)
+ mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor, default: default)
end
alias :cattr_accessor :mattr_accessor
end
diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
index 0b3d18301e..4b9b6ea9bd 100644
--- a/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
@@ -1,9 +1,12 @@
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "active_support/core_ext/array/extract_options"
+require "active_support/core_ext/regexp"
# Extends the module object with class/module and instance accessors for
# class/module attributes, just like the native attr* accessors for instance
# attributes, but does so on a per-thread basis.
-#
+#
# So the values are scoped within the Thread.current space under the class name
# of the module.
class Module
@@ -25,7 +28,7 @@ class Module
# end
# # => NameError: invalid attribute name: 1_Badname
#
- # If you want to opt out the creation on the instance reader method, pass
+ # If you want to opt out of the creation of the instance reader method, pass
# <tt>instance_reader: false</tt> or <tt>instance_accessor: false</tt>.
#
# class Current
@@ -33,21 +36,24 @@ class Module
# end
#
# Current.new.user # => NoMethodError
- def thread_mattr_reader(*syms)
+ def thread_mattr_reader(*syms) # :nodoc:
options = syms.extract_options!
syms.each do |sym|
- raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym)
+
+ # The following generated method concatenates `name` because we want it
+ # to work with inheritance via polymorphism.
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def self.#{sym}
- Thread.current[:"attr_#{name}_#{sym}"]
+ Thread.current["attr_" + name + "_#{sym}"]
end
EOS
unless options[:instance_reader] == false || options[:instance_accessor] == false
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
- Thread.current[:"attr_#{name}_#{sym}"]
+ self.class.#{sym}
end
EOS
end
@@ -65,7 +71,7 @@ class Module
# Current.user = "DHH"
# Thread.current[:attr_Current_user] # => "DHH"
#
- # If you want to opt out the instance writer method, pass
+ # If you want to opt out of the creation of the instance writer method, pass
# <tt>instance_writer: false</tt> or <tt>instance_accessor: false</tt>.
#
# class Current
@@ -73,20 +79,23 @@ class Module
# end
#
# Current.new.user = "DHH" # => NoMethodError
- def thread_mattr_writer(*syms)
+ def thread_mattr_writer(*syms) # :nodoc:
options = syms.extract_options!
syms.each do |sym|
- raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym)
+
+ # The following generated method concatenates `name` because we want it
+ # to work with inheritance via polymorphism.
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def self.#{sym}=(obj)
- Thread.current[:"attr_#{name}_#{sym}"] = obj
+ Thread.current["attr_" + name + "_#{sym}"] = obj
end
EOS
unless options[:instance_writer] == false || options[:instance_accessor] == false
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}=(obj)
- Thread.current[:"attr_#{name}_#{sym}"] = obj
+ self.class.#{sym} = obj
end
EOS
end
@@ -133,9 +142,9 @@ class Module
#
# Current.new.user = "DHH" # => NoMethodError
# Current.new.user # => NoMethodError
- def thread_mattr_accessor(*syms, &blk)
- thread_mattr_reader(*syms, &blk)
- thread_mattr_writer(*syms, &blk)
+ def thread_mattr_accessor(*syms)
+ thread_mattr_reader(*syms)
+ thread_mattr_writer(*syms)
end
alias :thread_cattr_accessor :thread_mattr_accessor
end
diff --git a/activesupport/lib/active_support/core_ext/module/concerning.rb b/activesupport/lib/active_support/core_ext/module/concerning.rb
index 65b88b9bbd..7bbbf321ab 100644
--- a/activesupport/lib/active_support/core_ext/module/concerning.rb
+++ b/activesupport/lib/active_support/core_ext/module/concerning.rb
@@ -1,4 +1,6 @@
-require 'active_support/concern'
+# frozen_string_literal: true
+
+require "active_support/concern"
class Module
# = Bite-sized separation of concerns
@@ -20,7 +22,7 @@ class Module
#
# == Using comments:
#
- # class Todo
+ # class Todo < ApplicationRecord
# # Other todo implementation
# # ...
#
@@ -28,7 +30,6 @@ class Module
# has_many :events
#
# before_create :track_creation
- # after_destroy :track_deletion
#
# private
# def track_creation
@@ -40,7 +41,7 @@ class Module
#
# Noisy syntax.
#
- # class Todo
+ # class Todo < ApplicationRecord
# # Other todo implementation
# # ...
#
@@ -50,7 +51,6 @@ class Module
# included do
# has_many :events
# before_create :track_creation
- # after_destroy :track_deletion
# end
#
# private
@@ -68,7 +68,7 @@ class Module
# increased overhead can be a reasonable tradeoff even if it reduces our
# at-a-glance perception of how things work.
#
- # class Todo
+ # class Todo < ApplicationRecord
# # Other todo implementation
# # ...
#
@@ -80,7 +80,7 @@ class Module
# By quieting the mix-in noise, we arrive at a natural, low-ceremony way to
# separate bite-sized concerns.
#
- # class Todo
+ # class Todo < ApplicationRecord
# # Other todo implementation
# # ...
#
@@ -88,7 +88,6 @@ class Module
# included do
# has_many :events
# before_create :track_creation
- # after_destroy :track_deletion
# end
#
# private
@@ -99,7 +98,7 @@ class Module
# end
#
# Todo.ancestors
- # # => [Todo, Todo::EventTracking, Object]
+ # # => [Todo, Todo::EventTracking, ApplicationRecord, Object]
#
# This small step has some wonderful ripple effects. We can
# * grok the behavior of our class in one glance,
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 24450cd221..4310df3024 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -1,15 +1,19 @@
-require 'set'
+# frozen_string_literal: true
+
+require "set"
+require "active_support/core_ext/regexp"
class Module
# Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+
# option is not used.
class DelegationError < NoMethodError; end
+ RUBY_RESERVED_KEYWORDS = %w(alias and BEGIN begin break case class def defined? do
+ else elsif END end ensure false for if in module next nil not or redo rescue retry
+ return self super then true undef unless until when while yield)
+ DELEGATION_RESERVED_KEYWORDS = %w(_ arg args block)
DELEGATION_RESERVED_METHOD_NAMES = Set.new(
- %w(_ arg args alias and BEGIN begin block break case class def defined? do
- else elsif END end ensure false for if in module next nil not or redo
- rescue retry return self super then true undef unless until when while
- yield)
+ RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS
).freeze
# Provides a +delegate+ class method to easily expose contained objects'
@@ -18,7 +22,8 @@ class Module
# ==== Options
# * <tt>:to</tt> - Specifies the target object
# * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
- # * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ from being raised
+ # * <tt>:allow_nil</tt> - if set to true, prevents a +Module::DelegationError+
+ # from being raised
#
# The macro receives one or more method names (specified as symbols or
# strings) and the name of the target object via the <tt>:to</tt> option
@@ -110,18 +115,16 @@ class Module
# invoice.customer_address # => 'Vimmersvej 13'
#
# If the target is +nil+ and does not respond to the delegated method a
- # +NoMethodError+ is raised, as with any other value. Sometimes, however, it
- # makes sense to be robust to that situation and that is the purpose of the
- # <tt>:allow_nil</tt> option: If the target is not +nil+, or it is and
- # responds to the method, everything works as usual. But if it is +nil+ and
- # does not respond to the delegated method, +nil+ is returned.
+ # +Module::DelegationError+ is raised. If you wish to instead return +nil+,
+ # use the <tt>:allow_nil</tt> option.
#
# class User < ActiveRecord::Base
# has_one :profile
# delegate :age, to: :profile
# end
#
- # User.new.age # raises NoMethodError: undefined method `age'
+ # User.new.age
+ # # => Module::DelegationError: User#age delegated to profile.age, but profile is nil
#
# But if not having a profile yet is fine and should not be an error
# condition:
@@ -148,33 +151,32 @@ class Module
# Foo.new("Bar").name # raises NoMethodError: undefined method `name'
#
# The target method must be public, otherwise it will raise +NoMethodError+.
- #
def delegate(*methods, to: nil, prefix: nil, allow_nil: nil)
unless to
- raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
+ raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter)."
end
- if prefix == true && to =~ /^[^a-z_]/
- raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
+ if prefix == true && /^[^a-z_]/.match?(to)
+ raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
end
method_prefix = \
if prefix
"#{prefix == true ? to : prefix}_"
else
- ''
+ ""
end
- file, line = caller(1, 1).first.split(':'.freeze, 2)
- line = line.to_i
+ location = caller_locations(1, 1).first
+ file, line = location.path, location.lineno
to = to.to_s
to = "self.#{to}" if DELEGATION_RESERVED_METHOD_NAMES.include?(to)
- methods.each do |method|
+ methods.map do |method|
# Attribute writer methods only accept one argument. Makes sure []=
# methods still accept two arguments.
- definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
+ definition = /[^\]]=$/.match?(method) ? "arg" : "*args, &block"
# The following generated method calls the target exactly once, storing
# the returned value in a dummy variable.
@@ -191,7 +193,7 @@ class Module
" _.#{method}(#{definition})",
"end",
"end"
- ].join ';'
+ ].join ";"
else
exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
@@ -206,10 +208,80 @@ class Module
" raise",
" end",
"end"
- ].join ';'
+ ].join ";"
end
module_eval(method_def, file, line)
end
end
+
+ # When building decorators, a common pattern may emerge:
+ #
+ # class Partition
+ # def initialize(event)
+ # @event = event
+ # end
+ #
+ # def person
+ # @event.detail.person || @event.creator
+ # end
+ #
+ # private
+ # def respond_to_missing?(name, include_private = false)
+ # @event.respond_to?(name, include_private)
+ # end
+ #
+ # def method_missing(method, *args, &block)
+ # @event.send(method, *args, &block)
+ # end
+ # end
+ #
+ # With <tt>Module#delegate_missing_to</tt>, the above is condensed to:
+ #
+ # class Partition
+ # delegate_missing_to :@event
+ #
+ # def initialize(event)
+ # @event = event
+ # end
+ #
+ # def person
+ # @event.detail.person || @event.creator
+ # end
+ # end
+ #
+ # The target can be anything callable within the object, e.g. instance
+ # variables, methods, constants, etc.
+ #
+ # The delegated method must be public on the target, otherwise it will
+ # raise +NoMethodError+.
+ def delegate_missing_to(target)
+ target = target.to_s
+ target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target)
+
+ module_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def respond_to_missing?(name, include_private = false)
+ # It may look like an oversight, but we deliberately do not pass
+ # +include_private+, because they do not get delegated.
+
+ #{target}.respond_to?(name) || super
+ end
+
+ def method_missing(method, *args, &block)
+ if #{target}.respond_to?(method)
+ #{target}.public_send(method, *args, &block)
+ else
+ begin
+ super
+ rescue NoMethodError
+ if #{target}.nil?
+ raise DelegationError, "\#{method} delegated to #{target}, but #{target} is nil"
+ else
+ raise
+ end
+ end
+ end
+ end
+ RUBY
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/module/deprecation.rb b/activesupport/lib/active_support/core_ext/module/deprecation.rb
index f3f2e7f5fc..71c42eb357 100644
--- a/activesupport/lib/active_support/core_ext/module/deprecation.rb
+++ b/activesupport/lib/active_support/core_ext/module/deprecation.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Module
# deprecate :foo
# deprecate bar: 'message'
diff --git a/activesupport/lib/active_support/core_ext/module/introspection.rb b/activesupport/lib/active_support/core_ext/module/introspection.rb
index fa692e1b0e..c5bb598bd1 100644
--- a/activesupport/lib/active_support/core_ext/module/introspection.rb
+++ b/activesupport/lib/active_support/core_ext/module/introspection.rb
@@ -1,14 +1,18 @@
-require 'active_support/inflector'
+# frozen_string_literal: true
+
+require "active_support/inflector"
class Module
# Returns the name of the module containing this one.
#
# M::N.parent_name # => "M"
def parent_name
- if defined? @parent_name
+ if defined?(@parent_name)
@parent_name
else
- @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
+ parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
+ @parent_name = parent_name unless frozen?
+ parent_name
end
end
@@ -46,21 +50,13 @@ class Module
def parents
parents = []
if parent_name
- parts = parent_name.split('::')
+ parts = parent_name.split("::")
until parts.empty?
- parents << ActiveSupport::Inflector.constantize(parts * '::')
+ parents << ActiveSupport::Inflector.constantize(parts * "::")
parts.pop
end
end
parents << Object unless parents.include? Object
parents
end
-
- def local_constants #:nodoc:
- ActiveSupport::Deprecation.warn(<<-MSG.squish)
- Module#local_constants is deprecated and will be removed in Rails 5.1.
- Use Module#constants(false) instead.
- MSG
- constants(false)
- end
end
diff --git a/activesupport/lib/active_support/core_ext/module/method_transplanting.rb b/activesupport/lib/active_support/core_ext/module/method_transplanting.rb
deleted file mode 100644
index 1fde3db070..0000000000
--- a/activesupport/lib/active_support/core_ext/module/method_transplanting.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("This file is deprecated and will be removed in Rails 5.1 with no replacement.")
diff --git a/activesupport/lib/active_support/core_ext/module/qualified_const.rb b/activesupport/lib/active_support/core_ext/module/qualified_const.rb
deleted file mode 100644
index 3ea39d4267..0000000000
--- a/activesupport/lib/active_support/core_ext/module/qualified_const.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-require 'active_support/core_ext/string/inflections'
-
-#--
-# Allows code reuse in the methods below without polluting Module.
-#++
-
-module ActiveSupport
- module QualifiedConstUtils
- def self.raise_if_absolute(path)
- raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
- end
-
- def self.names(path)
- path.split('::')
- end
- end
-end
-
-##
-# Extends the API for constants to be able to deal with qualified names. Arguments
-# are assumed to be relative to the receiver.
-#
-#--
-# Qualified names are required to be relative because we are extending existing
-# methods that expect constant names, ie, relative paths of length 1. For example,
-# Object.const_get('::String') raises NameError and so does qualified_const_get.
-#++
-class Module
- def qualified_const_defined?(path, search_parents=true)
- ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
- Module#qualified_const_defined? is deprecated in favour of the builtin
- Module#const_defined? and will be removed in Rails 5.1.
- MESSAGE
-
- ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)
-
- ActiveSupport::QualifiedConstUtils.names(path).inject(self) do |mod, name|
- return unless mod.const_defined?(name, search_parents)
- mod.const_get(name)
- end
- return true
- end
-
- def qualified_const_get(path)
- ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
- Module#qualified_const_get is deprecated in favour of the builtin
- Module#const_get and will be removed in Rails 5.1.
- MESSAGE
-
- ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)
-
- ActiveSupport::QualifiedConstUtils.names(path).inject(self) do |mod, name|
- mod.const_get(name)
- end
- end
-
- def qualified_const_set(path, value)
- ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
- Module#qualified_const_set is deprecated in favour of the builtin
- Module#const_set and will be removed in Rails 5.1.
- MESSAGE
-
- ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)
-
- const_name = path.demodulize
- mod_name = path.deconstantize
- mod = mod_name.empty? ? self : const_get(mod_name)
- mod.const_set(const_name, value)
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/module/reachable.rb b/activesupport/lib/active_support/core_ext/module/reachable.rb
index 5d3d0e9851..e9cbda5245 100644
--- a/activesupport/lib/active_support/core_ext/module/reachable.rb
+++ b/activesupport/lib/active_support/core_ext/module/reachable.rb
@@ -1,8 +1,11 @@
-require 'active_support/core_ext/module/anonymous'
-require 'active_support/core_ext/string/inflections'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/anonymous"
+require "active_support/core_ext/string/inflections"
class Module
def reachable? #:nodoc:
!anonymous? && name.safe_constantize.equal?(self)
end
+ deprecate :reachable?
end
diff --git a/activesupport/lib/active_support/core_ext/module/redefine_method.rb b/activesupport/lib/active_support/core_ext/module/redefine_method.rb
new file mode 100644
index 0000000000..a0a6622ca4
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/redefine_method.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+class Module
+ if RUBY_VERSION >= "2.3"
+ # Marks the named method as intended to be redefined, if it exists.
+ # Suppresses the Ruby method redefinition warning. Prefer
+ # #redefine_method where possible.
+ def silence_redefinition_of_method(method)
+ if method_defined?(method) || private_method_defined?(method)
+ # This suppresses the "method redefined" warning; the self-alias
+ # looks odd, but means we don't need to generate a unique name
+ alias_method method, method
+ end
+ end
+ else
+ def silence_redefinition_of_method(method)
+ if method_defined?(method) || private_method_defined?(method)
+ alias_method :__rails_redefine, method
+ remove_method :__rails_redefine
+ end
+ end
+ end
+
+ # Replaces the existing method definition, if there is one, with the passed
+ # block as its body.
+ def redefine_method(method, &block)
+ visibility = method_visibility(method)
+ silence_redefinition_of_method(method)
+ define_method(method, &block)
+ send(visibility, method)
+ end
+
+ # Replaces the existing singleton method definition, if there is one, with
+ # the passed block as its body.
+ def redefine_singleton_method(method, &block)
+ singleton_class.redefine_method(method, &block)
+ end
+
+ def method_visibility(method) # :nodoc:
+ case
+ when private_method_defined?(method)
+ :private
+ when protected_method_defined?(method)
+ :protected
+ else
+ :public
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/remove_method.rb b/activesupport/lib/active_support/core_ext/module/remove_method.rb
index d5ec16d68a..97eb5f9eca 100644
--- a/activesupport/lib/active_support/core_ext/module/remove_method.rb
+++ b/activesupport/lib/active_support/core_ext/module/remove_method.rb
@@ -1,3 +1,7 @@
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/redefine_method"
+
class Module
# Removes the named method, if it exists.
def remove_possible_method(method)
@@ -8,28 +12,6 @@ class Module
# Removes the named singleton method, if it exists.
def remove_possible_singleton_method(method)
- singleton_class.instance_eval do
- remove_possible_method(method)
- end
- end
-
- # Replaces the existing method definition, if there is one, with the passed
- # block as its body.
- def redefine_method(method, &block)
- visibility = method_visibility(method)
- remove_possible_method(method)
- define_method(method, &block)
- send(visibility, method)
- end
-
- def method_visibility(method) # :nodoc:
- case
- when private_method_defined?(method)
- :private
- when protected_method_defined?(method)
- :protected
- else
- :public
- end
+ singleton_class.remove_possible_method(method)
end
end
diff --git a/activesupport/lib/active_support/core_ext/name_error.rb b/activesupport/lib/active_support/core_ext/name_error.rb
index 6b447d772b..6d37cd9dfd 100644
--- a/activesupport/lib/active_support/core_ext/name_error.rb
+++ b/activesupport/lib/active_support/core_ext/name_error.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class NameError
# Extract the name of the missing constant from the exception message.
#
@@ -8,6 +10,11 @@ class NameError
# end
# # => "HelloWorld"
def missing_name
+ # Since ruby v2.3.0 `did_you_mean` gem is loaded by default.
+ # It extends NameError#message with spell corrections which are SLOW.
+ # We should use original_message message instead.
+ message = respond_to?(:original_message) ? original_message : self.message
+
if /undefined local variable or method/ !~ message
$1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
end
diff --git a/activesupport/lib/active_support/core_ext/numeric.rb b/activesupport/lib/active_support/core_ext/numeric.rb
index bcdc3eace2..0b04e359f9 100644
--- a/activesupport/lib/active_support/core_ext/numeric.rb
+++ b/activesupport/lib/active_support/core_ext/numeric.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/numeric/bytes'
-require 'active_support/core_ext/numeric/time'
-require 'active_support/core_ext/numeric/inquiry'
-require 'active_support/core_ext/numeric/conversions'
+# frozen_string_literal: true
+
+require "active_support/core_ext/numeric/bytes"
+require "active_support/core_ext/numeric/time"
+require "active_support/core_ext/numeric/inquiry"
+require "active_support/core_ext/numeric/conversions"
diff --git a/activesupport/lib/active_support/core_ext/numeric/bytes.rb b/activesupport/lib/active_support/core_ext/numeric/bytes.rb
index dfbca32474..b002eba406 100644
--- a/activesupport/lib/active_support/core_ext/numeric/bytes.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/bytes.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Numeric
KILOBYTE = 1024
MEGABYTE = KILOBYTE * 1024
diff --git a/activesupport/lib/active_support/core_ext/numeric/conversions.rb b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
index b25925b9d4..f6c2713986 100644
--- a/activesupport/lib/active_support/core_ext/numeric/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
@@ -1,9 +1,10 @@
-require 'active_support/core_ext/big_decimal/conversions'
-require 'active_support/number_helper'
-require 'active_support/core_ext/module/deprecation'
+# frozen_string_literal: true
-module ActiveSupport::NumericWithFormat
+require "active_support/core_ext/big_decimal/conversions"
+require "active_support/number_helper"
+require "active_support/core_ext/module/deprecation"
+module ActiveSupport::NumericWithFormat
# Provides options for converting numbers into formatted strings.
# Options are provided for phone numbers, currency, percentage,
# precision, positional notation, file size and pretty printing.
@@ -100,40 +101,40 @@ module ActiveSupport::NumericWithFormat
# 1234567.to_s(:human, precision: 1,
# separator: ',',
# significant: false) # => "1,2 Million"
- def to_s(*args)
- format, options = args
- options ||= {}
-
+ def to_s(format = nil, options = nil)
case format
+ when nil
+ super()
+ when Integer, String
+ super(format)
when :phone
- return ActiveSupport::NumberHelper.number_to_phone(self, options)
+ ActiveSupport::NumberHelper.number_to_phone(self, options || {})
when :currency
- return ActiveSupport::NumberHelper.number_to_currency(self, options)
+ ActiveSupport::NumberHelper.number_to_currency(self, options || {})
when :percentage
- return ActiveSupport::NumberHelper.number_to_percentage(self, options)
+ ActiveSupport::NumberHelper.number_to_percentage(self, options || {})
when :delimited
- return ActiveSupport::NumberHelper.number_to_delimited(self, options)
+ ActiveSupport::NumberHelper.number_to_delimited(self, options || {})
when :rounded
- return ActiveSupport::NumberHelper.number_to_rounded(self, options)
+ ActiveSupport::NumberHelper.number_to_rounded(self, options || {})
when :human
- return ActiveSupport::NumberHelper.number_to_human(self, options)
+ ActiveSupport::NumberHelper.number_to_human(self, options || {})
when :human_size
- return ActiveSupport::NumberHelper.number_to_human_size(self, options)
+ ActiveSupport::NumberHelper.number_to_human_size(self, options || {})
+ when Symbol
+ super()
else
- if is_a?(Float) || format.is_a?(Symbol)
- super()
- else
- super
- end
+ super(format)
end
end
-
- def to_formatted_s(*args)
- to_s(*args)
- end
- deprecate to_formatted_s: :to_s
end
-[Fixnum, Bignum, Float, BigDecimal].each do |klass|
- klass.prepend(ActiveSupport::NumericWithFormat)
+# Ruby 2.4+ unifies Fixnum & Bignum into Integer.
+if 0.class == Integer
+ Integer.prepend ActiveSupport::NumericWithFormat
+else
+ Fixnum.prepend ActiveSupport::NumericWithFormat
+ Bignum.prepend ActiveSupport::NumericWithFormat
end
+Float.prepend ActiveSupport::NumericWithFormat
+BigDecimal.prepend ActiveSupport::NumericWithFormat
diff --git a/activesupport/lib/active_support/core_ext/numeric/inquiry.rb b/activesupport/lib/active_support/core_ext/numeric/inquiry.rb
index 7e7ac1b0b2..15334c91f1 100644
--- a/activesupport/lib/active_support/core_ext/numeric/inquiry.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/inquiry.rb
@@ -1,26 +1,28 @@
+# frozen_string_literal: true
+
unless 1.respond_to?(:positive?) # TODO: Remove this file when we drop support to ruby < 2.3
-class Numeric
- # Returns true if the number is positive.
- #
- # 1.positive? # => true
- # 0.positive? # => false
- # -1.positive? # => false
- def positive?
- self > 0
- end
+ class Numeric
+ # Returns true if the number is positive.
+ #
+ # 1.positive? # => true
+ # 0.positive? # => false
+ # -1.positive? # => false
+ def positive?
+ self > 0
+ end
- # Returns true if the number is negative.
- #
- # -1.negative? # => true
- # 0.negative? # => false
- # 1.negative? # => false
- def negative?
- self < 0
+ # Returns true if the number is negative.
+ #
+ # -1.negative? # => true
+ # 0.negative? # => false
+ # 1.negative? # => false
+ def negative?
+ self < 0
+ end
end
-end
-class Complex
- undef :positive?
- undef :negative?
-end
+ class Complex
+ undef :positive?
+ undef :negative?
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/numeric/time.rb b/activesupport/lib/active_support/core_ext/numeric/time.rb
index c6ece22f8d..bc4627f7a2 100644
--- a/activesupport/lib/active_support/core_ext/numeric/time.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/time.rb
@@ -1,25 +1,17 @@
-require 'active_support/duration'
-require 'active_support/core_ext/time/calculations'
-require 'active_support/core_ext/time/acts_like'
-require 'active_support/core_ext/date/calculations'
-require 'active_support/core_ext/date/acts_like'
+# frozen_string_literal: true
+
+require "active_support/duration"
+require "active_support/core_ext/time/calculations"
+require "active_support/core_ext/time/acts_like"
+require "active_support/core_ext/date/calculations"
+require "active_support/core_ext/date/acts_like"
class Numeric
- # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
- #
- # These methods use Time#advance for precise date calculations when using from_now, ago, etc.
- # as well as adding or subtracting their results from a Time object. For example:
- #
- # # equivalent to Time.current.advance(months: 1)
- # 1.month.from_now
- #
- # # equivalent to Time.current.advance(years: 2)
- # 2.years.from_now
+ # Returns a Duration instance matching the number of seconds provided.
#
- # # equivalent to Time.current.advance(months: 4, years: 5)
- # (4.months + 5.years).from_now
+ # 2.seconds # => 2 seconds
def seconds
- ActiveSupport::Duration.new(self, [[:seconds, self]])
+ ActiveSupport::Duration.seconds(self)
end
alias :second :seconds
@@ -27,7 +19,7 @@ class Numeric
#
# 2.minutes # => 2 minutes
def minutes
- ActiveSupport::Duration.new(self * 60, [[:minutes, self]])
+ ActiveSupport::Duration.minutes(self)
end
alias :minute :minutes
@@ -35,7 +27,7 @@ class Numeric
#
# 2.hours # => 2 hours
def hours
- ActiveSupport::Duration.new(self * 3600, [[:hours, self]])
+ ActiveSupport::Duration.hours(self)
end
alias :hour :hours
@@ -43,7 +35,7 @@ class Numeric
#
# 2.days # => 2 days
def days
- ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
+ ActiveSupport::Duration.days(self)
end
alias :day :days
@@ -51,7 +43,7 @@ class Numeric
#
# 2.weeks # => 2 weeks
def weeks
- ActiveSupport::Duration.new(self * 7.days, [[:weeks, self]])
+ ActiveSupport::Duration.weeks(self)
end
alias :week :weeks
@@ -59,15 +51,15 @@ class Numeric
#
# 2.fortnights # => 4 weeks
def fortnights
- ActiveSupport::Duration.new(self * 2.weeks, [[:weeks, self * 2]])
+ ActiveSupport::Duration.weeks(self * 2)
end
alias :fortnight :fortnights
# Returns the number of milliseconds equivalent to the seconds provided.
- # Used with the standard time durations, like 1.hour.in_milliseconds --
- # so we can feed them to JavaScript functions like getTime().
+ # Used with the standard time durations.
#
- # 2.in_milliseconds # => 2_000
+ # 2.in_milliseconds # => 2000
+ # 1.hour.in_milliseconds # => 3600000
def in_milliseconds
self * 1000
end
diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb
index f4f9152d6a..efd34cc692 100644
--- a/activesupport/lib/active_support/core_ext/object.rb
+++ b/activesupport/lib/active_support/core_ext/object.rb
@@ -1,14 +1,16 @@
-require 'active_support/core_ext/object/acts_like'
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/object/duplicable'
-require 'active_support/core_ext/object/deep_dup'
-require 'active_support/core_ext/object/try'
-require 'active_support/core_ext/object/inclusion'
+# frozen_string_literal: true
-require 'active_support/core_ext/object/conversions'
-require 'active_support/core_ext/object/instance_variables'
+require "active_support/core_ext/object/acts_like"
+require "active_support/core_ext/object/blank"
+require "active_support/core_ext/object/duplicable"
+require "active_support/core_ext/object/deep_dup"
+require "active_support/core_ext/object/try"
+require "active_support/core_ext/object/inclusion"
-require 'active_support/core_ext/object/json'
-require 'active_support/core_ext/object/to_param'
-require 'active_support/core_ext/object/to_query'
-require 'active_support/core_ext/object/with_options'
+require "active_support/core_ext/object/conversions"
+require "active_support/core_ext/object/instance_variables"
+
+require "active_support/core_ext/object/json"
+require "active_support/core_ext/object/to_param"
+require "active_support/core_ext/object/to_query"
+require "active_support/core_ext/object/with_options"
diff --git a/activesupport/lib/active_support/core_ext/object/acts_like.rb b/activesupport/lib/active_support/core_ext/object/acts_like.rb
index 3912cc5ace..403ee20e39 100644
--- a/activesupport/lib/active_support/core_ext/object/acts_like.rb
+++ b/activesupport/lib/active_support/core_ext/object/acts_like.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Object
# A duck-type assistant method. For example, Active Support extends Date
# to define an <tt>acts_like_date?</tt> method, and extends Time to define
@@ -5,6 +7,15 @@ class Object
# <tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that
# we want to act like Time simply need to define an <tt>acts_like_time?</tt> method.
def acts_like?(duck)
- respond_to? :"acts_like_#{duck}?"
+ case duck
+ when :time
+ respond_to? :acts_like_time?
+ when :date
+ respond_to? :acts_like_date?
+ when :string
+ respond_to? :acts_like_string?
+ else
+ respond_to? :"acts_like_#{duck}?"
+ end
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb
index cb74bad73e..2ca431ab10 100644
--- a/activesupport/lib/active_support/core_ext/object/blank.rb
+++ b/activesupport/lib/active_support/core_ext/object/blank.rb
@@ -1,3 +1,8 @@
+# frozen_string_literal: true
+
+require "active_support/core_ext/regexp"
+require "concurrent/map"
+
class Object
# An object is blank if it's false, empty, or a whitespace string.
# For example, +false+, '', ' ', +nil+, [], and {} are all blank.
@@ -98,6 +103,9 @@ end
class String
BLANK_RE = /\A[[:space:]]*\z/
+ ENCODED_BLANKS = Concurrent::Map.new do |h, enc|
+ h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING)
+ end
# A string is blank if it's empty or contains whitespaces only:
#
@@ -115,7 +123,12 @@ class String
# The regexp that matches blank strings is expensive. For the case of empty
# strings we can speed up this method (~3.5x) with an empty? call. The
# penalty for the rest of strings is marginal.
- empty? || BLANK_RE === self
+ empty? ||
+ begin
+ BLANK_RE.match?(self)
+ rescue Encoding::CompatibilityError
+ ENCODED_BLANKS[self.encoding].match?(self)
+ end
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/conversions.rb b/activesupport/lib/active_support/core_ext/object/conversions.rb
index 540f7aadb0..624fb8d77c 100644
--- a/activesupport/lib/active_support/core_ext/object/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/object/conversions.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/object/to_param'
-require 'active_support/core_ext/object/to_query'
-require 'active_support/core_ext/array/conversions'
-require 'active_support/core_ext/hash/conversions'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/to_param"
+require "active_support/core_ext/object/to_query"
+require "active_support/core_ext/array/conversions"
+require "active_support/core_ext/hash/conversions"
diff --git a/activesupport/lib/active_support/core_ext/object/deep_dup.rb b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
index 8dfeed0066..c66c5eb2d9 100644
--- a/activesupport/lib/active_support/core_ext/object/deep_dup.rb
+++ b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/object/duplicable'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/duplicable"
class Object
# Returns a deep copy of object if it's duplicable. If it's
diff --git a/activesupport/lib/active_support/core_ext/object/duplicable.rb b/activesupport/lib/active_support/core_ext/object/duplicable.rb
index befa5aee21..9bb99087bc 100644
--- a/activesupport/lib/active_support/core_ext/object/duplicable.rb
+++ b/activesupport/lib/active_support/core_ext/object/duplicable.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
#--
-# Most objects are cloneable, but not all. For example you can't dup +nil+:
+# Most objects are cloneable, but not all. For example you can't dup methods:
#
-# nil.dup # => TypeError: can't dup NilClass
+# method(:puts).dup # => TypeError: allocator undefined for Method
#
# Classes may signal their instances are not duplicable removing +dup+/+clone+
# or raising exceptions from them. So, to dup an arbitrary object you normally
@@ -19,7 +21,7 @@
class Object
# Can you safely dup this object?
#
- # False for +nil+, +false+, +true+, symbol, number, method objects;
+ # False for method objects;
# true otherwise.
def duplicable?
true
@@ -27,61 +29,87 @@ class Object
end
class NilClass
- # +nil+ is not duplicable:
- #
- # nil.duplicable? # => false
- # nil.dup # => TypeError: can't dup NilClass
- def duplicable?
- false
+ begin
+ nil.dup
+ rescue TypeError
+
+ # +nil+ is not duplicable:
+ #
+ # nil.duplicable? # => false
+ # nil.dup # => TypeError: can't dup NilClass
+ def duplicable?
+ false
+ end
end
end
class FalseClass
- # +false+ is not duplicable:
- #
- # false.duplicable? # => false
- # false.dup # => TypeError: can't dup FalseClass
- def duplicable?
- false
+ begin
+ false.dup
+ rescue TypeError
+
+ # +false+ is not duplicable:
+ #
+ # false.duplicable? # => false
+ # false.dup # => TypeError: can't dup FalseClass
+ def duplicable?
+ false
+ end
end
end
class TrueClass
- # +true+ is not duplicable:
- #
- # true.duplicable? # => false
- # true.dup # => TypeError: can't dup TrueClass
- def duplicable?
- false
+ begin
+ true.dup
+ rescue TypeError
+
+ # +true+ is not duplicable:
+ #
+ # true.duplicable? # => false
+ # true.dup # => TypeError: can't dup TrueClass
+ def duplicable?
+ false
+ end
end
end
class Symbol
- # Symbols are not duplicable:
- #
- # :my_symbol.duplicable? # => false
- # :my_symbol.dup # => TypeError: can't dup Symbol
- def duplicable?
- false
+ begin
+ :symbol.dup # Ruby 2.4.x.
+ "symbol_from_string".to_sym.dup # Some symbols can't `dup` in Ruby 2.4.0.
+ rescue TypeError
+
+ # Symbols are not duplicable:
+ #
+ # :my_symbol.duplicable? # => false
+ # :my_symbol.dup # => TypeError: can't dup Symbol
+ def duplicable?
+ false
+ end
end
end
class Numeric
- # Numbers are not duplicable:
- #
- # 3.duplicable? # => false
- # 3.dup # => TypeError: can't dup Fixnum
- def duplicable?
- false
+ begin
+ 1.dup
+ rescue TypeError
+
+ # Numbers are not duplicable:
+ #
+ # 3.duplicable? # => false
+ # 3.dup # => TypeError: can't dup Integer
+ def duplicable?
+ false
+ end
end
end
-require 'bigdecimal'
+require "bigdecimal"
class BigDecimal
# BigDecimals are duplicable:
#
- # BigDecimal.new("1.2").duplicable? # => true
- # BigDecimal.new("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
+ # BigDecimal("1.2").duplicable? # => true
+ # BigDecimal("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
def duplicable?
true
end
@@ -96,3 +124,33 @@ class Method
false
end
end
+
+class Complex
+ begin
+ Complex(1).dup
+ rescue TypeError
+
+ # Complexes are not duplicable:
+ #
+ # Complex(1).duplicable? # => false
+ # Complex(1).dup # => TypeError: can't copy Complex
+ def duplicable?
+ false
+ end
+ end
+end
+
+class Rational
+ begin
+ Rational(1).dup
+ rescue TypeError
+
+ # Rationals are not duplicable:
+ #
+ # Rational(1).duplicable? # => false
+ # Rational(1).dup # => TypeError: can't copy Rational
+ def duplicable?
+ false
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/inclusion.rb b/activesupport/lib/active_support/core_ext/object/inclusion.rb
index d4c17dfb07..6064e92f20 100644
--- a/activesupport/lib/active_support/core_ext/object/inclusion.rb
+++ b/activesupport/lib/active_support/core_ext/object/inclusion.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Object
# Returns true if this object is included in the argument. Argument must be
# any object which responds to +#include?+. Usage:
@@ -22,6 +24,6 @@ class Object
#
# @return [Object]
def presence_in(another_object)
- self.in?(another_object) ? self : nil
+ in?(another_object) ? self : nil
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
index 593a7a4940..12fdf840b5 100644
--- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb
+++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Object
# Returns a hash with string keys that maps instance variable names without "@" to their
# corresponding values.
diff --git a/activesupport/lib/active_support/core_ext/object/json.rb b/activesupport/lib/active_support/core_ext/object/json.rb
index d49b2fbe54..f7c623fe13 100644
--- a/activesupport/lib/active_support/core_ext/object/json.rb
+++ b/activesupport/lib/active_support/core_ext/object/json.rb
@@ -1,14 +1,18 @@
+# frozen_string_literal: true
+
# Hack to load json gem first so we can overwrite its to_json.
-require 'json'
-require 'bigdecimal'
-require 'active_support/core_ext/big_decimal/conversions' # for #to_s
-require 'active_support/core_ext/hash/except'
-require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/object/instance_variables'
-require 'time'
-require 'active_support/core_ext/time/conversions'
-require 'active_support/core_ext/date_time/conversions'
-require 'active_support/core_ext/date/conversions'
+require "json"
+require "bigdecimal"
+require "uri/generic"
+require "pathname"
+require "active_support/core_ext/big_decimal/conversions" # for #to_s
+require "active_support/core_ext/hash/except"
+require "active_support/core_ext/hash/slice"
+require "active_support/core_ext/object/instance_variables"
+require "time"
+require "active_support/core_ext/time/conversions"
+require "active_support/core_ext/date_time/conversions"
+require "active_support/core_ext/date/conversions"
# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
# their default behavior. That said, we need to define the basic to_json method in all of them,
@@ -131,6 +135,12 @@ module Enumerable
end
end
+class IO
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
+end
+
class Range
def as_json(options = nil) #:nodoc:
to_s
@@ -187,14 +197,26 @@ class DateTime
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
else
- strftime('%Y/%m/%d %H:%M:%S %z')
+ strftime("%Y/%m/%d %H:%M:%S %z")
end
end
end
+class URI::Generic #:nodoc:
+ def as_json(options = nil)
+ to_s
+ end
+end
+
+class Pathname #:nodoc:
+ def as_json(options = nil)
+ to_s
+ end
+end
+
class Process::Status #:nodoc:
def as_json(options = nil)
- { :exitstatus => exitstatus, :pid => pid }
+ { exitstatus: exitstatus, pid: pid }
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb
index 684d4ef57e..6d2bdd70f3 100644
--- a/activesupport/lib/active_support/core_ext/object/to_param.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_param.rb
@@ -1 +1,3 @@
-require 'active_support/core_ext/object/to_query'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/to_query"
diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb
index ec5ace4e16..abb461966a 100644
--- a/activesupport/lib/active_support/core_ext/object/to_query.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_query.rb
@@ -1,4 +1,6 @@
-require 'cgi'
+# frozen_string_literal: true
+
+require "cgi"
class Object
# Alias of <tt>to_s</tt>.
@@ -38,7 +40,7 @@ class Array
# Calls <tt>to_param</tt> on all its elements and joins the result with
# slashes. This is used by <tt>url_for</tt> in Action Pack.
def to_param
- collect(&:to_param).join '/'
+ collect(&:to_param).join "/"
end
# Converts an array into a string suitable for use as a URL query string,
@@ -51,7 +53,7 @@ class Array
if empty?
nil.to_query(prefix)
else
- collect { |value| value.to_query(prefix) }.join '&'
+ collect { |value| value.to_query(prefix) }.join "&"
end
end
end
@@ -77,7 +79,7 @@ class Hash
unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty?
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
end
- end.compact.sort! * '&'
+ end.compact.sort! * "&"
end
alias_method :to_param, :to_query
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index 8c16d95b62..c874691629 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -1,4 +1,6 @@
-require 'delegate'
+# frozen_string_literal: true
+
+require "delegate"
module ActiveSupport
module Tryable #:nodoc:
@@ -99,7 +101,7 @@ class Object
#
# "a".try!(:upcase) # => "A"
# nil.try!(:upcase) # => nil
- # 123.try!(:upcase) # => NoMethodError: undefined method `upcase' for 123:Fixnum
+ # 123.try!(:upcase) # => NoMethodError: undefined method `upcase' for 123:Integer
end
class Delegator
diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb
index 513c8b1d55..2838fd76be 100644
--- a/activesupport/lib/active_support/core_ext/object/with_options.rb
+++ b/activesupport/lib/active_support/core_ext/object/with_options.rb
@@ -1,4 +1,6 @@
-require 'active_support/option_merger'
+# frozen_string_literal: true
+
+require "active_support/option_merger"
class Object
# An elegant way to factor duplication out of options passed to a series of
@@ -60,7 +62,18 @@ class Object
#
# validates :content, length: { minimum: 50 }, if: -> { content.present? }
#
- # Hence the inherited default for `if` key is ignored.
+ # Hence the inherited default for +if+ key is ignored.
+ #
+ # NOTE: You cannot call class methods implicitly inside of with_options.
+ # You can access these methods using the class name instead:
+ #
+ # class Phone < ActiveRecord::Base
+ # enum phone_number_type: [home: 0, office: 1, mobile: 2]
+ #
+ # with_options presence: true do
+ # validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys }
+ # end
+ # end
#
def with_options(options, &block)
option_merger = ActiveSupport::OptionMerger.new(self, options)
diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb
index 9368e81235..4074e91d17 100644
--- a/activesupport/lib/active_support/core_ext/range.rb
+++ b/activesupport/lib/active_support/core_ext/range.rb
@@ -1,4 +1,7 @@
-require 'active_support/core_ext/range/conversions'
-require 'active_support/core_ext/range/include_range'
-require 'active_support/core_ext/range/overlaps'
-require 'active_support/core_ext/range/each'
+# frozen_string_literal: true
+
+require "active_support/core_ext/range/conversions"
+require "active_support/core_ext/range/include_range"
+require "active_support/core_ext/range/include_time_with_zone"
+require "active_support/core_ext/range/overlaps"
+require "active_support/core_ext/range/each"
diff --git a/activesupport/lib/active_support/core_ext/range/conversions.rb b/activesupport/lib/active_support/core_ext/range/conversions.rb
index 965436c23a..8832fbcb3c 100644
--- a/activesupport/lib/active_support/core_ext/range/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/range/conversions.rb
@@ -1,6 +1,14 @@
+# frozen_string_literal: true
+
module ActiveSupport::RangeWithFormat
RANGE_FORMATS = {
- :db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
+ db: -> (start, stop) do
+ case start
+ when String then "BETWEEN '#{start}' AND '#{stop}'"
+ else
+ "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'"
+ end
+ end
}
# Convert range to a formatted string. See RANGE_FORMATS for predefined formats.
diff --git a/activesupport/lib/active_support/core_ext/range/each.rb b/activesupport/lib/active_support/core_ext/range/each.rb
index dc6dad5ced..2f22cd0e92 100644
--- a/activesupport/lib/active_support/core_ext/range/each.rb
+++ b/activesupport/lib/active_support/core_ext/range/each.rb
@@ -1,3 +1,7 @@
+# frozen_string_literal: true
+
+require "active_support/time_with_zone"
+
module ActiveSupport
module EachTimeWithZone #:nodoc:
def each(&block)
@@ -13,7 +17,7 @@ module ActiveSupport
private
def ensure_iteration_allowed
- raise TypeError, "can't iterate from #{first.class}" if first.is_a?(Time)
+ raise TypeError, "can't iterate from #{first.class}" if first.is_a?(TimeWithZone)
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/range/include_range.rb b/activesupport/lib/active_support/core_ext/range/include_range.rb
index c69e1e3fb9..7ba1011921 100644
--- a/activesupport/lib/active_support/core_ext/range/include_range.rb
+++ b/activesupport/lib/active_support/core_ext/range/include_range.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module IncludeWithRange #:nodoc:
# Extends the default Range#include? to support range comparisons.
diff --git a/activesupport/lib/active_support/core_ext/range/include_time_with_zone.rb b/activesupport/lib/active_support/core_ext/range/include_time_with_zone.rb
new file mode 100644
index 0000000000..5f80acf68e
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/include_time_with_zone.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+require "active_support/time_with_zone"
+
+module ActiveSupport
+ module IncludeTimeWithZone #:nodoc:
+ # Extends the default Range#include? to support ActiveSupport::TimeWithZone.
+ #
+ # (1.hour.ago..1.hour.from_now).include?(Time.current) # => true
+ #
+ def include?(value)
+ if first.is_a?(TimeWithZone)
+ cover?(value)
+ elsif last.is_a?(TimeWithZone)
+ cover?(value)
+ else
+ super
+ end
+ end
+ end
+end
+
+Range.prepend(ActiveSupport::IncludeTimeWithZone)
diff --git a/activesupport/lib/active_support/core_ext/range/overlaps.rb b/activesupport/lib/active_support/core_ext/range/overlaps.rb
index 603657c180..f753607f8b 100644
--- a/activesupport/lib/active_support/core_ext/range/overlaps.rb
+++ b/activesupport/lib/active_support/core_ext/range/overlaps.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class Range
# Compare two ranges and see if they overlap each other
# (1..5).overlaps?(4..6) # => true
diff --git a/activesupport/lib/active_support/core_ext/regexp.rb b/activesupport/lib/active_support/core_ext/regexp.rb
index 784145f5fb..efbd708aee 100644
--- a/activesupport/lib/active_support/core_ext/regexp.rb
+++ b/activesupport/lib/active_support/core_ext/regexp.rb
@@ -1,5 +1,11 @@
+# frozen_string_literal: true
+
class Regexp #:nodoc:
def multiline?
options & MULTILINE == MULTILINE
end
+
+ def match?(string, pos = 0)
+ !!match(string, pos)
+ end unless //.respond_to?(:match?)
end
diff --git a/activesupport/lib/active_support/core_ext/securerandom.rb b/activesupport/lib/active_support/core_ext/securerandom.rb
index 98cf7430f7..b4a491f5fd 100644
--- a/activesupport/lib/active_support/core_ext/securerandom.rb
+++ b/activesupport/lib/active_support/core_ext/securerandom.rb
@@ -1,12 +1,14 @@
-require 'securerandom'
+# frozen_string_literal: true
+
+require "securerandom"
module SecureRandom
- BASE58_ALPHABET = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a - ['0', 'O', 'I', 'l']
+ BASE58_ALPHABET = ("0".."9").to_a + ("A".."Z").to_a + ("a".."z").to_a - ["0", "O", "I", "l"]
# SecureRandom.base58 generates a random base58 string.
#
# The argument _n_ specifies the length, of the random string to be generated.
#
- # If _n_ is not specified or is nil, 16 is assumed. It may be larger in the future.
+ # If _n_ is not specified or is +nil+, 16 is assumed. It may be larger in the future.
#
# The result may contain alphanumeric characters except 0, O, I and l
#
diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb
index c656db2c6c..757d15c51a 100644
--- a/activesupport/lib/active_support/core_ext/string.rb
+++ b/activesupport/lib/active_support/core_ext/string.rb
@@ -1,13 +1,15 @@
-require 'active_support/core_ext/string/conversions'
-require 'active_support/core_ext/string/filters'
-require 'active_support/core_ext/string/multibyte'
-require 'active_support/core_ext/string/starts_ends_with'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/core_ext/string/access'
-require 'active_support/core_ext/string/behavior'
-require 'active_support/core_ext/string/output_safety'
-require 'active_support/core_ext/string/exclude'
-require 'active_support/core_ext/string/strip'
-require 'active_support/core_ext/string/inquiry'
-require 'active_support/core_ext/string/indent'
-require 'active_support/core_ext/string/zones'
+# frozen_string_literal: true
+
+require "active_support/core_ext/string/conversions"
+require "active_support/core_ext/string/filters"
+require "active_support/core_ext/string/multibyte"
+require "active_support/core_ext/string/starts_ends_with"
+require "active_support/core_ext/string/inflections"
+require "active_support/core_ext/string/access"
+require "active_support/core_ext/string/behavior"
+require "active_support/core_ext/string/output_safety"
+require "active_support/core_ext/string/exclude"
+require "active_support/core_ext/string/strip"
+require "active_support/core_ext/string/inquiry"
+require "active_support/core_ext/string/indent"
+require "active_support/core_ext/string/zones"
diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb
index ebd0dd3fc7..58591bbaaf 100644
--- a/activesupport/lib/active_support/core_ext/string/access.rb
+++ b/activesupport/lib/active_support/core_ext/string/access.rb
@@ -1,9 +1,11 @@
+# frozen_string_literal: true
+
class String
- # If you pass a single Fixnum, returns a substring of one character at that
+ # If you pass a single integer, returns a substring of one character at that
# position. The first character of the string is at position 0, the next at
# position 1, and so on. If a range is supplied, a substring containing
# characters at offsets given by the range is returned. In both cases, if an
- # offset is negative, it is counted from the end of the string. Returns nil
+ # offset is negative, it is counted from the end of the string. Returns +nil+
# if the initial offset falls outside the string. Returns an empty string if
# the beginning of the range is greater than the end of the string.
#
@@ -17,7 +19,7 @@ class String
#
# If a Regexp is given, the matching portion of the string is returned.
# If a String is given, that given string is returned if it occurs in
- # the string. In both cases, nil is returned if there is no match.
+ # the string. In both cases, +nil+ is returned if there is no match.
#
# str = "hello"
# str.at(/lo/) # => "lo"
@@ -74,9 +76,9 @@ class String
# str.first(6) # => "hello"
def first(limit = 1)
if limit == 0
- ''
+ ""
elsif limit >= size
- self.dup
+ dup
else
to(limit - 1)
end
@@ -94,9 +96,9 @@ class String
# str.last(6) # => "hello"
def last(limit = 1)
if limit == 0
- ''
+ ""
elsif limit >= size
- self.dup
+ dup
else
from(-limit)
end
diff --git a/activesupport/lib/active_support/core_ext/string/behavior.rb b/activesupport/lib/active_support/core_ext/string/behavior.rb
index 710f1f4670..35a5aa7840 100644
--- a/activesupport/lib/active_support/core_ext/string/behavior.rb
+++ b/activesupport/lib/active_support/core_ext/string/behavior.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class String
# Enables more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
def acts_like_string?
diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb
index 946976c5e9..29a88b07ad 100644
--- a/activesupport/lib/active_support/core_ext/string/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/string/conversions.rb
@@ -1,5 +1,7 @@
-require 'date'
-require 'active_support/core_ext/time/calculations'
+# frozen_string_literal: true
+
+require "date"
+require "active_support/core_ext/time/calculations"
class String
# Converts a string to a Time value.
diff --git a/activesupport/lib/active_support/core_ext/string/exclude.rb b/activesupport/lib/active_support/core_ext/string/exclude.rb
index 0ac684f6ee..8e462689f1 100644
--- a/activesupport/lib/active_support/core_ext/string/exclude.rb
+++ b/activesupport/lib/active_support/core_ext/string/exclude.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class String
# The inverse of <tt>String#include?</tt>. Returns true if the string
# does not include the other string.
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb
index 375ec1aef8..66e721eea3 100644
--- a/activesupport/lib/active_support/core_ext/string/filters.rb
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class String
# Returns the string, first removing all whitespace on both ends of
# the string, and then changing remaining consecutive whitespace
@@ -17,7 +19,7 @@ class String
# str.squish! # => "foo bar boo"
# str # => "foo bar boo"
def squish!
- gsub!(/[[:space:]]+/, ' ')
+ gsub!(/[[:space:]]+/, " ")
strip!
self
end
@@ -64,7 +66,7 @@ class String
def truncate(truncate_at, options = {})
return dup unless length > truncate_at
- omission = options[:omission] || '...'
+ omission = options[:omission] || "..."
length_with_room_for_omission = truncate_at - omission.length
stop = \
if options[:separator]
@@ -94,7 +96,7 @@ class String
sep = options[:separator] || /\s+/
sep = Regexp.escape(sep.to_s) unless Regexp === sep
if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m
- $1 + (options[:omission] || '...')
+ $1 + (options[:omission] || "...")
else
dup
end
diff --git a/activesupport/lib/active_support/core_ext/string/indent.rb b/activesupport/lib/active_support/core_ext/string/indent.rb
index ce3a69cf5f..af9d181487 100644
--- a/activesupport/lib/active_support/core_ext/string/indent.rb
+++ b/activesupport/lib/active_support/core_ext/string/indent.rb
@@ -1,9 +1,11 @@
+# frozen_string_literal: true
+
class String
# Same as +indent+, except it indents the receiver in-place.
#
# Returns the indented string, or +nil+ if there was nothing to indent.
- def indent!(amount, indent_string=nil, indent_empty_lines=false)
- indent_string = indent_string || self[/^[ \t]/] || ' '
+ def indent!(amount, indent_string = nil, indent_empty_lines = false)
+ indent_string = indent_string || self[/^[ \t]/] || " "
re = indent_empty_lines ? /^/ : /^(?!$)/
gsub!(re, indent_string * amount)
end
@@ -37,7 +39,7 @@ class String
# "foo\n\nbar".indent(2) # => " foo\n\n bar"
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
#
- def indent(amount, indent_string=nil, indent_empty_lines=false)
- dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
+ def indent(amount, indent_string = nil, indent_empty_lines = false)
+ dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) }
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
index 7277f51076..8af301734a 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -1,5 +1,7 @@
-require 'active_support/inflector/methods'
-require 'active_support/inflector/transliterate'
+# frozen_string_literal: true
+
+require "active_support/inflector/methods"
+require "active_support/inflector/transliterate"
# String inflections define new methods on the String class to transform names for different purposes.
# For instance, you can figure out the name of a table from the name of a class.
@@ -31,7 +33,7 @@ class String
def pluralize(count = nil, locale = :en)
locale = count if count.is_a?(Symbol)
if count == 1
- self.dup
+ dup
else
ActiveSupport::Inflector.pluralize(self, locale)
end
@@ -67,7 +69,7 @@ class String
end
# +safe_constantize+ tries to find a declared constant with the name specified
- # in the string. It returns nil when the name is not in CamelCase
+ # in the string. It returns +nil+ when the name is not in CamelCase
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
#
# 'Module'.safe_constantize # => Module
@@ -92,6 +94,8 @@ class String
ActiveSupport::Inflector.camelize(self, true)
when :lower
ActiveSupport::Inflector.camelize(self, false)
+ else
+ raise ArgumentError, "Invalid option, use either :upper or :lower."
end
end
alias_method :camelcase, :camelize
@@ -100,12 +104,17 @@ class String
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
# used in the Rails internals.
#
+ # The trailing '_id','Id'.. can be kept and capitalized by setting the
+ # optional parameter +keep_id_suffix+ to true.
+ # By default, this parameter is false.
+ #
# +titleize+ is also aliased as +titlecase+.
#
- # 'man from the boondocks'.titleize # => "Man From The Boondocks"
- # 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
- def titleize
- ActiveSupport::Inflector.titleize(self)
+ # 'man from the boondocks'.titleize # => "Man From The Boondocks"
+ # 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
+ # 'string_ending_with_id'.titleize(keep_id_suffix: true) # => "String Ending With Id"
+ def titleize(keep_id_suffix: false)
+ ActiveSupport::Inflector.titleize(self, keep_id_suffix: keep_id_suffix)
end
alias_method :titlecase, :titleize
@@ -128,10 +137,10 @@ class String
# Removes the module part from the constant expression in the string.
#
- # 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
- # 'Inflections'.demodulize # => "Inflections"
- # '::Inflections'.demodulize # => "Inflections"
- # ''.demodulize # => ''
+ # 'ActiveSupport::Inflector::Inflections'.demodulize # => "Inflections"
+ # 'Inflections'.demodulize # => "Inflections"
+ # '::Inflections'.demodulize # => "Inflections"
+ # ''.demodulize # => ''
#
# See also +deconstantize+.
def demodulize
@@ -164,8 +173,8 @@ class String
#
# <%= link_to(@person.name, person_path) %>
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
- #
- # To preserve the case of the characters in a string, use the `preserve_case` argument.
+ #
+ # To preserve the case of the characters in a string, use the +preserve_case+ argument.
#
# class Person
# def to_param
@@ -178,11 +187,7 @@ class String
#
# <%= link_to(@person.name, person_path) %>
# # => <a href="/person/1-Donald-E-Knuth">Donald E. Knuth</a>
- def parameterize(sep = :unused, separator: '-', preserve_case: false)
- unless sep == :unused
- ActiveSupport::Deprecation.warn("Passing the separator argument as a positional parameter is deprecated and will soon be removed. Use `separator: '#{sep}'` instead.")
- separator = sep
- end
+ def parameterize(separator: "-", preserve_case: false)
ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case)
end
@@ -206,7 +211,7 @@ class String
ActiveSupport::Inflector.classify(self)
end
- # Capitalizes the first word, turns underscores into spaces, and strips a
+ # Capitalizes the first word, turns underscores into spaces, and (by default)strips a
# trailing '_id' if present.
# Like +titleize+, this is meant for creating pretty output.
#
@@ -214,12 +219,17 @@ class String
# optional parameter +capitalize+ to false.
# By default, this parameter is true.
#
- # 'employee_salary'.humanize # => "Employee salary"
- # 'author_id'.humanize # => "Author"
- # 'author_id'.humanize(capitalize: false) # => "author"
- # '_id'.humanize # => "Id"
- def humanize(options = {})
- ActiveSupport::Inflector.humanize(self, options)
+ # The trailing '_id' can be kept and capitalized by setting the
+ # optional parameter +keep_id_suffix+ to true.
+ # By default, this parameter is false.
+ #
+ # 'employee_salary'.humanize # => "Employee salary"
+ # 'author_id'.humanize # => "Author"
+ # 'author_id'.humanize(capitalize: false) # => "author"
+ # '_id'.humanize # => "Id"
+ # 'author_id'.humanize(keep_id_suffix: true) # => "Author Id"
+ def humanize(capitalize: true, keep_id_suffix: false)
+ ActiveSupport::Inflector.humanize(self, capitalize: capitalize, keep_id_suffix: keep_id_suffix)
end
# Converts just the first character to uppercase.
diff --git a/activesupport/lib/active_support/core_ext/string/inquiry.rb b/activesupport/lib/active_support/core_ext/string/inquiry.rb
index 1dcd949536..a796d5fb4f 100644
--- a/activesupport/lib/active_support/core_ext/string/inquiry.rb
+++ b/activesupport/lib/active_support/core_ext/string/inquiry.rb
@@ -1,4 +1,6 @@
-require 'active_support/string_inquirer'
+# frozen_string_literal: true
+
+require "active_support/string_inquirer"
class String
# Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
diff --git a/activesupport/lib/active_support/core_ext/string/multibyte.rb b/activesupport/lib/active_support/core_ext/string/multibyte.rb
index cc6f2158e7..07c0d16398 100644
--- a/activesupport/lib/active_support/core_ext/string/multibyte.rb
+++ b/activesupport/lib/active_support/core_ext/string/multibyte.rb
@@ -1,4 +1,6 @@
-require 'active_support/multibyte'
+# frozen_string_literal: true
+
+require "active_support/multibyte"
class String
# == Multibyte proxy
@@ -14,6 +16,8 @@ class String
# >> "lj".mb_chars.upcase.to_s
# => "LJ"
#
+ # NOTE: An above example is useful for pre Ruby 2.4. Ruby 2.4 supports Unicode case mappings.
+ #
# == Method chaining
#
# All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb
index 005ad93b08..f3bdc2977e 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -1,32 +1,32 @@
-require 'erb'
-require 'active_support/core_ext/kernel/singleton_class'
+# frozen_string_literal: true
+
+require "erb"
+require "active_support/core_ext/kernel/singleton_class"
+require "active_support/core_ext/module/redefine_method"
+require "active_support/multibyte/unicode"
class ERB
module Util
- HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;', "'" => '&#39;' }
- JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003e', '<' => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
+ HTML_ESCAPE = { "&" => "&amp;", ">" => "&gt;", "<" => "&lt;", '"' => "&quot;", "'" => "&#39;" }
+ JSON_ESCAPE = { "&" => '\u0026', ">" => '\u003e', "<" => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+)|(#[xX][\dA-Fa-f]+));)/
JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u
# A utility method for escaping HTML tag characters.
# This method is also aliased as <tt>h</tt>.
#
- # In your ERB templates, use this method to escape any unsafe content. For example:
- # <%= h @person.name %>
- #
# puts html_escape('is a > 0 & a < 10?')
# # => is a &gt; 0 &amp; a &lt; 10?
def html_escape(s)
unwrapped_html_escape(s).html_safe
end
- # Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
- remove_method(:h)
+ silence_redefinition_of_method :h
alias h html_escape
module_function :h
- singleton_class.send(:remove_method, :html_escape)
+ singleton_class.silence_redefinition_of_method :html_escape
module_function :html_escape
# HTML escapes strings but doesn't wrap them with an ActiveSupport::SafeBuffer.
@@ -144,25 +144,23 @@ module ActiveSupport #:nodoc:
# Raised when <tt>ActiveSupport::SafeBuffer#safe_concat</tt> is called on unsafe buffers.
class SafeConcatError < StandardError
def initialize
- super 'Could not concatenate to the buffer because it is not html safe.'
+ super "Could not concatenate to the buffer because it is not html safe."
end
end
def [](*args)
if args.size < 2
super
- else
- if html_safe?
- new_safe_buffer = super
-
- if new_safe_buffer
- new_safe_buffer.instance_variable_set :@html_safe, true
- end
+ elsif html_safe?
+ new_safe_buffer = super
- new_safe_buffer
- else
- to_str[*args]
+ if new_safe_buffer
+ new_safe_buffer.instance_variable_set :@html_safe, true
end
+
+ new_safe_buffer
+ else
+ to_str[*args]
end
end
@@ -171,7 +169,7 @@ module ActiveSupport #:nodoc:
original_concat(value)
end
- def initialize(str = '')
+ def initialize(str = "")
@html_safe = true
super
end
@@ -201,7 +199,7 @@ module ActiveSupport #:nodoc:
def %(args)
case args
when Hash
- escaped_args = Hash[args.map { |k,arg| [k, html_escape_interpolated_argument(arg)] }]
+ escaped_args = Hash[args.map { |k, arg| [k, html_escape_interpolated_argument(arg)] }]
else
escaped_args = Array(args).map { |arg| html_escape_interpolated_argument(arg) }
end
@@ -242,9 +240,9 @@ module ActiveSupport #:nodoc:
private
- def html_escape_interpolated_argument(arg)
- (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s)
- end
+ def html_escape_interpolated_argument(arg)
+ (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s)
+ end
end
end
@@ -252,7 +250,7 @@ class String
# Marks a string as trusted safe. It will be inserted into HTML with no
# additional escaping performed. It is your responsibility to ensure that the
# string contains no malicious content. This method is equivalent to the
- # `raw` helper in views. It is recommended that you use `sanitize` instead of
+ # +raw+ helper in views. It is recommended that you use +sanitize+ instead of
# this method. It should never be called on user input.
def html_safe
ActiveSupport::SafeBuffer.new(self)
diff --git a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb
index 641acf62d0..919eb7a573 100644
--- a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb
+++ b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class String
alias_method :starts_with?, :start_with?
alias_method :ends_with?, :end_with?
diff --git a/activesupport/lib/active_support/core_ext/string/strip.rb b/activesupport/lib/active_support/core_ext/string/strip.rb
index 55b9b87352..cc26274e4a 100644
--- a/activesupport/lib/active_support/core_ext/string/strip.rb
+++ b/activesupport/lib/active_support/core_ext/string/strip.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class String
# Strips indentation in heredocs.
#
@@ -18,6 +20,6 @@ class String
# Technically, it looks for the least indented non-empty line
# in the whole string, and removes that amount of leading whitespace.
def strip_heredoc
- gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, ''.freeze)
+ gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "".freeze)
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/zones.rb b/activesupport/lib/active_support/core_ext/string/zones.rb
index 510c884c18..55dc231464 100644
--- a/activesupport/lib/active_support/core_ext/string/zones.rb
+++ b/activesupport/lib/active_support/core_ext/string/zones.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/string/conversions'
-require 'active_support/core_ext/time/zones'
+# frozen_string_literal: true
+
+require "active_support/core_ext/string/conversions"
+require "active_support/core_ext/time/zones"
class String
# Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
diff --git a/activesupport/lib/active_support/core_ext/struct.rb b/activesupport/lib/active_support/core_ext/struct.rb
deleted file mode 100644
index 1fde3db070..0000000000
--- a/activesupport/lib/active_support/core_ext/struct.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("This file is deprecated and will be removed in Rails 5.1 with no replacement.")
diff --git a/activesupport/lib/active_support/core_ext/time.rb b/activesupport/lib/active_support/core_ext/time.rb
index 0bce632222..c809def05f 100644
--- a/activesupport/lib/active_support/core_ext/time.rb
+++ b/activesupport/lib/active_support/core_ext/time.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/time/acts_like'
-require 'active_support/core_ext/time/calculations'
-require 'active_support/core_ext/time/compatibility'
-require 'active_support/core_ext/time/conversions'
-require 'active_support/core_ext/time/zones'
+# frozen_string_literal: true
+
+require "active_support/core_ext/time/acts_like"
+require "active_support/core_ext/time/calculations"
+require "active_support/core_ext/time/compatibility"
+require "active_support/core_ext/time/conversions"
+require "active_support/core_ext/time/zones"
diff --git a/activesupport/lib/active_support/core_ext/time/acts_like.rb b/activesupport/lib/active_support/core_ext/time/acts_like.rb
index 3f853b7893..8572b49639 100644
--- a/activesupport/lib/active_support/core_ext/time/acts_like.rb
+++ b/activesupport/lib/active_support/core_ext/time/acts_like.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/object/acts_like'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/acts_like"
class Time
# Duck-types as a Time-like class. See Object#acts_like?.
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index b755726db2..120768dec5 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -1,9 +1,11 @@
-require 'active_support/duration'
-require 'active_support/core_ext/time/conversions'
-require 'active_support/time_with_zone'
-require 'active_support/core_ext/time/zones'
-require 'active_support/core_ext/date_and_time/calculations'
-require 'active_support/core_ext/date/calculations'
+# frozen_string_literal: true
+
+require "active_support/duration"
+require "active_support/core_ext/time/conversions"
+require "active_support/time_with_zone"
+require "active_support/core_ext/time/zones"
+require "active_support/core_ext/date_and_time/calculations"
+require "active_support/core_ext/date/calculations"
class Time
include DateAndTime::Calculations
@@ -53,6 +55,29 @@ class Time
end
alias_method :at_without_coercion, :at
alias_method :at, :at_with_coercion
+
+ # Creates a +Time+ instance from an RFC 3339 string.
+ #
+ # Time.rfc3339('1999-12-31T14:00:00-10:00') # => 2000-01-01 00:00:00 -1000
+ #
+ # If the time or offset components are missing then an +ArgumentError+ will be raised.
+ #
+ # Time.rfc3339('1999-12-31') # => ArgumentError: invalid date
+ def rfc3339(str)
+ parts = Date._rfc3339(str)
+
+ raise ArgumentError, "invalid date" if parts.empty?
+
+ Time.new(
+ parts.fetch(:year),
+ parts.fetch(:mon),
+ parts.fetch(:mday),
+ parts.fetch(:hour),
+ parts.fetch(:min),
+ parts.fetch(:sec) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset)
+ )
+ end
end
# Returns the number of seconds since 00:00:00.
@@ -61,7 +86,7 @@ class Time
# Time.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296.0
# Time.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399.0
def seconds_since_midnight
- to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
+ to_i - change(hour: 0).to_i + (usec / 1.0e+6)
end
# Returns the number of seconds until 23:59:59.
@@ -84,36 +109,42 @@ class Time
# to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
# <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>) reset cascadingly, so if only
# the hour is passed, then minute, sec, usec and nsec is set to 0. If the hour
- # and minute is passed, then sec, usec and nsec is set to 0. The +options+
- # parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>,
- # <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>
- # <tt>:nsec</tt>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
+ # and minute is passed, then sec, usec and nsec is set to 0. The +options+ parameter
+ # takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>,
+ # <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>,
+ # <tt>:offset</tt>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
#
# Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
def change(options)
- new_year = options.fetch(:year, year)
- new_month = options.fetch(:month, month)
- new_day = options.fetch(:day, day)
- new_hour = options.fetch(:hour, hour)
- new_min = options.fetch(:min, options[:hour] ? 0 : min)
- new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
+ new_year = options.fetch(:year, year)
+ new_month = options.fetch(:month, month)
+ new_day = options.fetch(:day, day)
+ new_hour = options.fetch(:hour, hour)
+ new_min = options.fetch(:min, options[:hour] ? 0 : min)
+ new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
+ new_offset = options.fetch(:offset, nil)
if new_nsec = options[:nsec]
raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
new_usec = Rational(new_nsec, 1000)
else
- new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
+ new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
end
- if utc?
- ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
+ raise ArgumentError, "argument out of range" if new_usec >= 1000000
+
+ new_sec += Rational(new_usec, 1000000)
+
+ if new_offset
+ ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, new_offset)
+ elsif utc?
+ ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec)
elsif zone
- ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
+ ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec)
else
- raise ArgumentError, 'argument out of range' if new_usec >= 1000000
- ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
+ ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, utc_offset)
end
end
@@ -141,7 +172,7 @@ class Time
d = to_date.advance(options)
d = d.gregorian if d.julian?
- time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
+ time_advanced_by_date = change(year: d.year, month: d.month, day: d.day)
seconds_to_advance = \
options.fetch(:seconds, 0) +
options.fetch(:minutes, 0) * 60 +
@@ -169,7 +200,7 @@ class Time
# Returns a new Time representing the start of the day (0:00)
def beginning_of_day
- change(:hour => 0)
+ change(hour: 0)
end
alias :midnight :beginning_of_day
alias :at_midnight :beginning_of_day
@@ -177,7 +208,7 @@ class Time
# Returns a new Time representing the middle of the day (12:00)
def middle_of_day
- change(:hour => 12)
+ change(hour: 12)
end
alias :midday :middle_of_day
alias :noon :middle_of_day
@@ -188,50 +219,45 @@ class Time
# Returns a new Time representing the end of the day, 23:59:59.999999
def end_of_day
change(
- :hour => 23,
- :min => 59,
- :sec => 59,
- :usec => Rational(999999999, 1000)
+ hour: 23,
+ min: 59,
+ sec: 59,
+ usec: Rational(999999999, 1000)
)
end
alias :at_end_of_day :end_of_day
# Returns a new Time representing the start of the hour (x:00)
def beginning_of_hour
- change(:min => 0)
+ change(min: 0)
end
alias :at_beginning_of_hour :beginning_of_hour
# Returns a new Time representing the end of the hour, x:59:59.999999
def end_of_hour
change(
- :min => 59,
- :sec => 59,
- :usec => Rational(999999999, 1000)
+ min: 59,
+ sec: 59,
+ usec: Rational(999999999, 1000)
)
end
alias :at_end_of_hour :end_of_hour
# Returns a new Time representing the start of the minute (x:xx:00)
def beginning_of_minute
- change(:sec => 0)
+ change(sec: 0)
end
alias :at_beginning_of_minute :beginning_of_minute
# Returns a new Time representing the end of the minute, x:xx:59.999999
def end_of_minute
change(
- :sec => 59,
- :usec => Rational(999999999, 1000)
+ sec: 59,
+ usec: Rational(999999999, 1000)
)
end
alias :at_end_of_minute :end_of_minute
- # Returns a Range representing the whole day of the current time.
- def all_day
- beginning_of_day..end_of_day
- end
-
def plus_with_duration(other) #:nodoc:
if ActiveSupport::Duration === other
other.since(self)
@@ -286,5 +312,4 @@ class Time
end
alias_method :eql_without_coercion, :eql?
alias_method :eql?, :eql_with_coercion
-
end
diff --git a/activesupport/lib/active_support/core_ext/time/compatibility.rb b/activesupport/lib/active_support/core_ext/time/compatibility.rb
index 945319461b..495e4f307b 100644
--- a/activesupport/lib/active_support/core_ext/time/compatibility.rb
+++ b/activesupport/lib/active_support/core_ext/time/compatibility.rb
@@ -1,5 +1,16 @@
-require 'active_support/core_ext/date_and_time/compatibility'
+# frozen_string_literal: true
+
+require "active_support/core_ext/date_and_time/compatibility"
+require "active_support/core_ext/module/redefine_method"
class Time
- prepend DateAndTime::Compatibility
+ include DateAndTime::Compatibility
+
+ silence_redefinition_of_method :to_time
+
+ # Either return +self+ or the time in the local system timezone depending
+ # on the setting of +ActiveSupport.to_time_preserves_timezone+.
+ def to_time
+ preserve_timezone ? self : getlocal
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index 536c4bf525..345cb2832c 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -1,24 +1,26 @@
-require 'active_support/inflector/methods'
-require 'active_support/values/time_zone'
+# frozen_string_literal: true
+
+require "active_support/inflector/methods"
+require "active_support/values/time_zone"
class Time
DATE_FORMATS = {
- :db => '%Y-%m-%d %H:%M:%S',
- :number => '%Y%m%d%H%M%S',
- :nsec => '%Y%m%d%H%M%S%9N',
- :usec => '%Y%m%d%H%M%S%6N',
- :time => '%H:%M',
- :short => '%d %b %H:%M',
- :long => '%B %d, %Y %H:%M',
- :long_ordinal => lambda { |time|
+ db: "%Y-%m-%d %H:%M:%S",
+ number: "%Y%m%d%H%M%S",
+ nsec: "%Y%m%d%H%M%S%9N",
+ usec: "%Y%m%d%H%M%S%6N",
+ time: "%H:%M",
+ short: "%d %b %H:%M",
+ long: "%B %d, %Y %H:%M",
+ long_ordinal: lambda { |time|
day_format = ActiveSupport::Inflector.ordinalize(time.day)
time.strftime("%B #{day_format}, %Y %H:%M")
},
- :rfc822 => lambda { |time|
+ rfc822: lambda { |time|
offset_format = time.formatted_offset(false)
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
},
- :iso8601 => lambda { |time| time.iso8601 }
+ iso8601: lambda { |time| time.iso8601 }
}
# Converts to a formatted string. See DATE_FORMATS for built-in formats.
@@ -64,4 +66,7 @@ class Time
def formatted_offset(colon = true, alternate_utc_string = nil)
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
end
+
+ # Aliased to +xmlschema+ for compatibility with +DateTime+
+ alias_method :rfc3339, :xmlschema
end
diff --git a/activesupport/lib/active_support/core_ext/time/marshal.rb b/activesupport/lib/active_support/core_ext/time/marshal.rb
deleted file mode 100644
index 467bad1726..0000000000
--- a/activesupport/lib/active_support/core_ext/time/marshal.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("This is deprecated and will be removed in Rails 5.1 with no replacement.")
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
index 7a60f94996..a5588fd488 100644
--- a/activesupport/lib/active_support/core_ext/time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -1,6 +1,8 @@
-require 'active_support/time_with_zone'
-require 'active_support/core_ext/time/acts_like'
-require 'active_support/core_ext/date_and_time/zones'
+# frozen_string_literal: true
+
+require "active_support/time_with_zone"
+require "active_support/core_ext/time/acts_like"
+require "active_support/core_ext/date_and_time/zones"
class Time
include DateAndTime::Zones
@@ -53,10 +55,10 @@ class Time
# end
# end
#
- # NOTE: This won't affect any <tt>ActiveSupport::TimeWithZone</tt>
- # objects that have already been created, e.g. any model timestamp
- # attributes that have been read before the block will remain in
- # the application's default timezone.
+ # NOTE: This won't affect any <tt>ActiveSupport::TimeWithZone</tt>
+ # objects that have already been created, e.g. any model timestamp
+ # attributes that have been read before the block will remain in
+ # the application's default timezone.
def use_zone(time_zone)
new_zone = find_zone!(time_zone)
begin
diff --git a/activesupport/lib/active_support/core_ext/uri.rb b/activesupport/lib/active_support/core_ext/uri.rb
index c6c183edd9..c93c0b5c2d 100644
--- a/activesupport/lib/active_support/core_ext/uri.rb
+++ b/activesupport/lib/active_support/core_ext/uri.rb
@@ -1,16 +1,19 @@
-require 'uri'
+# frozen_string_literal: true
+
+require "uri"
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
parser = URI::Parser.new
unless str == parser.unescape(parser.escape(str))
+ require "active_support/core_ext/module/redefine_method"
URI::Parser.class_eval do
- remove_method :unescape
+ silence_redefinition_of_method :unescape
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
# TODO: Are we actually sure that ASCII == UTF-8?
# YK: My initial experiments say yes, but let's be sure please
enc = str.encoding
enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
- str.gsub(escaped) { |match| [match[1, 2].hex].pack('C') }.force_encoding(enc)
+ str.gsub(escaped) { |match| [match[1, 2].hex].pack("C") }.force_encoding(enc)
end
end
end
diff --git a/activesupport/lib/active_support/current_attributes.rb b/activesupport/lib/active_support/current_attributes.rb
new file mode 100644
index 0000000000..4e6d8e4585
--- /dev/null
+++ b/activesupport/lib/active_support/current_attributes.rb
@@ -0,0 +1,195 @@
+# frozen_string_literal: true
+
+module ActiveSupport
+ # Abstract super class that provides a thread-isolated attributes singleton, which resets automatically
+ # before and after each request. This allows you to keep all the per-request attributes easily
+ # available to the whole system.
+ #
+ # The following full app-like example demonstrates how to use a Current class to
+ # facilitate easy access to the global, per-request attributes without passing them deeply
+ # around everywhere:
+ #
+ # # app/models/current.rb
+ # class Current < ActiveSupport::CurrentAttributes
+ # attribute :account, :user
+ # attribute :request_id, :user_agent, :ip_address
+ #
+ # resets { Time.zone = nil }
+ #
+ # def user=(user)
+ # super
+ # self.account = user.account
+ # Time.zone = user.time_zone
+ # end
+ # end
+ #
+ # # app/controllers/concerns/authentication.rb
+ # module Authentication
+ # extend ActiveSupport::Concern
+ #
+ # included do
+ # before_action :authenticate
+ # end
+ #
+ # private
+ # def authenticate
+ # if authenticated_user = User.find_by(id: cookies.encrypted[:user_id])
+ # Current.user = authenticated_user
+ # else
+ # redirect_to new_session_url
+ # end
+ # end
+ # end
+ #
+ # # app/controllers/concerns/set_current_request_details.rb
+ # module SetCurrentRequestDetails
+ # extend ActiveSupport::Concern
+ #
+ # included do
+ # before_action do
+ # Current.request_id = request.uuid
+ # Current.user_agent = request.user_agent
+ # Current.ip_address = request.ip
+ # end
+ # end
+ # end
+ #
+ # class ApplicationController < ActionController::Base
+ # include Authentication
+ # include SetCurrentRequestDetails
+ # end
+ #
+ # class MessagesController < ApplicationController
+ # def create
+ # Current.account.messages.create(message_params)
+ # end
+ # end
+ #
+ # class Message < ApplicationRecord
+ # belongs_to :creator, default: -> { Current.user }
+ # after_create { |message| Event.create(record: message) }
+ # end
+ #
+ # class Event < ApplicationRecord
+ # before_create do
+ # self.request_id = Current.request_id
+ # self.user_agent = Current.user_agent
+ # self.ip_address = Current.ip_address
+ # end
+ # end
+ #
+ # A word of caution: It's easy to overdo a global singleton like Current and tangle your model as a result.
+ # Current should only be used for a few, top-level globals, like account, user, and request details.
+ # The attributes stuck in Current should be used by more or less all actions on all requests. If you start
+ # sticking controller-specific attributes in there, you're going to create a mess.
+ class CurrentAttributes
+ include ActiveSupport::Callbacks
+ define_callbacks :reset
+
+ class << self
+ # Returns singleton instance for this class in this thread. If none exists, one is created.
+ def instance
+ current_instances[name] ||= new
+ end
+
+ # Declares one or more attributes that will be given both class and instance accessor methods.
+ def attribute(*names)
+ generated_attribute_methods.module_eval do
+ names.each do |name|
+ define_method(name) do
+ attributes[name.to_sym]
+ end
+
+ define_method("#{name}=") do |attribute|
+ attributes[name.to_sym] = attribute
+ end
+ end
+ end
+
+ names.each do |name|
+ define_singleton_method(name) do
+ instance.public_send(name)
+ end
+
+ define_singleton_method("#{name}=") do |attribute|
+ instance.public_send("#{name}=", attribute)
+ end
+ end
+ end
+
+ # Calls this block after #reset is called on the instance. Used for resetting external collaborators, like Time.zone.
+ def resets(&block)
+ set_callback :reset, :after, &block
+ end
+
+ delegate :set, :reset, to: :instance
+
+ def reset_all # :nodoc:
+ current_instances.each_value(&:reset)
+ end
+
+ def clear_all # :nodoc:
+ reset_all
+ current_instances.clear
+ end
+
+ private
+ def generated_attribute_methods
+ @generated_attribute_methods ||= Module.new.tap { |mod| include mod }
+ end
+
+ def current_instances
+ Thread.current[:current_attributes_instances] ||= {}
+ end
+
+ def method_missing(name, *args, &block)
+ # Caches the method definition as a singleton method of the receiver.
+ #
+ # By letting #delegate handle it, we avoid an enclosure that'll capture args.
+ singleton_class.delegate name, to: :instance
+
+ send(name, *args, &block)
+ end
+ end
+
+ attr_accessor :attributes
+
+ def initialize
+ @attributes = {}
+ end
+
+ # Expose one or more attributes within a block. Old values are returned after the block concludes.
+ # Example demonstrating the common use of needing to set Current attributes outside the request-cycle:
+ #
+ # class Chat::PublicationJob < ApplicationJob
+ # def perform(attributes, room_number, creator)
+ # Current.set(person: creator) do
+ # Chat::Publisher.publish(attributes: attributes, room_number: room_number)
+ # end
+ # end
+ # end
+ def set(set_attributes)
+ old_attributes = compute_attributes(set_attributes.keys)
+ assign_attributes(set_attributes)
+ yield
+ ensure
+ assign_attributes(old_attributes)
+ end
+
+ # Reset all attributes. Should be called before and after actions, when used as a per-request singleton.
+ def reset
+ run_callbacks :reset do
+ self.attributes = {}
+ end
+ end
+
+ private
+ def assign_attributes(new_attributes)
+ new_attributes.each { |key, value| public_send("#{key}=", value) }
+ end
+
+ def compute_attributes(keys)
+ keys.collect { |key| [ key, public_send(key) ] }.to_h
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 57f6286de3..82c10b3079 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -1,26 +1,26 @@
-require 'set'
-require 'thread'
-require 'concurrent/map'
-require 'pathname'
-require 'active_support/core_ext/module/aliasing'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/module/introspection'
-require 'active_support/core_ext/module/anonymous'
-require 'active_support/core_ext/module/qualified_const'
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/kernel/reporting'
-require 'active_support/core_ext/load_error'
-require 'active_support/core_ext/name_error'
-require 'active_support/core_ext/string/starts_ends_with'
+# frozen_string_literal: true
+
+require "set"
+require "thread"
+require "concurrent/map"
+require "pathname"
+require "active_support/core_ext/module/aliasing"
+require "active_support/core_ext/module/attribute_accessors"
+require "active_support/core_ext/module/introspection"
+require "active_support/core_ext/module/anonymous"
+require "active_support/core_ext/object/blank"
+require "active_support/core_ext/kernel/reporting"
+require "active_support/core_ext/load_error"
+require "active_support/core_ext/name_error"
+require "active_support/core_ext/string/starts_ends_with"
require "active_support/dependencies/interlock"
-require 'active_support/inflector'
+require "active_support/inflector"
module ActiveSupport #:nodoc:
module Dependencies #:nodoc:
extend self
- mattr_accessor :interlock
- self.interlock = Interlock.new
+ mattr_accessor :interlock, default: Interlock.new
# :doc:
@@ -47,46 +47,37 @@ module ActiveSupport #:nodoc:
# :nodoc:
# Should we turn on Ruby warnings on the first load of dependent files?
- mattr_accessor :warnings_on_first_load
- self.warnings_on_first_load = false
+ mattr_accessor :warnings_on_first_load, default: false
# All files ever loaded.
- mattr_accessor :history
- self.history = Set.new
+ mattr_accessor :history, default: Set.new
# All files currently loaded.
- mattr_accessor :loaded
- self.loaded = Set.new
+ mattr_accessor :loaded, default: Set.new
# Stack of files being loaded.
- mattr_accessor :loading
- self.loading = []
+ mattr_accessor :loading, default: []
# Should we load files or require them?
- mattr_accessor :mechanism
- self.mechanism = ENV['NO_RELOAD'] ? :require : :load
+ mattr_accessor :mechanism, default: ENV["NO_RELOAD"] ? :require : :load
# The set of directories from which we may automatically load files. Files
# under these directories will be reloaded on each request in development mode,
# unless the directory also appears in autoload_once_paths.
- mattr_accessor :autoload_paths
- self.autoload_paths = []
+ mattr_accessor :autoload_paths, default: []
# The set of directories from which automatically loaded constants are loaded
# only once. All directories in this set must also be present in +autoload_paths+.
- mattr_accessor :autoload_once_paths
- self.autoload_once_paths = []
+ mattr_accessor :autoload_once_paths, default: []
# An array of qualified constant names that have been loaded. Adding a name
# to this array will cause it to be unloaded the next time Dependencies are
# cleared.
- mattr_accessor :autoloaded_constants
- self.autoloaded_constants = []
+ mattr_accessor :autoloaded_constants, default: []
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
- mattr_accessor :explicitly_unloadable_constants
- self.explicitly_unloadable_constants = []
+ mattr_accessor :explicitly_unloadable_constants, default: []
# The WatchStack keeps a stack of the modules being watched as files are
# loaded. If a file in the process of being loaded (parent.rb) triggers the
@@ -94,7 +85,7 @@ module ActiveSupport #:nodoc:
# handles the new constants.
#
# If child.rb is being autoloaded, its constants will be added to
- # autoloaded_constants. If it was being `require`d, they will be discarded.
+ # autoloaded_constants. If it was being required, they will be discarded.
#
# This is handled by walking back up the watch stack and adding the constants
# found by child.rb to the list of original constants in parent.rb.
@@ -108,7 +99,7 @@ module ActiveSupport #:nodoc:
def initialize
@watching = []
- @stack = Hash.new { |h,k| h[k] = [] }
+ @stack = Hash.new { |h, k| h[k] = [] }
end
def each(&block)
@@ -170,14 +161,13 @@ module ActiveSupport #:nodoc:
end
private
- def pop_modules(modules)
- modules.each { |mod| @stack[mod].pop }
- end
+ def pop_modules(modules)
+ modules.each { |mod| @stack[mod].pop }
+ end
end
# An internal stack used to record which constants are loaded by any block.
- mattr_accessor :constant_watch_stack
- self.constant_watch_stack = WatchStack.new
+ mattr_accessor :constant_watch_stack, default: WatchStack.new
# Module includes this module.
module ModuleConstMissing #:nodoc:
@@ -243,7 +233,7 @@ module ActiveSupport #:nodoc:
# resolution deterministic for constants with the same relative name in
# different namespaces whose evaluation would depend on load order
# otherwise.
- def require_dependency(file_name, message = "No such file to load -- %s")
+ def require_dependency(file_name, message = "No such file to load -- %s.rb")
file_name = file_name.to_path if file_name.respond_to?(:to_path)
unless file_name.is_a?(String)
raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}"
@@ -282,17 +272,17 @@ module ActiveSupport #:nodoc:
private
- def load(file, wrap = false)
- result = false
- load_dependency(file) { result = super }
- result
- end
+ def load(file, wrap = false)
+ result = false
+ load_dependency(file) { result = super }
+ result
+ end
- def require(file)
- result = false
- load_dependency(file) { result = super }
- result
- end
+ def require(file)
+ result = false
+ load_dependency(file) { result = super }
+ result
+ end
end
# Exception file-blaming.
@@ -371,7 +361,7 @@ module ActiveSupport #:nodoc:
load_args = ["#{file_name}.rb"]
load_args << const_path unless const_path.nil?
- if !warnings_on_first_load or history.include?(expanded)
+ if !warnings_on_first_load || history.include?(expanded)
result = load_file(*load_args)
else
enable_warnings { result = load_file(*load_args) }
@@ -503,7 +493,7 @@ module ActiveSupport #:nodoc:
if file_path
expanded = File.expand_path(file_path)
- expanded.sub!(/\.rb\z/, ''.freeze)
+ expanded.sub!(/\.rb\z/, "".freeze)
if loading.include?(expanded)
raise "Circular dependency detected while autoloading constant #{qualified_name}"
@@ -547,7 +537,7 @@ module ActiveSupport #:nodoc:
end
name_error = NameError.new("uninitialized constant #{qualified_name}", const_name)
- name_error.set_backtrace(caller.reject {|l| l.starts_with? __FILE__ })
+ name_error.set_backtrace(caller.reject { |l| l.starts_with? __FILE__ })
raise name_error
end
@@ -591,7 +581,7 @@ module ActiveSupport #:nodoc:
def store(klass)
return self unless klass.respond_to?(:name)
- raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
+ raise(ArgumentError, "anonymous classes cannot be cached") if klass.name.empty?
@store[klass.name] = klass
self
end
@@ -625,7 +615,7 @@ module ActiveSupport #:nodoc:
return false if desc.is_a?(Module) && desc.anonymous?
name = to_constant_name desc
return false unless qualified_const_defined?(name)
- return autoloaded_constants.include?(name)
+ autoloaded_constants.include?(name)
end
# Will the provided constant descriptor be unloaded?
@@ -675,29 +665,29 @@ module ActiveSupport #:nodoc:
# A module, class, symbol, or string may be provided.
def to_constant_name(desc) #:nodoc:
case desc
- when String then desc.sub(/^::/, '')
- when Symbol then desc.to_s
- when Module
- desc.name ||
- raise(ArgumentError, "Anonymous modules have no name to be referenced by")
+ when String then desc.sub(/^::/, "")
+ when Symbol then desc.to_s
+ when Module
+ desc.name ||
+ raise(ArgumentError, "Anonymous modules have no name to be referenced by")
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
end
end
def remove_constant(const) #:nodoc:
# Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
- normalized = const.to_s.sub(/\A::/, '')
- normalized.sub!(/\A(Object::)+/, '')
+ normalized = const.to_s.sub(/\A::/, "")
+ normalized.sub!(/\A(Object::)+/, "")
- constants = normalized.split('::')
+ constants = normalized.split("::")
to_remove = constants.pop
# Remove the file path from the loaded list.
file_path = search_for_file(const.underscore)
if file_path
expanded = File.expand_path(file_path)
- expanded.sub!(/\.rb\z/, '')
- self.loaded.delete(expanded)
+ expanded.sub!(/\.rb\z/, "")
+ loaded.delete(expanded)
end
if constants.empty?
@@ -710,7 +700,7 @@ module ActiveSupport #:nodoc:
# here than require the caller to be clever. We check the parent
# rather than the very const argument because we do not want to
# trigger Kernel#autoloads, see the comment below.
- parent_name = constants.join('::')
+ parent_name = constants.join("::")
return unless qualified_const_defined?(parent_name)
parent = constantize(parent_name)
end
diff --git a/activesupport/lib/active_support/dependencies/autoload.rb b/activesupport/lib/active_support/dependencies/autoload.rb
index 13036d521d..1cee85d98f 100644
--- a/activesupport/lib/active_support/dependencies/autoload.rb
+++ b/activesupport/lib/active_support/dependencies/autoload.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
require "active_support/inflector/methods"
module ActiveSupport
diff --git a/activesupport/lib/active_support/dependencies/interlock.rb b/activesupport/lib/active_support/dependencies/interlock.rb
index f1865ca2f8..948be75638 100644
--- a/activesupport/lib/active_support/dependencies/interlock.rb
+++ b/activesupport/lib/active_support/dependencies/interlock.rb
@@ -1,4 +1,6 @@
-require 'active_support/concurrency/share_lock'
+# frozen_string_literal: true
+
+require "active_support/concurrency/share_lock"
module ActiveSupport #:nodoc:
module Dependencies #:nodoc:
@@ -46,6 +48,10 @@ module ActiveSupport #:nodoc:
yield
end
end
+
+ def raw_state(&block) # :nodoc:
+ @lock.raw_state(&block)
+ end
end
end
end
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index 24545d766c..a1ad2ca465 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -1,4 +1,6 @@
-require 'singleton'
+# frozen_string_literal: true
+
+require "singleton"
module ActiveSupport
# \Deprecation specifies the API used by Rails to deprecate methods, instance
@@ -12,12 +14,13 @@ module ActiveSupport
# a circular require warning for active_support/deprecation.rb.
#
# So, we define the constant first, and load dependencies later.
- require 'active_support/deprecation/instance_delegator'
- require 'active_support/deprecation/behaviors'
- require 'active_support/deprecation/reporting'
- require 'active_support/deprecation/method_wrappers'
- require 'active_support/deprecation/proxy_wrappers'
- require 'active_support/core_ext/module/deprecation'
+ require "active_support/deprecation/instance_delegator"
+ require "active_support/deprecation/behaviors"
+ require "active_support/deprecation/reporting"
+ require "active_support/deprecation/constant_accessor"
+ require "active_support/deprecation/method_wrappers"
+ require "active_support/deprecation/proxy_wrappers"
+ require "active_support/core_ext/module/deprecation"
include Singleton
include InstanceDelegator
@@ -29,10 +32,10 @@ module ActiveSupport
attr_accessor :deprecation_horizon
# It accepts two parameters on initialization. The first is a version of library
- # and the second is a library name
+ # and the second is a library name.
#
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
- def initialize(deprecation_horizon = '5.1', gem_name = 'Rails')
+ def initialize(deprecation_horizon = "6.0", gem_name = "Rails")
self.gem_name = gem_name
self.deprecation_horizon = deprecation_horizon
# By default, warnings are not silenced and debugging is off.
diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb
index dc24e2d0e1..581db5f449 100644
--- a/activesupport/lib/active_support/deprecation/behaviors.rb
+++ b/activesupport/lib/active_support/deprecation/behaviors.rb
@@ -1,43 +1,49 @@
+# frozen_string_literal: true
+
require "active_support/notifications"
module ActiveSupport
# Raised when <tt>ActiveSupport::Deprecation::Behavior#behavior</tt> is set with <tt>:raise</tt>.
- # You would set <tt>:raise</tt>, as a behaviour to raise errors and proactively report exceptions from deprecations.
+ # You would set <tt>:raise</tt>, as a behavior to raise errors and proactively report exceptions from deprecations.
class DeprecationException < StandardError
end
class Deprecation
# Default warning behaviors per Rails.env.
DEFAULT_BEHAVIORS = {
- raise: ->(message, callstack) {
+ raise: ->(message, callstack, deprecation_horizon, gem_name) {
e = DeprecationException.new(message)
e.set_backtrace(callstack.map(&:to_s))
raise e
},
- stderr: ->(message, callstack) {
+ stderr: ->(message, callstack, deprecation_horizon, gem_name) {
$stderr.puts(message)
$stderr.puts callstack.join("\n ") if debug
},
- log: ->(message, callstack) {
+ log: ->(message, callstack, deprecation_horizon, gem_name) {
logger =
if defined?(Rails.logger) && Rails.logger
Rails.logger
else
- require 'active_support/logger'
+ require "active_support/logger"
ActiveSupport::Logger.new($stderr)
end
logger.warn message
logger.debug callstack.join("\n ") if debug
},
- notify: ->(message, callstack) {
- ActiveSupport::Notifications.instrument("deprecation.rails",
- :message => message, :callstack => callstack)
+ notify: ->(message, callstack, deprecation_horizon, gem_name) {
+ notification_name = "deprecation.#{gem_name.underscore.tr('/', '_')}"
+ ActiveSupport::Notifications.instrument(notification_name,
+ message: message,
+ callstack: callstack,
+ gem_name: gem_name,
+ deprecation_horizon: deprecation_horizon)
},
- silence: ->(message, callstack) {},
+ silence: ->(message, callstack, deprecation_horizon, gem_name) {},
}
# Behavior module allows to determine how to display deprecation messages.
@@ -83,8 +89,17 @@ module ActiveSupport
# # custom stuff
# }
def behavior=(behavior)
- @behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
+ @behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || arity_coerce(b) }
end
+
+ private
+ def arity_coerce(behavior)
+ if behavior.arity == 4 || behavior.arity == -1
+ behavior
+ else
+ -> message, callstack, _, _ { behavior.call(message, callstack) }
+ end
+ end
end
end
end
diff --git a/activesupport/lib/active_support/deprecation/constant_accessor.rb b/activesupport/lib/active_support/deprecation/constant_accessor.rb
new file mode 100644
index 0000000000..1ed0015812
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/constant_accessor.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module ActiveSupport
+ class Deprecation
+ # DeprecatedConstantAccessor transforms a constant into a deprecated one by
+ # hooking +const_missing+.
+ #
+ # It takes the names of an old (deprecated) constant and of a new constant
+ # (both in string form) and optionally a deprecator. The deprecator defaults
+ # to +ActiveSupport::Deprecator+ if none is specified.
+ #
+ # The deprecated constant now returns the same object as the new one rather
+ # than a proxy object, so it can be used transparently in +rescue+ blocks
+ # etc.
+ #
+ # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto)
+ #
+ # # (In a later update, the original implementation of `PLANETS` has been removed.)
+ #
+ # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
+ # include ActiveSupport::Deprecation::DeprecatedConstantAccessor
+ # deprecate_constant 'PLANETS', 'PLANETS_POST_2006'
+ #
+ # PLANETS.map { |planet| planet.capitalize }
+ # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead.
+ # (Backtrace information…)
+ # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+ module DeprecatedConstantAccessor
+ def self.included(base)
+ require "active_support/inflector/methods"
+
+ extension = Module.new do
+ def const_missing(missing_const_name)
+ if class_variable_defined?(:@@_deprecated_constants)
+ if (replacement = class_variable_get(:@@_deprecated_constants)[missing_const_name.to_s])
+ replacement[:deprecator].warn(replacement[:message] || "#{name}::#{missing_const_name} is deprecated! Use #{replacement[:new]} instead.", caller_locations)
+ return ActiveSupport::Inflector.constantize(replacement[:new].to_s)
+ end
+ end
+ super
+ end
+
+ def deprecate_constant(const_name, new_constant, message: nil, deprecator: ActiveSupport::Deprecation.instance)
+ class_variable_set(:@@_deprecated_constants, {}) unless class_variable_defined?(:@@_deprecated_constants)
+ class_variable_get(:@@_deprecated_constants)[const_name.to_s] = { new: new_constant, message: message, deprecator: deprecator }
+ end
+ end
+ base.singleton_class.prepend extension
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation/instance_delegator.rb b/activesupport/lib/active_support/deprecation/instance_delegator.rb
index 8472a58add..8beda373a2 100644
--- a/activesupport/lib/active_support/deprecation/instance_delegator.rb
+++ b/activesupport/lib/active_support/deprecation/instance_delegator.rb
@@ -1,11 +1,14 @@
-require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/module/delegation'
+# frozen_string_literal: true
+
+require "active_support/core_ext/kernel/singleton_class"
+require "active_support/core_ext/module/delegation"
module ActiveSupport
class Deprecation
module InstanceDelegator # :nodoc:
def self.included(base)
base.extend(ClassMethods)
+ base.singleton_class.prepend(OverrideDelegators)
base.public_class_method :new
end
@@ -19,6 +22,18 @@ module ActiveSupport
singleton_class.delegate(method_name, to: :instance)
end
end
+
+ module OverrideDelegators # :nodoc:
+ def warn(message = nil, callstack = nil)
+ callstack ||= caller_locations(2)
+ super
+ end
+
+ def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)
+ caller_backtrace ||= caller_locations(2)
+ super
+ end
+ end
end
end
end
diff --git a/activesupport/lib/active_support/deprecation/method_wrappers.rb b/activesupport/lib/active_support/deprecation/method_wrappers.rb
index f5ea6669ce..5be893d281 100644
--- a/activesupport/lib/active_support/deprecation/method_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/method_wrappers.rb
@@ -1,14 +1,14 @@
-require 'active_support/core_ext/module/aliasing'
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/aliasing"
+require "active_support/core_ext/array/extract_options"
module ActiveSupport
class Deprecation
module MethodWrapper
# Declare that a method has been deprecated.
#
- # module Fred
- # extend self
- #
+ # class Fred
# def aaa; end
# def bbb; end
# def ccc; end
@@ -18,17 +18,17 @@ module ActiveSupport
#
# Using the default deprecator:
# ActiveSupport::Deprecation.deprecate_methods(Fred, :aaa, bbb: :zzz, ccc: 'use Bar#ccc instead')
- # # => [:aaa, :bbb, :ccc]
+ # # => Fred
#
- # Fred.aaa
+ # Fred.new.aaa
# # DEPRECATION WARNING: aaa is deprecated and will be removed from Rails 5.1. (called from irb_binding at (irb):10)
# # => nil
#
- # Fred.bbb
+ # Fred.new.bbb
# # DEPRECATION WARNING: bbb is deprecated and will be removed from Rails 5.1 (use zzz instead). (called from irb_binding at (irb):11)
# # => nil
#
- # Fred.ccc
+ # Fred.new.ccc
# # DEPRECATION WARNING: ccc is deprecated and will be removed from Rails 5.1 (use Bar#ccc instead). (called from irb_binding at (irb):12)
# # => nil
#
@@ -37,7 +37,7 @@ module ActiveSupport
# ActiveSupport::Deprecation.deprecate_methods(Fred, ddd: :zzz, deprecator: custom_deprecator)
# # => [:ddd]
#
- # Fred.ddd
+ # Fred.new.ddd
# DEPRECATION WARNING: ddd is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):15)
# # => nil
#
@@ -46,7 +46,7 @@ module ActiveSupport
# custom_deprecator.deprecate_methods(Fred, eee: :zzz)
# # => [:eee]
#
- # Fred.eee
+ # Fred.new.eee
# DEPRECATION WARNING: eee is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):18)
# # => nil
def deprecate_methods(target_module, *method_names)
@@ -60,6 +60,13 @@ module ActiveSupport
deprecator.deprecation_warning(method_name, options[method_name])
super(*args, &block)
end
+
+ case
+ when target_module.protected_method_defined?(method_name)
+ protected method_name
+ when target_module.private_method_defined?(method_name)
+ private method_name
+ end
end
end
diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
index 0cb2d4d22e..896c0d2d8e 100644
--- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
@@ -1,4 +1,6 @@
-require 'active_support/inflector/methods'
+# frozen_string_literal: true
+
+require "active_support/core_ext/regexp"
module ActiveSupport
class Deprecation
@@ -10,7 +12,7 @@ module ActiveSupport
super
end
- instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
+ instance_methods.each { |m| undef_method m unless /^__|^object_id$/.match?(m) }
# Don't give a deprecation warning on inspect since test/unit and error
# logs rely on it for diagnostics.
@@ -111,7 +113,7 @@ module ActiveSupport
#
# PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto)
#
- # (In a later update, the original implementation of `PLANETS` has been removed.)
+ # # (In a later update, the original implementation of `PLANETS` has been removed.)
#
# PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
# PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006')
@@ -121,10 +123,13 @@ module ActiveSupport
# (Backtrace information…)
# ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
class DeprecatedConstantProxy < DeprecationProxy
- def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
+ def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance, message: "#{old_const} is deprecated! Use #{new_const} instead.")
+ require "active_support/inflector/methods"
+
@old_const = old_const
@new_const = new_const
@deprecator = deprecator
+ @message = message
end
# Returns the class of the new constant.
@@ -142,7 +147,7 @@ module ActiveSupport
end
def warn(callstack, called, args)
- @deprecator.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
+ @deprecator.warn(@message, callstack)
end
end
end
diff --git a/activesupport/lib/active_support/deprecation/reporting.rb b/activesupport/lib/active_support/deprecation/reporting.rb
index de5b233679..242e21b782 100644
--- a/activesupport/lib/active_support/deprecation/reporting.rb
+++ b/activesupport/lib/active_support/deprecation/reporting.rb
@@ -1,4 +1,6 @@
-require 'rbconfig'
+# frozen_string_literal: true
+
+require "rbconfig"
module ActiveSupport
class Deprecation
@@ -18,7 +20,7 @@ module ActiveSupport
callstack ||= caller_locations(2)
deprecation_message(callstack, message).tap do |m|
- behavior.each { |b| b.call(m, callstack) }
+ behavior.each { |b| b.call(m, callstack, deprecation_horizon, gem_name) }
end
end
@@ -48,17 +50,17 @@ module ActiveSupport
private
# Outputs a deprecation warning message
#
- # ActiveSupport::Deprecation.deprecated_method_warning(:method_name)
+ # deprecated_method_warning(:method_name)
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
- # ActiveSupport::Deprecation.deprecated_method_warning(:method_name, :another_method)
+ # deprecated_method_warning(:method_name, :another_method)
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
- # ActiveSupport::Deprecation.deprecated_method_warning(:method_name, "Optional message")
+ # deprecated_method_warning(:method_name, "Optional message")
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)"
def deprecated_method_warning(method_name, message = nil)
warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
case message
- when Symbol then "#{warning} (use #{message} instead)"
- when String then "#{warning} (#{message})"
+ when Symbol then "#{warning} (use #{message} instead)"
+ when String then "#{warning} (#{message})"
else warning
end
end
@@ -102,10 +104,10 @@ module ActiveSupport
end
end
- RAILS_GEM_ROOT = File.expand_path("../../../../..", __FILE__) + "/"
+ RAILS_GEM_ROOT = File.expand_path("../../../..", __dir__)
def ignored_callstack(path)
- path.start_with?(RAILS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG['rubylibdir'])
+ path.start_with?(RAILS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG["rubylibdir"])
end
end
end
diff --git a/activesupport/lib/active_support/descendants_tracker.rb b/activesupport/lib/active_support/descendants_tracker.rb
index 27861e01d0..a4cee788b6 100644
--- a/activesupport/lib/active_support/descendants_tracker.rb
+++ b/activesupport/lib/active_support/descendants_tracker.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# This module provides an internal implementation to track descendants
# which is faster than iterating through ObjectSpace.
diff --git a/activesupport/lib/active_support/digest.rb b/activesupport/lib/active_support/digest.rb
new file mode 100644
index 0000000000..fba10fbdcf
--- /dev/null
+++ b/activesupport/lib/active_support/digest.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module ActiveSupport
+ class Digest #:nodoc:
+ class <<self
+ def hash_digest_class
+ @hash_digest_class ||= ::Digest::MD5
+ end
+
+ def hash_digest_class=(klass)
+ raise ArgumentError, "#{klass} is expected to implement hexdigest class method" unless klass.respond_to?(:hexdigest)
+ @hash_digest_class = klass
+ end
+
+ def hexdigest(arg)
+ hash_digest_class.hexdigest(arg)[0...32]
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 47d09f4f5a..fe1058762b 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -1,5 +1,10 @@
-require 'active_support/core_ext/array/conversions'
-require 'active_support/core_ext/object/acts_like'
+# frozen_string_literal: true
+
+require "active_support/core_ext/array/conversions"
+require "active_support/core_ext/module/delegation"
+require "active_support/core_ext/object/acts_like"
+require "active_support/core_ext/string/filters"
+require "active_support/deprecation"
module ActiveSupport
# Provides accurate date and time measurements using Date#advance and
@@ -7,22 +12,237 @@ module ActiveSupport
#
# 1.month.ago # equivalent to Time.now.advance(months: -1)
class Duration
+ class Scalar < Numeric #:nodoc:
+ attr_reader :value
+ delegate :to_i, :to_f, :to_s, to: :value
+
+ def initialize(value)
+ @value = value
+ end
+
+ def coerce(other)
+ [Scalar.new(other), self]
+ end
+
+ def -@
+ Scalar.new(-value)
+ end
+
+ def <=>(other)
+ if Scalar === other || Duration === other
+ value <=> other.value
+ elsif Numeric === other
+ value <=> other
+ else
+ nil
+ end
+ end
+
+ def +(other)
+ if Duration === other
+ seconds = value + other.parts[:seconds]
+ new_parts = other.parts.merge(seconds: seconds)
+ new_value = value + other.value
+
+ Duration.new(new_value, new_parts)
+ else
+ calculate(:+, other)
+ end
+ end
+
+ def -(other)
+ if Duration === other
+ seconds = value - other.parts[:seconds]
+ new_parts = other.parts.map { |part, other_value| [part, -other_value] }.to_h
+ new_parts = new_parts.merge(seconds: seconds)
+ new_value = value - other.value
+
+ Duration.new(new_value, new_parts)
+ else
+ calculate(:-, other)
+ end
+ end
+
+ def *(other)
+ if Duration === other
+ new_parts = other.parts.map { |part, other_value| [part, value * other_value] }.to_h
+ new_value = value * other.value
+
+ Duration.new(new_value, new_parts)
+ else
+ calculate(:*, other)
+ end
+ end
+
+ def /(other)
+ if Duration === other
+ value / other.value
+ else
+ calculate(:/, other)
+ end
+ end
+
+ def %(other)
+ if Duration === other
+ Duration.build(value % other.value)
+ else
+ calculate(:%, other)
+ end
+ end
+
+ private
+ def calculate(op, other)
+ if Scalar === other
+ Scalar.new(value.public_send(op, other.value))
+ elsif Numeric === other
+ Scalar.new(value.public_send(op, other))
+ else
+ raise_type_error(other)
+ end
+ end
+
+ def raise_type_error(other)
+ raise TypeError, "no implicit conversion of #{other.class} into #{self.class}"
+ end
+ end
+
+ SECONDS_PER_MINUTE = 60
+ SECONDS_PER_HOUR = 3600
+ SECONDS_PER_DAY = 86400
+ SECONDS_PER_WEEK = 604800
+ SECONDS_PER_MONTH = 2629746 # 1/12 of a gregorian year
+ SECONDS_PER_YEAR = 31556952 # length of a gregorian year (365.2425 days)
+
+ PARTS_IN_SECONDS = {
+ seconds: 1,
+ minutes: SECONDS_PER_MINUTE,
+ hours: SECONDS_PER_HOUR,
+ days: SECONDS_PER_DAY,
+ weeks: SECONDS_PER_WEEK,
+ months: SECONDS_PER_MONTH,
+ years: SECONDS_PER_YEAR
+ }.freeze
+
+ PARTS = [:years, :months, :weeks, :days, :hours, :minutes, :seconds].freeze
+
attr_accessor :value, :parts
- autoload :ISO8601Parser, 'active_support/duration/iso8601_parser'
- autoload :ISO8601Serializer, 'active_support/duration/iso8601_serializer'
+ autoload :ISO8601Parser, "active_support/duration/iso8601_parser"
+ autoload :ISO8601Serializer, "active_support/duration/iso8601_serializer"
+
+ class << self
+ # Creates a new Duration from string formatted according to ISO 8601 Duration.
+ #
+ # See {ISO 8601}[https://en.wikipedia.org/wiki/ISO_8601#Durations] for more information.
+ # This method allows negative parts to be present in pattern.
+ # If invalid string is provided, it will raise +ActiveSupport::Duration::ISO8601Parser::ParsingError+.
+ def parse(iso8601duration)
+ parts = ISO8601Parser.new(iso8601duration).parse!
+ new(calculate_total_seconds(parts), parts)
+ end
+
+ def ===(other) #:nodoc:
+ other.is_a?(Duration)
+ rescue ::NoMethodError
+ false
+ end
+
+ def seconds(value) #:nodoc:
+ new(value, [[:seconds, value]])
+ end
+
+ def minutes(value) #:nodoc:
+ new(value * SECONDS_PER_MINUTE, [[:minutes, value]])
+ end
+
+ def hours(value) #:nodoc:
+ new(value * SECONDS_PER_HOUR, [[:hours, value]])
+ end
+
+ def days(value) #:nodoc:
+ new(value * SECONDS_PER_DAY, [[:days, value]])
+ end
+
+ def weeks(value) #:nodoc:
+ new(value * SECONDS_PER_WEEK, [[:weeks, value]])
+ end
+
+ def months(value) #:nodoc:
+ new(value * SECONDS_PER_MONTH, [[:months, value]])
+ end
+
+ def years(value) #:nodoc:
+ new(value * SECONDS_PER_YEAR, [[:years, value]])
+ end
+
+ # Creates a new Duration from a seconds value that is converted
+ # to the individual parts:
+ #
+ # ActiveSupport::Duration.build(31556952).parts # => {:years=>1}
+ # ActiveSupport::Duration.build(2716146).parts # => {:months=>1, :days=>1}
+ #
+ def build(value)
+ parts = {}
+ remainder = value.to_f
+
+ PARTS.each do |part|
+ unless part == :seconds
+ part_in_seconds = PARTS_IN_SECONDS[part]
+ parts[part] = remainder.div(part_in_seconds)
+ remainder = (remainder % part_in_seconds).round(9)
+ end
+ end
+
+ parts[:seconds] = remainder
+
+ new(value, parts)
+ end
+
+ private
+
+ def calculate_total_seconds(parts)
+ parts.inject(0) do |total, (part, value)|
+ total + value * PARTS_IN_SECONDS[part]
+ end
+ end
+ end
def initialize(value, parts) #:nodoc:
- @value, @parts = value, parts
+ @value, @parts = value, parts.to_h
+ @parts.default = 0
+ @parts.reject! { |k, v| v.zero? }
+ end
+
+ def coerce(other) #:nodoc:
+ if Scalar === other
+ [other, self]
+ else
+ [Scalar.new(other), self]
+ end
+ end
+
+ # Compares one Duration with another or a Numeric to this Duration.
+ # Numeric values are treated as seconds.
+ def <=>(other)
+ if Duration === other
+ value <=> other.value
+ elsif Numeric === other
+ value <=> other
+ end
end
# Adds another Duration or a Numeric to this Duration. Numeric values
# are treated as seconds.
def +(other)
if Duration === other
- Duration.new(value + other.value, @parts + other.parts)
+ parts = @parts.dup
+ other.parts.each do |(key, value)|
+ parts[key] += value
+ end
+ Duration.new(value + other.value, parts)
else
- Duration.new(value + other, @parts + [[:seconds, other]])
+ seconds = @parts[:seconds] + other
+ Duration.new(value + other, @parts.merge(seconds: seconds))
end
end
@@ -32,8 +252,44 @@ module ActiveSupport
self + (-other)
end
+ # Multiplies this Duration by a Numeric and returns a new Duration.
+ def *(other)
+ if Scalar === other || Duration === other
+ Duration.new(value * other.value, parts.map { |type, number| [type, number * other.value] })
+ elsif Numeric === other
+ Duration.new(value * other, parts.map { |type, number| [type, number * other] })
+ else
+ raise_type_error(other)
+ end
+ end
+
+ # Divides this Duration by a Numeric and returns a new Duration.
+ def /(other)
+ if Scalar === other
+ Duration.new(value / other.value, parts.map { |type, number| [type, number / other.value] })
+ elsif Duration === other
+ value / other.value
+ elsif Numeric === other
+ Duration.new(value / other, parts.map { |type, number| [type, number / other] })
+ else
+ raise_type_error(other)
+ end
+ end
+
+ # Returns the modulo of this Duration by another Duration or Numeric.
+ # Numeric values are treated as seconds.
+ def %(other)
+ if Duration === other || Scalar === other
+ Duration.build(value % other.value)
+ elsif Numeric === other
+ Duration.build(value % other)
+ else
+ raise_type_error(other)
+ end
+ end
+
def -@ #:nodoc:
- Duration.new(-value, parts.map { |type,number| [type, -number] })
+ Duration.new(-value, parts.map { |type, number| [type, -number] })
end
def is_a?(klass) #:nodoc:
@@ -70,14 +326,14 @@ module ActiveSupport
# 1.day.to_i # => 86400
#
# Note that this conversion makes some assumptions about the
- # duration of some periods, e.g. months are always 30 days
- # and years are 365.25 days:
+ # duration of some periods, e.g. months are always 1/12 of year
+ # and years are 365.2425 days:
#
- # # equivalent to 30.days.to_i
- # 1.month.to_i # => 2592000
+ # # equivalent to (1.year / 12).to_i
+ # 1.month.to_i # => 2629746
#
- # # equivalent to 365.25.days.to_i
- # 1.year.to_i # => 31557600
+ # # equivalent to 365.2425.days.to_i
+ # 1.year.to_i # => 31556952
#
# In such cases, Ruby's core
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
@@ -97,18 +353,13 @@ module ActiveSupport
@value.hash
end
- def self.===(other) #:nodoc:
- other.is_a?(Duration)
- rescue ::NoMethodError
- false
- end
-
# Calculates a new Time or Date that is as far in the future
# as this Duration represents.
def since(time = ::Time.current)
sum(1, time)
end
alias :from_now :since
+ alias :after :since
# Calculates a new Time or Date that is as far in the past
# as this Duration represents.
@@ -116,12 +367,15 @@ module ActiveSupport
sum(-1, time)
end
alias :until :ago
+ alias :before :ago
def inspect #:nodoc:
+ return "0 seconds" if parts.empty?
+
parts.
- reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
- sort_by {|unit, _ | [:years, :months, :weeks, :days, :hours, :minutes, :seconds].index(unit)}.
- map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
+ reduce(::Hash.new(0)) { |h, (l, r)| h[l] += r; h }.
+ sort_by { |unit, _ | PARTS.index(unit) }.
+ map { |unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}" }.
to_sentence(locale: ::I18n.default_locale)
end
@@ -129,33 +383,16 @@ module ActiveSupport
to_i
end
- def respond_to_missing?(method, include_private=false) #:nodoc:
- @value.respond_to?(method, include_private)
- end
-
- # Creates a new Duration from string formatted according to ISO 8601 Duration.
- #
- # See {ISO 8601}[http://en.wikipedia.org/wiki/ISO_8601#Durations] for more information.
- # This method allows negative parts to be present in pattern.
- # If invalid string is provided, it will raise +ActiveSupport::Duration::ISO8601Parser::ParsingError+.
- def self.parse(iso8601duration)
- parts = ISO8601Parser.new(iso8601duration).parse!
- time = ::Time.current
- new(time.advance(parts) - time, parts)
- end
-
# Build ISO 8601 Duration string for this duration.
# The +precision+ parameter can be used to limit seconds' precision of duration.
def iso8601(precision: nil)
ISO8601Serializer.new(self, precision: precision).serialize
end
- delegate :<=>, to: :value
-
- protected
+ private
- def sum(sign, time = ::Time.current) #:nodoc:
- parts.inject(time) do |t,(type,number)|
+ def sum(sign, time = ::Time.current)
+ parts.inject(time) do |t, (type, number)|
if t.acts_like?(:time) || t.acts_like?(:date)
if type == :seconds
t.since(sign * number)
@@ -172,10 +409,16 @@ module ActiveSupport
end
end
- private
+ def respond_to_missing?(method, _)
+ value.respond_to?(method)
+ end
+
+ def method_missing(method, *args, &block)
+ value.public_send(method, *args, &block)
+ end
- def method_missing(method, *args, &block) #:nodoc:
- value.send(method, *args, &block)
+ def raise_type_error(other)
+ raise TypeError, "no implicit conversion of #{other.class} into #{self.class}"
end
end
end
diff --git a/activesupport/lib/active_support/duration/iso8601_parser.rb b/activesupport/lib/active_support/duration/iso8601_parser.rb
index 07af58ad99..1847eeaa86 100644
--- a/activesupport/lib/active_support/duration/iso8601_parser.rb
+++ b/activesupport/lib/active_support/duration/iso8601_parser.rb
@@ -1,18 +1,21 @@
-require 'strscan'
+# frozen_string_literal: true
+
+require "strscan"
+require "active_support/core_ext/regexp"
module ActiveSupport
class Duration
# Parses a string formatted according to ISO 8601 Duration into the hash.
#
- # See {ISO 8601}[http://en.wikipedia.org/wiki/ISO_8601#Durations] for more information.
+ # See {ISO 8601}[https://en.wikipedia.org/wiki/ISO_8601#Durations] for more information.
#
# This parser allows negative parts to be present in pattern.
class ISO8601Parser # :nodoc:
class ParsingError < ::ArgumentError; end
PERIOD_OR_COMMA = /\.|,/
- PERIOD = '.'.freeze
- COMMA = ','.freeze
+ PERIOD = ".".freeze
+ COMMA = ",".freeze
SIGN_MARKER = /\A\-|\+|/
DATE_MARKER = /P/
@@ -20,8 +23,8 @@ module ActiveSupport
DATE_COMPONENT = /(\-?\d+(?:[.,]\d+)?)(Y|M|D|W)/
TIME_COMPONENT = /(\-?\d+(?:[.,]\d+)?)(H|M|S)/
- DATE_TO_PART = { 'Y' => :years, 'M' => :months, 'W' => :weeks, 'D' => :days }
- TIME_TO_PART = { 'H' => :hours, 'M' => :minutes, 'S' => :seconds }
+ DATE_TO_PART = { "Y" => :years, "M" => :months, "W" => :weeks, "D" => :days }
+ TIME_TO_PART = { "H" => :hours, "M" => :minutes, "S" => :seconds }
DATE_COMPONENTS = [:years, :months, :days]
TIME_COMPONENTS = [:hours, :minutes, :seconds]
@@ -39,36 +42,36 @@ module ActiveSupport
def parse!
while !finished?
case mode
- when :start
- if scan(SIGN_MARKER)
- self.sign = (scanner.matched == '-') ? -1 : 1
- self.mode = :sign
- else
- raise_parsing_error
- end
-
- when :sign
- if scan(DATE_MARKER)
- self.mode = :date
- else
- raise_parsing_error
- end
-
- when :date
- if scan(TIME_MARKER)
- self.mode = :time
- elsif scan(DATE_COMPONENT)
- parts[DATE_TO_PART[scanner[2]]] = number * sign
- else
- raise_parsing_error
- end
-
- when :time
- if scan(TIME_COMPONENT)
- parts[TIME_TO_PART[scanner[2]]] = number * sign
- else
- raise_parsing_error
- end
+ when :start
+ if scan(SIGN_MARKER)
+ self.sign = (scanner.matched == "-") ? -1 : 1
+ self.mode = :sign
+ else
+ raise_parsing_error
+ end
+
+ when :sign
+ if scan(DATE_MARKER)
+ self.mode = :date
+ else
+ raise_parsing_error
+ end
+
+ when :date
+ if scan(TIME_MARKER)
+ self.mode = :time
+ elsif scan(DATE_COMPONENT)
+ parts[DATE_TO_PART[scanner[2]]] = number * sign
+ else
+ raise_parsing_error
+ end
+
+ when :time
+ if scan(TIME_COMPONENT)
+ parts[TIME_TO_PART[scanner[2]]] = number * sign
+ else
+ raise_parsing_error
+ end
end
end
@@ -79,44 +82,44 @@ module ActiveSupport
private
- def finished?
- scanner.eos?
- end
+ def finished?
+ scanner.eos?
+ end
- # Parses number which can be a float with either comma or period.
- def number
- scanner[1] =~ PERIOD_OR_COMMA ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i
- end
+ # Parses number which can be a float with either comma or period.
+ def number
+ PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i
+ end
- def scan(pattern)
- scanner.scan(pattern)
- end
+ def scan(pattern)
+ scanner.scan(pattern)
+ end
- def raise_parsing_error(reason = nil)
- raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip
- end
+ def raise_parsing_error(reason = nil)
+ raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip
+ end
- # Checks for various semantic errors as stated in ISO 8601 standard.
- def validate!
- raise_parsing_error('is empty duration') if parts.empty?
+ # Checks for various semantic errors as stated in ISO 8601 standard.
+ def validate!
+ raise_parsing_error("is empty duration") if parts.empty?
- # Mixing any of Y, M, D with W is invalid.
- if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any?
- raise_parsing_error('mixing weeks with other date parts not allowed')
- end
+ # Mixing any of Y, M, D with W is invalid.
+ if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any?
+ raise_parsing_error("mixing weeks with other date parts not allowed")
+ end
- # Specifying an empty T part is invalid.
- if mode == :time && (parts.keys & TIME_COMPONENTS).empty?
- raise_parsing_error('time part marker is present but time part is empty')
- end
+ # Specifying an empty T part is invalid.
+ if mode == :time && (parts.keys & TIME_COMPONENTS).empty?
+ raise_parsing_error("time part marker is present but time part is empty")
+ end
- fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 }
- unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last)
- raise_parsing_error '(only last part can be fractional)'
- end
+ fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 }
+ unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last)
+ raise_parsing_error "(only last part can be fractional)"
+ end
- return true
- end
+ true
+ end
end
end
end
diff --git a/activesupport/lib/active_support/duration/iso8601_serializer.rb b/activesupport/lib/active_support/duration/iso8601_serializer.rb
index 05c6a083a9..bb177ae5b7 100644
--- a/activesupport/lib/active_support/duration/iso8601_serializer.rb
+++ b/activesupport/lib/active_support/duration/iso8601_serializer.rb
@@ -1,10 +1,12 @@
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/hash/transform_values'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/blank"
+require "active_support/core_ext/hash/transform_values"
module ActiveSupport
class Duration
# Serializes duration to string according to ISO 8601 Duration format.
- class ISO8601Serializer
+ class ISO8601Serializer # :nodoc:
def initialize(duration, precision: nil)
@duration = duration
@precision = precision
@@ -12,19 +14,21 @@ module ActiveSupport
# Builds and returns output string.
def serialize
- output = 'P'
parts, sign = normalize
+ return "PT0S".freeze if parts.empty?
+
+ output = "P".dup
output << "#{parts[:years]}Y" if parts.key?(:years)
output << "#{parts[:months]}M" if parts.key?(:months)
output << "#{parts[:weeks]}W" if parts.key?(:weeks)
output << "#{parts[:days]}D" if parts.key?(:days)
- time = ''
+ time = "".dup
time << "#{parts[:hours]}H" if parts.key?(:hours)
time << "#{parts[:minutes]}M" if parts.key?(:minutes)
if parts.key?(:seconds)
time << "#{sprintf(@precision ? "%0.0#{@precision}f" : '%g', parts[:seconds])}S"
end
- output << "T#{time}" if time.present?
+ output << "T#{time}" unless time.empty?
"#{sign}#{output}"
end
@@ -35,13 +39,13 @@ module ActiveSupport
# Zero parts are removed as not significant.
# If all parts are negative it will negate all of them and return minus as a sign.
def normalize
- parts = @duration.parts.each_with_object(Hash.new(0)) do |(k,v),p|
+ parts = @duration.parts.each_with_object(Hash.new(0)) do |(k, v), p|
p[k] += v unless v.zero?
end
# If all parts are negative - let's make a negative duration
- sign = ''
+ sign = ""
if parts.values.all? { |v| v < 0 }
- sign = '-'
+ sign = "-"
parts.transform_values!(&:-@)
end
[parts, sign]
diff --git a/activesupport/lib/active_support/encrypted_configuration.rb b/activesupport/lib/active_support/encrypted_configuration.rb
new file mode 100644
index 0000000000..dab953d5d5
--- /dev/null
+++ b/activesupport/lib/active_support/encrypted_configuration.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+require "yaml"
+require "active_support/encrypted_file"
+require "active_support/ordered_options"
+require "active_support/core_ext/object/inclusion"
+require "active_support/core_ext/module/delegation"
+
+module ActiveSupport
+ class EncryptedConfiguration < EncryptedFile
+ delegate :[], :fetch, to: :config
+ delegate_missing_to :options
+
+ def initialize(config_path:, key_path:, env_key:, raise_if_missing_key:)
+ super content_path: config_path, key_path: key_path,
+ env_key: env_key, raise_if_missing_key: raise_if_missing_key
+ end
+
+ # Allow a config to be started without a file present
+ def read
+ super
+ rescue ActiveSupport::EncryptedFile::MissingContentError
+ ""
+ end
+
+ def write(contents)
+ deserialize(contents)
+
+ super
+ end
+
+ def config
+ @config ||= deserialize(read).deep_symbolize_keys
+ end
+
+ private
+ def options
+ @options ||= ActiveSupport::InheritableOptions.new(config)
+ end
+
+ def serialize(config)
+ config.present? ? YAML.dump(config) : ""
+ end
+
+ def deserialize(config)
+ config.present? ? YAML.load(config, content_path) : {}
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/encrypted_file.rb b/activesupport/lib/active_support/encrypted_file.rb
new file mode 100644
index 0000000000..671b6b6a69
--- /dev/null
+++ b/activesupport/lib/active_support/encrypted_file.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+require "pathname"
+require "active_support/message_encryptor"
+
+module ActiveSupport
+ class EncryptedFile
+ class MissingContentError < RuntimeError
+ def initialize(content_path)
+ super "Missing encrypted content file in #{content_path}."
+ end
+ end
+
+ class MissingKeyError < RuntimeError
+ def initialize(key_path:, env_key:)
+ super \
+ "Missing encryption key to decrypt file with. " +
+ "Ask your team for your master key and write it to #{key_path} or put it in the ENV['#{env_key}']."
+ end
+ end
+
+ CIPHER = "aes-128-gcm"
+
+ def self.generate_key
+ SecureRandom.hex(ActiveSupport::MessageEncryptor.key_len(CIPHER))
+ end
+
+
+ attr_reader :content_path, :key_path, :env_key, :raise_if_missing_key
+
+ def initialize(content_path:, key_path:, env_key:, raise_if_missing_key:)
+ @content_path, @key_path = Pathname.new(content_path), Pathname.new(key_path)
+ @env_key, @raise_if_missing_key = env_key, raise_if_missing_key
+ end
+
+ def key
+ read_env_key || read_key_file || handle_missing_key
+ end
+
+ def read
+ if !key.nil? && content_path.exist?
+ decrypt content_path.binread
+ else
+ raise MissingContentError, content_path
+ end
+ end
+
+ def write(contents)
+ IO.binwrite "#{content_path}.tmp", encrypt(contents)
+ FileUtils.mv "#{content_path}.tmp", content_path
+ end
+
+ def change(&block)
+ writing read, &block
+ end
+
+
+ private
+ def writing(contents)
+ tmp_file = "#{content_path.basename}.#{Process.pid}"
+ tmp_path = Pathname.new File.join(Dir.tmpdir, tmp_file)
+ tmp_path.binwrite contents
+
+ yield tmp_path
+
+ updated_contents = tmp_path.binread
+
+ write(updated_contents) if updated_contents != contents
+ ensure
+ FileUtils.rm(tmp_path) if tmp_path.exist?
+ end
+
+
+ def encrypt(contents)
+ encryptor.encrypt_and_sign contents
+ end
+
+ def decrypt(contents)
+ encryptor.decrypt_and_verify contents
+ end
+
+ def encryptor
+ @encryptor ||= ActiveSupport::MessageEncryptor.new([ key ].pack("H*"), cipher: CIPHER)
+ end
+
+
+ def read_env_key
+ ENV[env_key]
+ end
+
+ def read_key_file
+ key_path.binread.strip if key_path.exist?
+ end
+
+ def handle_missing_key
+ raise MissingKeyError, key_path: key_path, env_key: env_key if raise_if_missing_key
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/evented_file_update_checker.rb b/activesupport/lib/active_support/evented_file_update_checker.rb
index 21fdf7bb80..97e982eb05 100644
--- a/activesupport/lib/active_support/evented_file_update_checker.rb
+++ b/activesupport/lib/active_support/evented_file_update_checker.rb
@@ -1,10 +1,43 @@
-require 'set'
-require 'pathname'
-require 'concurrent/atomic/atomic_boolean'
+# frozen_string_literal: true
+
+require "set"
+require "pathname"
+require "concurrent/atomic/atomic_boolean"
module ActiveSupport
+ # Allows you to "listen" to changes in a file system.
+ # The evented file updater does not hit disk when checking for updates
+ # instead it uses platform specific file system events to trigger a change
+ # in state.
+ #
+ # The file checker takes an array of files to watch or a hash specifying directories
+ # and file extensions to watch. It also takes a block that is called when
+ # EventedFileUpdateChecker#execute is run or when EventedFileUpdateChecker#execute_if_updated
+ # is run and there have been changes to the file system.
+ #
+ # Note: Forking will cause the first call to `updated?` to return `true`.
+ #
+ # Example:
+ #
+ # checker = ActiveSupport::EventedFileUpdateChecker.new(["/tmp/foo"]) { puts "changed" }
+ # checker.updated?
+ # # => false
+ # checker.execute_if_updated
+ # # => nil
+ #
+ # FileUtils.touch("/tmp/foo")
+ #
+ # checker.updated?
+ # # => true
+ # checker.execute_if_updated
+ # # => "changed"
+ #
class EventedFileUpdateChecker #:nodoc: all
def initialize(files, dirs = {}, &block)
+ unless block
+ raise ArgumentError, "A block is required to initialize an EventedFileUpdateChecker"
+ end
+
@ph = PathHelper.new
@files = files.map { |f| @ph.xpath(f) }.to_set
@@ -13,26 +46,35 @@ module ActiveSupport
@dirs[@ph.xpath(dir)] = Array(exts).map { |ext| @ph.normalize_extension(ext) }
end
- @block = block
- @updated = Concurrent::AtomicBoolean.new(false)
- @lcsp = @ph.longest_common_subpath(@dirs.keys)
+ @block = block
+ @updated = Concurrent::AtomicBoolean.new(false)
+ @lcsp = @ph.longest_common_subpath(@dirs.keys)
+ @pid = Process.pid
+ @boot_mutex = Mutex.new
- if (dtw = directories_to_watch).any?
+ if (@dtw = directories_to_watch).any?
# Loading listen triggers warnings. These are originated by a legit
# usage of attr_* macros for private attributes, but adds a lot of noise
# to our test suite. Thus, we lazy load it and disable warnings locally.
silence_warnings do
begin
- require 'listen'
+ require "listen"
rescue LoadError => e
raise LoadError, "Could not load the 'listen' gem. Add `gem 'listen'` to the development group of your Gemfile", e.backtrace
end
end
- Listen.to(*dtw, &method(:changed)).start
end
+ boot!
end
def updated?
+ @boot_mutex.synchronize do
+ if @pid != Process.pid
+ boot!
+ @pid = Process.pid
+ @updated.make_true
+ end
+ end
@updated.true?
end
@@ -50,6 +92,9 @@ module ActiveSupport
end
private
+ def boot!
+ Listen.to(*@dtw, &method(:changed)).start
+ end
def changed(modified, added, removed)
unless updated?
@@ -82,74 +127,79 @@ module ActiveSupport
dtw.compact!
dtw.uniq!
+ normalized_gem_paths = Gem.path.map { |path| File.join path, "" }
+ dtw = dtw.reject do |path|
+ normalized_gem_paths.any? { |gem_path| path.to_s.start_with?(gem_path) }
+ end
+
@ph.filter_out_descendants(dtw)
end
- class PathHelper
- def xpath(path)
- Pathname.new(path).expand_path
- end
+ class PathHelper
+ def xpath(path)
+ Pathname.new(path).expand_path
+ end
- def normalize_extension(ext)
- ext.to_s.sub(/\A\./, '')
- end
+ def normalize_extension(ext)
+ ext.to_s.sub(/\A\./, "")
+ end
- # Given a collection of Pathname objects returns the longest subpath
- # common to all of them, or +nil+ if there is none.
- def longest_common_subpath(paths)
- return if paths.empty?
-
- lcsp = Pathname.new(paths[0])
-
- paths[1..-1].each do |path|
- until ascendant_of?(lcsp, path)
- if lcsp.root?
- # If we get here a root directory is not an ascendant of path.
- # This may happen if there are paths in different drives on
- # Windows.
- return
- else
- lcsp = lcsp.parent
+ # Given a collection of Pathname objects returns the longest subpath
+ # common to all of them, or +nil+ if there is none.
+ def longest_common_subpath(paths)
+ return if paths.empty?
+
+ lcsp = Pathname.new(paths[0])
+
+ paths[1..-1].each do |path|
+ until ascendant_of?(lcsp, path)
+ if lcsp.root?
+ # If we get here a root directory is not an ascendant of path.
+ # This may happen if there are paths in different drives on
+ # Windows.
+ return
+ else
+ lcsp = lcsp.parent
+ end
end
end
- end
- lcsp
- end
+ lcsp
+ end
- # Returns the deepest existing ascendant, which could be the argument itself.
- def existing_parent(dir)
- dir.ascend do |ascendant|
- break ascendant if ascendant.directory?
+ # Returns the deepest existing ascendant, which could be the argument itself.
+ def existing_parent(dir)
+ dir.ascend do |ascendant|
+ break ascendant if ascendant.directory?
+ end
end
- end
- # Filters out directories which are descendants of others in the collection (stable).
- def filter_out_descendants(dirs)
- return dirs if dirs.length < 2
+ # Filters out directories which are descendants of others in the collection (stable).
+ def filter_out_descendants(dirs)
+ return dirs if dirs.length < 2
- dirs_sorted_by_nparts = dirs.sort_by { |dir| dir.each_filename.to_a.length }
- descendants = []
+ dirs_sorted_by_nparts = dirs.sort_by { |dir| dir.each_filename.to_a.length }
+ descendants = []
- until dirs_sorted_by_nparts.empty?
- dir = dirs_sorted_by_nparts.shift
+ until dirs_sorted_by_nparts.empty?
+ dir = dirs_sorted_by_nparts.shift
- dirs_sorted_by_nparts.reject! do |possible_descendant|
- ascendant_of?(dir, possible_descendant) && descendants << possible_descendant
+ dirs_sorted_by_nparts.reject! do |possible_descendant|
+ ascendant_of?(dir, possible_descendant) && descendants << possible_descendant
+ end
end
- end
- # Array#- preserves order.
- dirs - descendants
- end
+ # Array#- preserves order.
+ dirs - descendants
+ end
- private
+ private
- def ascendant_of?(base, other)
- base != other && other.ascend do |ascendant|
- break true if base == ascendant
+ def ascendant_of?(base, other)
+ base != other && other.ascend do |ascendant|
+ break true if base == ascendant
+ end
end
- end
- end
+ end
end
end
diff --git a/activesupport/lib/active_support/execution_wrapper.rb b/activesupport/lib/active_support/execution_wrapper.rb
index 00c5745a25..f48c586cad 100644
--- a/activesupport/lib/active_support/execution_wrapper.rb
+++ b/activesupport/lib/active_support/execution_wrapper.rb
@@ -1,4 +1,6 @@
-require 'active_support/callbacks'
+# frozen_string_literal: true
+
+require "active_support/callbacks"
module ActiveSupport
class ExecutionWrapper
@@ -19,6 +21,23 @@ module ActiveSupport
set_callback(:complete, *args, &block)
end
+ RunHook = Struct.new(:hook) do # :nodoc:
+ def before(target)
+ hook_state = target.send(:hook_state)
+ hook_state[hook] = hook.run
+ end
+ end
+
+ CompleteHook = Struct.new(:hook) do # :nodoc:
+ def before(target)
+ hook_state = target.send(:hook_state)
+ if hook_state.key?(hook)
+ hook.complete hook_state[hook]
+ end
+ end
+ alias after before
+ end
+
# Register an object to be invoked during both the +run+ and
# +complete+ steps.
#
@@ -29,19 +48,11 @@ module ActiveSupport
# invoked in that situation.)
def self.register_hook(hook, outer: false)
if outer
- run_args = [prepend: true]
- complete_args = [:after]
+ to_run RunHook.new(hook), prepend: true
+ to_complete :after, CompleteHook.new(hook)
else
- run_args = complete_args = []
- end
-
- to_run(*run_args) do
- hook_state[hook] = hook.run
- end
- to_complete(*complete_args) do
- if hook_state.key?(hook)
- hook.complete hook_state[hook]
- end
+ to_run RunHook.new(hook)
+ to_complete CompleteHook.new(hook)
end
end
diff --git a/activesupport/lib/active_support/executor.rb b/activesupport/lib/active_support/executor.rb
index 602fb11a44..ce391b07ec 100644
--- a/activesupport/lib/active_support/executor.rb
+++ b/activesupport/lib/active_support/executor.rb
@@ -1,4 +1,6 @@
-require 'active_support/execution_wrapper'
+# frozen_string_literal: true
+
+require "active_support/execution_wrapper"
module ActiveSupport
class Executor < ExecutionWrapper
diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb
index b5667b6ac8..1a0bb10815 100644
--- a/activesupport/lib/active_support/file_update_checker.rb
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/time/calculations'
+# frozen_string_literal: true
+
+require "active_support/core_ext/time/calculations"
module ActiveSupport
# FileUpdateChecker specifies the API used by Rails to watch files
@@ -38,6 +40,10 @@ module ActiveSupport
# changes. The array of files and list of directories cannot be changed
# after FileUpdateChecker has been initialized.
def initialize(files, dirs = {}, &block)
+ unless block
+ raise ArgumentError, "A block is required to initialize a FileUpdateChecker"
+ end
+
@files = files.freeze
@glob = compile_glob(dirs)
@block = block
@@ -93,65 +99,65 @@ module ActiveSupport
private
- def watched
- @watched || begin
- all = @files.select { |f| File.exist?(f) }
- all.concat(Dir[@glob]) if @glob
- all
+ def watched
+ @watched || begin
+ all = @files.select { |f| File.exist?(f) }
+ all.concat(Dir[@glob]) if @glob
+ all
+ end
end
- end
- def updated_at(paths)
- @updated_at || max_mtime(paths) || Time.at(0)
- end
+ def updated_at(paths)
+ @updated_at || max_mtime(paths) || Time.at(0)
+ end
- # This method returns the maximum mtime of the files in +paths+, or +nil+
- # if the array is empty.
- #
- # Files with a mtime in the future are ignored. Such abnormal situation
- # can happen for example if the user changes the clock by hand. It is
- # healthy to consider this edge case because with mtimes in the future
- # reloading is not triggered.
- def max_mtime(paths)
- time_now = Time.now
- max_mtime = nil
-
- # Time comparisons are performed with #compare_without_coercion because
- # AS redefines these operators in a way that is much slower and does not
- # bring any benefit in this particular code.
+ # This method returns the maximum mtime of the files in +paths+, or +nil+
+ # if the array is empty.
#
- # Read t1.compare_without_coercion(t2) < 0 as t1 < t2.
- paths.each do |path|
- mtime = File.mtime(path)
-
- next if time_now.compare_without_coercion(mtime) < 0
-
- if max_mtime.nil? || max_mtime.compare_without_coercion(mtime) < 0
- max_mtime = mtime
+ # Files with a mtime in the future are ignored. Such abnormal situation
+ # can happen for example if the user changes the clock by hand. It is
+ # healthy to consider this edge case because with mtimes in the future
+ # reloading is not triggered.
+ def max_mtime(paths)
+ time_now = Time.now
+ max_mtime = nil
+
+ # Time comparisons are performed with #compare_without_coercion because
+ # AS redefines these operators in a way that is much slower and does not
+ # bring any benefit in this particular code.
+ #
+ # Read t1.compare_without_coercion(t2) < 0 as t1 < t2.
+ paths.each do |path|
+ mtime = File.mtime(path)
+
+ next if time_now.compare_without_coercion(mtime) < 0
+
+ if max_mtime.nil? || max_mtime.compare_without_coercion(mtime) < 0
+ max_mtime = mtime
+ end
end
- end
- max_mtime
- end
+ max_mtime
+ end
- def compile_glob(hash)
- hash.freeze # Freeze so changes aren't accidentally pushed
- return if hash.empty?
+ def compile_glob(hash)
+ hash.freeze # Freeze so changes aren't accidentally pushed
+ return if hash.empty?
- globs = hash.map do |key, value|
- "#{escape(key)}/**/*#{compile_ext(value)}"
+ globs = hash.map do |key, value|
+ "#{escape(key)}/**/*#{compile_ext(value)}"
+ end
+ "{#{globs.join(",")}}"
end
- "{#{globs.join(",")}}"
- end
- def escape(key)
- key.gsub(',','\,')
- end
+ def escape(key)
+ key.gsub(",", '\,')
+ end
- def compile_ext(array)
- array = Array(array)
- return if array.empty?
- ".{#{array.join(",")}}"
- end
+ def compile_ext(array)
+ array = Array(array)
+ return if array.empty?
+ ".{#{array.join(",")}}"
+ end
end
end
diff --git a/activesupport/lib/active_support/gem_version.rb b/activesupport/lib/active_support/gem_version.rb
index 4048133fb4..1e09adbb52 100644
--- a/activesupport/lib/active_support/gem_version.rb
+++ b/activesupport/lib/active_support/gem_version.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# Returns the version of the currently loaded Active Support as a <tt>Gem::Version</tt>.
def self.gem_version
@@ -6,9 +8,9 @@ module ActiveSupport
module VERSION
MAJOR = 5
- MINOR = 0
+ MINOR = 2
TINY = 0
- PRE = "beta4"
+ PRE = "beta2"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb
index b837c879bb..7ffa6d90a2 100644
--- a/activesupport/lib/active_support/gzip.rb
+++ b/activesupport/lib/active_support/gzip.rb
@@ -1,5 +1,7 @@
-require 'zlib'
-require 'stringio'
+# frozen_string_literal: true
+
+require "zlib"
+require "stringio"
module ActiveSupport
# A convenient wrapper for the zlib standard library that allows
@@ -9,7 +11,7 @@ module ActiveSupport
# # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00"
#
# ActiveSupport::Gzip.decompress(gzip)
- # # => "compress me!"
+ # # => "compress me!"
module Gzip
class Stream < StringIO
def initialize(*)
@@ -21,11 +23,11 @@ module ActiveSupport
# Decompresses a gzipped string.
def self.decompress(source)
- Zlib::GzipReader.new(StringIO.new(source)).read
+ Zlib::GzipReader.wrap(StringIO.new(source), &:read)
end
# Compresses a string using gzip.
- def self.compress(source, level=Zlib::DEFAULT_COMPRESSION, strategy=Zlib::DEFAULT_STRATEGY)
+ def self.compress(source, level = Zlib::DEFAULT_COMPRESSION, strategy = Zlib::DEFAULT_STRATEGY)
output = Stream.new
gz = Zlib::GzipWriter.new(output, level, strategy)
gz.write(source)
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index 03770a197c..2e2ed8a25d 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/hash/reverse_merge'
+# frozen_string_literal: true
+
+require "active_support/core_ext/hash/keys"
+require "active_support/core_ext/hash/reverse_merge"
module ActiveSupport
# Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
@@ -40,6 +42,12 @@ module ActiveSupport
# rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
#
# which may be handy.
+ #
+ # To access this class outside of Rails, require the core extension with:
+ #
+ # require "active_support/core_ext/hash/indifferent_access"
+ #
+ # which will, in turn, require this file.
class HashWithIndifferentAccess < Hash
# Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
# this class.
@@ -68,25 +76,6 @@ module ActiveSupport
end
end
- def default(*args)
- arg_key = args.first
-
- if include?(key = convert_key(arg_key))
- self[key]
- else
- super
- end
- end
-
- def self.new_from_hash_copying_default(hash)
- ActiveSupport::Deprecation.warn(<<-MSG.squish)
- `ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default`
- has been deprecated, and will be removed in Rails 5.1. The behavior of
- this method is now identical to the behavior of `.new`.
- MSG
- new(hash)
- end
-
def self.[](*args)
new.merge!(Hash[*args])
end
@@ -161,7 +150,6 @@ module ActiveSupport
alias_method :has_key?, :key?
alias_method :member?, :key?
-
# Same as <tt>Hash#[]</tt> where the key passed as argument can be
# either a string or a symbol:
#
@@ -189,6 +177,36 @@ module ActiveSupport
super(convert_key(key), *extras)
end
+ if Hash.new.respond_to?(:dig)
+ # Same as <tt>Hash#dig</tt> where the key passed as argument can be
+ # either a string or a symbol:
+ #
+ # counters = ActiveSupport::HashWithIndifferentAccess.new
+ # counters[:foo] = { bar: 1 }
+ #
+ # counters.dig('foo', 'bar') # => 1
+ # counters.dig(:foo, :bar) # => 1
+ # counters.dig(:zoo) # => nil
+ def dig(*args)
+ args[0] = convert_key(args[0]) if args.size > 0
+ super(*args)
+ end
+ end
+
+ # Same as <tt>Hash#default</tt> where the key passed as argument can be
+ # either a string or a symbol:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new(1)
+ # hash.default # => 1
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new { |hash, key| key }
+ # hash.default # => nil
+ # hash.default('foo') # => 'foo'
+ # hash.default(:foo) # => 'foo'
+ def default(*args)
+ super(*args.map { |arg| convert_key(arg) })
+ end
+
# Returns an array of the values at the specified indices:
#
# hash = ActiveSupport::HashWithIndifferentAccess.new
@@ -199,13 +217,26 @@ module ActiveSupport
indices.collect { |key| self[convert_key(key)] }
end
+ # Returns an array of the values at the specified indices, but also
+ # raises an exception when one of the keys can't be found.
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
+ # hash[:a] = 'x'
+ # hash[:b] = 'y'
+ # hash.fetch_values('a', 'b') # => ["x", "y"]
+ # hash.fetch_values('a', 'c') { |key| 'z' } # => ["x", "z"]
+ # hash.fetch_values('a', 'c') # => KeyError: key not found: "c"
+ def fetch_values(*indices, &block)
+ indices.collect { |key| fetch(key, &block) }
+ end if Hash.method_defined?(:fetch_values)
+
# Returns a shallow copy of the hash.
#
# hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } })
# dup = hash.dup
# dup[:a][:c] = 'c'
#
- # hash[:a][:c] # => nil
+ # hash[:a][:c] # => "c"
# dup[:a][:c] # => "c"
def dup
self.class.new(self).tap do |new_hash|
@@ -217,7 +248,7 @@ module ActiveSupport
# modify the receiver but rather returns a new hash with indifferent
# access with the result of the merge.
def merge(hash, &block)
- self.dup.update(hash, &block)
+ dup.update(hash, &block)
end
# Like +merge+ but the other way around: Merges the receiver into the
@@ -229,11 +260,13 @@ module ActiveSupport
def reverse_merge(other_hash)
super(self.class.new(other_hash))
end
+ alias_method :with_defaults, :reverse_merge
# Same semantics as +reverse_merge+ but modifies the receiver in-place.
def reverse_merge!(other_hash)
- replace(reverse_merge( other_hash ))
+ super(self.class.new(other_hash))
end
+ alias_method :with_defaults!, :reverse_merge!
# Replaces the contents of this hash with other_hash.
#
@@ -268,6 +301,30 @@ module ActiveSupport
dup.tap { |hash| hash.reject!(*args, &block) }
end
+ def transform_values(*args, &block)
+ return to_enum(:transform_values) unless block_given?
+ dup.tap { |hash| hash.transform_values!(*args, &block) }
+ end
+
+ def transform_keys(*args, &block)
+ return to_enum(:transform_keys) unless block_given?
+ dup.tap { |hash| hash.transform_keys!(*args, &block) }
+ end
+
+ def slice(*keys)
+ keys.map! { |key| convert_key(key) }
+ self.class.new(super)
+ end
+
+ def slice!(*keys)
+ keys.map! { |key| convert_key(key) }
+ super
+ end
+
+ def compact
+ dup.tap(&:compact!)
+ end
+
# Convert to a regular hash with string keys.
def to_hash
_new_hash = Hash.new
@@ -279,12 +336,12 @@ module ActiveSupport
_new_hash
end
- protected
- def convert_key(key)
+ private
+ def convert_key(key) # :doc:
key.kind_of?(Symbol) ? key.to_s : key
end
- def convert_value(value, options = {})
+ def convert_value(value, options = {}) # :doc:
if value.is_a? Hash
if options[:for] == :to_hash
value.to_hash
@@ -301,7 +358,7 @@ module ActiveSupport
end
end
- def set_defaults(target)
+ def set_defaults(target) # :doc:
if default_proc
target.default_proc = default_proc.dup
else
@@ -311,4 +368,6 @@ module ActiveSupport
end
end
+# :stopdoc:
+
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
diff --git a/activesupport/lib/active_support/i18n.rb b/activesupport/lib/active_support/i18n.rb
index 6cc98191d4..d60b3eff30 100644
--- a/activesupport/lib/active_support/i18n.rb
+++ b/activesupport/lib/active_support/i18n.rb
@@ -1,13 +1,15 @@
-require 'active_support/core_ext/hash/deep_merge'
-require 'active_support/core_ext/hash/except'
-require 'active_support/core_ext/hash/slice'
+# frozen_string_literal: true
+
+require "active_support/core_ext/hash/deep_merge"
+require "active_support/core_ext/hash/except"
+require "active_support/core_ext/hash/slice"
begin
- require 'i18n'
+ require "i18n"
rescue LoadError => e
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
raise e
end
-require 'active_support/lazy_load_hooks'
+require "active_support/lazy_load_hooks"
ActiveSupport.run_load_hooks(:i18n)
-I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
+I18n.load_path << File.expand_path("locale/en.yml", __dir__)
diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb
index 6cc7c90c12..ce8bfbfd8c 100644
--- a/activesupport/lib/active_support/i18n_railtie.rb
+++ b/activesupport/lib/active_support/i18n_railtie.rb
@@ -1,7 +1,11 @@
+# frozen_string_literal: true
+
require "active_support"
require "active_support/file_update_checker"
require "active_support/core_ext/array/wrap"
+# :enddoc:
+
module I18n
class Railtie < Rails::Railtie
config.i18n = ActiveSupport::OrderedOptions.new
@@ -21,8 +25,6 @@ module I18n
I18n::Railtie.initialize_i18n(app)
end
- protected
-
@i18n_inited = false
# Setup i18n configuration.
@@ -42,7 +44,7 @@ module I18n
case setting
when :railties_load_path
reloadable_paths = value
- app.config.i18n.load_path.unshift(*value.map(&:existent).flatten)
+ app.config.i18n.load_path.unshift(*value.flat_map(&:existent))
when :load_path
I18n.load_path += value
else
@@ -58,7 +60,7 @@ module I18n
directories = watched_dirs_with_extensions(reloadable_paths)
reloader = app.config.file_watcher.new(I18n.load_path.dup, directories) do
I18n.load_path.keep_if { |p| File.exist?(p) }
- I18n.load_path |= reloadable_paths.map(&:existent).flatten
+ I18n.load_path |= reloadable_paths.flat_map(&:existent)
I18n.reload!
end
@@ -66,10 +68,6 @@ module I18n
app.reloaders << reloader
app.reloader.to_run do
reloader.execute_if_updated { require_unload_lock! }
- # TODO: remove the following line as soon as the return value of
- # callbacks is ignored, that is, returning `false` does not
- # display a deprecation warning or halts the callback chain.
- true
end
reloader.execute
@@ -83,14 +81,15 @@ module I18n
def self.init_fallbacks(fallbacks)
include_fallbacks_module
- args = case fallbacks
- when ActiveSupport::OrderedOptions
- [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
- when Hash, Array
- Array.wrap(fallbacks)
- else # TrueClass
- []
- end
+ args = \
+ case fallbacks
+ when ActiveSupport::OrderedOptions
+ [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
+ when Hash, Array
+ Array.wrap(fallbacks)
+ else # TrueClass
+ []
+ end
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index 2ca1124e76..baf1cb3038 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -1,4 +1,6 @@
-require 'active_support/inflector/inflections'
+# frozen_string_literal: true
+
+require "active_support/inflector/inflections"
#--
# Defines the standard inflection rules. These are the starting point for
@@ -8,8 +10,8 @@ require 'active_support/inflector/inflections'
#++
module ActiveSupport
Inflector.inflections(:en) do |inflect|
- inflect.plural(/$/, 's')
- inflect.plural(/s$/i, 's')
+ inflect.plural(/$/, "s")
+ inflect.plural(/s$/i, "s")
inflect.plural(/^(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
inflect.plural(/(octop|vir)i$/i, '\1i')
@@ -18,7 +20,7 @@ module ActiveSupport
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
inflect.plural(/([ti])a$/i, '\1a')
- inflect.plural(/sis$/i, 'ses')
+ inflect.plural(/sis$/i, "ses")
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
@@ -30,7 +32,7 @@ module ActiveSupport
inflect.plural(/^(oxen)$/i, '\1')
inflect.plural(/(quiz)$/i, '\1zes')
- inflect.singular(/s$/i, '')
+ inflect.singular(/s$/i, "")
inflect.singular(/(ss)$/i, '\1')
inflect.singular(/(n)ews$/i, '\1ews')
inflect.singular(/([ti])a$/i, '\1um')
@@ -58,12 +60,12 @@ module ActiveSupport
inflect.singular(/(quiz)zes$/i, '\1')
inflect.singular(/(database)s$/i, '\1')
- inflect.irregular('person', 'people')
- inflect.irregular('man', 'men')
- inflect.irregular('child', 'children')
- inflect.irregular('sex', 'sexes')
- inflect.irregular('move', 'moves')
- inflect.irregular('zombie', 'zombies')
+ inflect.irregular("person", "people")
+ inflect.irregular("man", "men")
+ inflect.irregular("child", "children")
+ inflect.irregular("sex", "sexes")
+ inflect.irregular("move", "moves")
+ inflect.irregular("zombie", "zombies")
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
end
diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb
index 215a60eba7..d77f04c9c5 100644
--- a/activesupport/lib/active_support/inflector.rb
+++ b/activesupport/lib/active_support/inflector.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
# in case active_support/inflector is required without the rest of active_support
-require 'active_support/inflector/inflections'
-require 'active_support/inflector/transliterate'
-require 'active_support/inflector/methods'
+require "active_support/inflector/inflections"
+require "active_support/inflector/transliterate"
+require "active_support/inflector/methods"
-require 'active_support/inflections'
-require 'active_support/core_ext/string/inflections'
+require "active_support/inflections"
+require "active_support/core_ext/string/inflections"
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index f3e52b48ac..0450a4be4c 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -1,6 +1,10 @@
-require 'concurrent/map'
-require 'active_support/core_ext/array/prepend_and_append'
-require 'active_support/i18n'
+# frozen_string_literal: true
+
+require "concurrent/map"
+require "active_support/core_ext/array/prepend_and_append"
+require "active_support/core_ext/regexp"
+require "active_support/i18n"
+require "active_support/deprecation"
module ActiveSupport
module Inflector
@@ -43,13 +47,14 @@ module ActiveSupport
end
def add(words)
- self.concat(words.flatten.map(&:downcase))
- @regex_array += self.map {|word| to_regex(word) }
+ words = words.flatten.map(&:downcase)
+ concat(words)
+ @regex_array += words.map { |word| to_regex(word) }
self
end
def uncountable?(str)
- @regex_array.any? { |regex| regex === str }
+ @regex_array.any? { |regex| regex.match? str }
end
private
@@ -63,16 +68,21 @@ module ActiveSupport
end
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
+ deprecate :acronym_regex
+
+ attr_reader :acronyms_camelize_regex, :acronyms_underscore_regex # :nodoc:
def initialize
- @plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], Uncountables.new, [], {}, /(?=a)b/
+ @plurals, @singulars, @uncountables, @humans, @acronyms = [], [], Uncountables.new, [], {}
+ define_acronym_regex_patterns
end
# Private, for the test suite.
def initialize_dup(orig) # :nodoc:
- %w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
+ %w(plurals singulars uncountables humans acronyms).each do |scope|
instance_variable_set("@#{scope}", orig.send(scope).dup)
end
+ define_acronym_regex_patterns
end
# Specifies a new acronym. An acronym must be specified as it will appear
@@ -126,7 +136,7 @@ module ActiveSupport
# camelize 'mcdonald' # => 'McDonald'
def acronym(word)
@acronyms[word.downcase] = word
- @acronym_regex = /#{@acronyms.values.join("|")}/
+ define_acronym_regex_patterns
end
# Specifies a new pluralization rule and its replacement. The rule can
@@ -215,12 +225,20 @@ module ActiveSupport
# clear :plurals
def clear(scope = :all)
case scope
- when :all
- @plurals, @singulars, @uncountables, @humans = [], [], Uncountables.new, []
+ when :all
+ @plurals, @singulars, @uncountables, @humans = [], [], Uncountables.new, []
else
- instance_variable_set "@#{scope}", []
+ instance_variable_set "@#{scope}", []
end
end
+
+ private
+
+ def define_acronym_regex_patterns
+ @acronym_regex = @acronyms.empty? ? /(?=a)b/ : /#{@acronyms.values.join("|")}/
+ @acronyms_camelize_regex = /^(?:#{@acronym_regex}(?=\b|[A-Z_])|\w)/
+ @acronyms_underscore_regex = /(?:(?<=([A-Za-z\d]))|\b)(#{@acronym_regex})(?=\b|[^a-z])/
+ end
end
# Yields a singleton instance of Inflector::Inflections so you can specify
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index f94e12e14f..60eeaa77cb 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -1,4 +1,7 @@
-require 'active_support/inflections'
+# frozen_string_literal: true
+
+require "active_support/inflections"
+require "active_support/core_ext/regexp"
module ActiveSupport
# The Inflector transforms words from singular to plural, class names to table
@@ -27,7 +30,7 @@ module ActiveSupport
# pluralize('CamelOctopus') # => "CamelOctopi"
# pluralize('ley', :es) # => "leyes"
def pluralize(word, locale = :en)
- apply_inflections(word, inflections(locale).plurals)
+ apply_inflections(word, inflections(locale).plurals, locale)
end
# The reverse of #pluralize, returns the singular form of a word in a
@@ -44,7 +47,7 @@ module ActiveSupport
# singularize('CamelOctopi') # => "CamelOctopus"
# singularize('leyes', :es) # => "ley"
def singularize(word, locale = :en)
- apply_inflections(word, inflections(locale).singulars)
+ apply_inflections(word, inflections(locale).singulars, locale)
end
# Converts strings to UpperCamelCase.
@@ -68,10 +71,10 @@ module ActiveSupport
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize }
else
- string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
+ string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase }
end
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
- string.gsub!('/'.freeze, '::'.freeze)
+ string.gsub!("/".freeze, "::".freeze)
string
end
@@ -87,9 +90,9 @@ module ActiveSupport
#
# camelize(underscore('SSLError')) # => "SslError"
def underscore(camel_cased_word)
- return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/
- word = camel_cased_word.to_s.gsub('::'.freeze, '/'.freeze)
- word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'.freeze }#{$2.downcase}" }
+ return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word)
+ word = camel_cased_word.to_s.gsub("::".freeze, "/".freeze)
+ word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_'.freeze }#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze)
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze)
word.tr!("-".freeze, "_".freeze)
@@ -107,33 +110,38 @@ module ActiveSupport
# * Replaces underscores with spaces, if any.
# * Downcases all words except acronyms.
# * Capitalizes the first word.
- #
# The capitalization of the first word can be turned off by setting the
# +:capitalize+ option to false (default is true).
#
- # humanize('employee_salary') # => "Employee salary"
- # humanize('author_id') # => "Author"
- # humanize('author_id', capitalize: false) # => "author"
- # humanize('_id') # => "Id"
+ # The trailing '_id' can be kept and capitalized by setting the
+ # optional parameter +keep_id_suffix+ to true (default is false).
+ #
+ # humanize('employee_salary') # => "Employee salary"
+ # humanize('author_id') # => "Author"
+ # humanize('author_id', capitalize: false) # => "author"
+ # humanize('_id') # => "Id"
+ # humanize('author_id', keep_id_suffix: true) # => "Author Id"
#
# If "SSL" was defined to be an acronym:
#
# humanize('ssl_error') # => "SSL error"
#
- def humanize(lower_case_and_underscored_word, options = {})
+ def humanize(lower_case_and_underscored_word, capitalize: true, keep_id_suffix: false)
result = lower_case_and_underscored_word.to_s.dup
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
- result.sub!(/\A_+/, ''.freeze)
- result.sub!(/_id\z/, ''.freeze)
- result.tr!('_'.freeze, ' '.freeze)
+ result.sub!(/\A_+/, "".freeze)
+ unless keep_id_suffix
+ result.sub!(/_id\z/, "".freeze)
+ end
+ result.tr!("_".freeze, " ".freeze)
result.gsub!(/([a-z\d]*)/i) do |match|
- "#{inflections.acronyms[match] || match.downcase}"
+ "#{inflections.acronyms[match.downcase] || match.downcase}"
end
- if options.fetch(:capitalize, true)
+ if capitalize
result.sub!(/\A\w/) { |match| match.upcase }
end
@@ -146,21 +154,28 @@ module ActiveSupport
# upcase_first('w') # => "W"
# upcase_first('') # => ""
def upcase_first(string)
- string.length > 0 ? string[0].upcase.concat(string[1..-1]) : ''
+ string.length > 0 ? string[0].upcase.concat(string[1..-1]) : ""
end
# Capitalizes all the words and replaces some characters in the string to
# create a nicer looking title. +titleize+ is meant for creating pretty
# output. It is not used in the Rails internals.
#
+ # The trailing '_id','Id'.. can be kept and capitalized by setting the
+ # optional parameter +keep_id_suffix+ to true.
+ # By default, this parameter is false.
+ #
# +titleize+ is also aliased as +titlecase+.
#
- # titleize('man from the boondocks') # => "Man From The Boondocks"
- # titleize('x-men: the last stand') # => "X Men: The Last Stand"
- # titleize('TheManWithoutAPast') # => "The Man Without A Past"
- # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark"
- def titleize(word)
- humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { |match| match.capitalize }
+ # titleize('man from the boondocks') # => "Man From The Boondocks"
+ # titleize('x-men: the last stand') # => "X Men: The Last Stand"
+ # titleize('TheManWithoutAPast') # => "The Man Without A Past"
+ # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark"
+ # titleize('string_ending_with_id', keep_id_suffix: true) # => "String Ending With Id"
+ def titleize(word, keep_id_suffix: false)
+ humanize(underscore(word), keep_id_suffix: keep_id_suffix).gsub(/\b(?<!\w['’`])[a-z]/) do |match|
+ match.capitalize
+ end
end
# Creates the name of a table like Rails does for models to table names.
@@ -185,28 +200,28 @@ module ActiveSupport
# classify('calculus') # => "Calculus"
def classify(table_name)
# strip out any leading schema name
- camelize(singularize(table_name.to_s.sub(/.*\./, ''.freeze)))
+ camelize(singularize(table_name.to_s.sub(/.*\./, "".freeze)))
end
# Replaces underscores with dashes in the string.
#
# dasherize('puni_puni') # => "puni-puni"
def dasherize(underscored_word)
- underscored_word.tr('_'.freeze, '-'.freeze)
+ underscored_word.tr("_".freeze, "-".freeze)
end
# Removes the module part from the expression in the string.
#
- # demodulize('ActiveRecord::CoreExtensions::String::Inflections') # => "Inflections"
- # demodulize('Inflections') # => "Inflections"
- # demodulize('::Inflections') # => "Inflections"
- # demodulize('') # => ""
+ # demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections"
+ # demodulize('Inflections') # => "Inflections"
+ # demodulize('::Inflections') # => "Inflections"
+ # demodulize('') # => ""
#
# See also #deconstantize.
def demodulize(path)
path = path.to_s
- if i = path.rindex('::')
- path[(i+2)..-1]
+ if i = path.rindex("::")
+ path[(i + 2)..-1]
else
path
end
@@ -222,7 +237,7 @@ module ActiveSupport
#
# See also #demodulize.
def deconstantize(path)
- path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
+ path.to_s[0, path.rindex("::") || 0] # implementation based on the one in facets' Module#spacename
end
# Creates a foreign key name from a class name.
@@ -238,8 +253,8 @@ module ActiveSupport
# Tries to find a constant with the name specified in the argument string.
#
- # 'Module'.constantize # => Module
- # 'Foo::Bar'.constantize # => Foo::Bar
+ # constantize('Module') # => Module
+ # constantize('Foo::Bar') # => Foo::Bar
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
@@ -248,14 +263,14 @@ module ActiveSupport
# C = 'outside'
# module M
# C = 'inside'
- # C # => 'inside'
- # 'C'.constantize # => 'outside', same as ::C
+ # C # => 'inside'
+ # constantize('C') # => 'outside', same as ::C
# end
#
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
def constantize(camel_cased_word)
- names = camel_cased_word.split('::'.freeze)
+ names = camel_cased_word.split("::".freeze)
# Trigger a built-in NameError exception including the ill-formed constant in the message.
Object.const_get(camel_cased_word) if names.empty?
@@ -273,7 +288,7 @@ module ActiveSupport
# Go down the ancestors to check if it is owned directly. The check
# stops when we reach Object or the end of ancestors tree.
- constant = constant.ancestors.inject do |const, ancestor|
+ constant = constant.ancestors.inject(constant) do |const, ancestor|
break const if ancestor == Object
break ancestor if ancestor.const_defined?(name, false)
const
@@ -313,7 +328,7 @@ module ActiveSupport
raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) ||
e.name.to_s == camel_cased_word.to_s)
rescue ArgumentError => e
- raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
+ raise unless /not missing constant #{const_regexp(camel_cased_word)}!$/.match?(e.message)
end
# Returns the suffix that should be added to a number to denote the position
@@ -332,9 +347,9 @@ module ActiveSupport
"th"
else
case abs_number % 10
- when 1; "st"
- when 2; "nd"
- when 3; "rd"
+ when 1; "st"
+ when 2; "nd"
+ when 3; "rd"
else "th"
end
end
@@ -355,36 +370,39 @@ module ActiveSupport
private
- # Mounts a regular expression, returned as a string to ease interpolation,
- # that will match part by part the given constant.
- #
- # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?"
- # const_regexp("::") # => "::"
- def const_regexp(camel_cased_word) #:nodoc:
- parts = camel_cased_word.split("::".freeze)
+ # Mounts a regular expression, returned as a string to ease interpolation,
+ # that will match part by part the given constant.
+ #
+ # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?"
+ # const_regexp("::") # => "::"
+ def const_regexp(camel_cased_word)
+ parts = camel_cased_word.split("::".freeze)
- return Regexp.escape(camel_cased_word) if parts.blank?
+ return Regexp.escape(camel_cased_word) if parts.blank?
- last = parts.pop
+ last = parts.pop
- parts.reverse.inject(last) do |acc, part|
- part.empty? ? acc : "#{part}(::#{acc})?"
+ parts.reverse.inject(last) do |acc, part|
+ part.empty? ? acc : "#{part}(::#{acc})?"
+ end
end
- end
-
- # Applies inflection rules for +singularize+ and +pluralize+.
- #
- # apply_inflections('post', inflections.plurals) # => "posts"
- # apply_inflections('posts', inflections.singulars) # => "post"
- def apply_inflections(word, rules)
- result = word.to_s.dup
- if word.empty? || inflections.uncountables.uncountable?(result)
- result
- else
- rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
- result
+ # Applies inflection rules for +singularize+ and +pluralize+.
+ #
+ # If passed an optional +locale+ parameter, the uncountables will be
+ # found for that locale.
+ #
+ # apply_inflections('post', inflections.plurals, :en) # => "posts"
+ # apply_inflections('posts', inflections.singulars, :en) # => "post"
+ def apply_inflections(word, rules, locale = :en)
+ result = word.to_s.dup
+
+ if word.empty? || inflections(locale).uncountables.uncountable?(result)
+ result
+ else
+ rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
+ result
+ end
end
- end
end
end
diff --git a/activesupport/lib/active_support/inflector/transliterate.rb b/activesupport/lib/active_support/inflector/transliterate.rb
index 871cfb8a72..6f2ca4999c 100644
--- a/activesupport/lib/active_support/inflector/transliterate.rb
+++ b/activesupport/lib/active_support/inflector/transliterate.rb
@@ -1,9 +1,10 @@
-require 'active_support/core_ext/string/multibyte'
-require 'active_support/i18n'
+# frozen_string_literal: true
+
+require "active_support/core_ext/string/multibyte"
+require "active_support/i18n"
module ActiveSupport
module Inflector
-
# Replaces non-ASCII characters with an ASCII approximation, or if none
# exists, a replacement character which defaults to "?".
#
@@ -58,32 +59,37 @@ module ActiveSupport
# transliterate('Jürgen')
# # => "Juergen"
def transliterate(string, replacement = "?".freeze)
- I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
- ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
- :replacement => replacement)
+ raise ArgumentError, "Can only transliterate strings. Received #{string.class.name}" unless string.is_a?(String)
+
+ I18n.transliterate(
+ ActiveSupport::Multibyte::Unicode.normalize(
+ ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
+ replacement: replacement)
end
# Replaces special characters in a string so that it may be used as part of
# a 'pretty' URL.
#
# parameterize("Donald E. Knuth") # => "donald-e-knuth"
- # parameterize("^trés|Jolie-- ") # => "tres-jolie"
+ # parameterize("^très|Jolie-- ") # => "tres-jolie"
#
- # To use a custom separator, override the `separator` argument.
+ # To use a custom separator, override the +separator+ argument.
#
# parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth"
- # parameterize("^trés|Jolie-- ", separator: '_') # => "tres_jolie"
+ # parameterize("^très|Jolie__ ", separator: '_') # => "tres_jolie"
#
- # To preserve the case of the characters in a string, use the `preserve_case` argument.
+ # To preserve the case of the characters in a string, use the +preserve_case+ argument.
#
# parameterize("Donald E. Knuth", preserve_case: true) # => "Donald-E-Knuth"
- # parameterize("^trés|Jolie-- ", preserve_case: true) # => "tres-Jolie"
+ # parameterize("^très|Jolie-- ", preserve_case: true) # => "tres-Jolie"
#
- def parameterize(string, sep = :unused, separator: '-', preserve_case: false)
- unless sep == :unused
- ActiveSupport::Deprecation.warn("Passing the separator argument as a positional parameter is deprecated and will soon be removed. Use `separator: '#{sep}'` instead.")
- separator = sep
- end
+ # It preserves dashes and underscores unless they are used as separators:
+ #
+ # parameterize("^très|Jolie__ ") # => "tres-jolie__"
+ # parameterize("^très|Jolie-- ", separator: "_") # => "tres_jolie--"
+ # parameterize("^très_Jolie-- ", separator: ".") # => "tres_jolie--"
+ #
+ def parameterize(string, separator: "-", preserve_case: false)
# Replace accented chars with their ASCII equivalents.
parameterized_string = transliterate(string)
@@ -102,9 +108,9 @@ module ActiveSupport
# No more than one of the separator in a row.
parameterized_string.gsub!(re_duplicate_separator, separator)
# Remove leading/trailing separator.
- parameterized_string.gsub!(re_leading_trailing_separator, ''.freeze)
+ parameterized_string.gsub!(re_leading_trailing_separator, "".freeze)
end
-
+
parameterized_string.downcase! unless preserve_case
parameterized_string
end
diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb
index 3e1d9b1d33..d7887175c0 100644
--- a/activesupport/lib/active_support/json.rb
+++ b/activesupport/lib/active_support/json.rb
@@ -1,2 +1,4 @@
-require 'active_support/json/decoding'
-require 'active_support/json/encoding'
+# frozen_string_literal: true
+
+require "active_support/json/decoding"
+require "active_support/json/encoding"
diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb
index 2932954f03..8c0e016dc5 100644
--- a/activesupport/lib/active_support/json/decoding.rb
+++ b/activesupport/lib/active_support/json/decoding.rb
@@ -1,6 +1,8 @@
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/module/delegation'
-require 'json'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/attribute_accessors"
+require "active_support/core_ext/module/delegation"
+require "json"
module ActiveSupport
# Look for and parse json strings that look like ISO 8601 times.
@@ -8,7 +10,8 @@ module ActiveSupport
module JSON
# matches YAML-formatted dates
- DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
+ DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/
+ DATETIME_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?)$/
class << self
# Parses a JSON string (JavaScript Object Notation) into a hash.
@@ -48,7 +51,13 @@ module ActiveSupport
nil
when DATE_REGEX
begin
- DateTime.parse(data)
+ Date.parse(data)
+ rescue ArgumentError
+ data
+ end
+ when DATETIME_REGEX
+ begin
+ Time.zone.parse(data)
rescue ArgumentError
data
end
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 031c5e9339..1339c75ffe 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -1,5 +1,7 @@
-require 'active_support/core_ext/object/json'
-require 'active_support/core_ext/module/delegation'
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/json"
+require "active_support/core_ext/module/delegation"
module ActiveSupport
class << self
@@ -7,7 +9,7 @@ module ActiveSupport
:time_precision, :time_precision=,
:escape_html_entities_in_json, :escape_html_entities_in_json=,
:json_encoder, :json_encoder=,
- :to => :'ActiveSupport::JSON::Encoding'
+ to: :'ActiveSupport::JSON::Encoding'
end
module JSON
@@ -40,9 +42,9 @@ module ActiveSupport
ESCAPED_CHARS = {
"\u2028" => '\u2028',
"\u2029" => '\u2029',
- '>' => '\u003e',
- '<' => '\u003c',
- '&' => '\u0026',
+ ">" => '\u003e',
+ "<" => '\u003c',
+ "&" => '\u0026',
}
ESCAPE_REGEX_WITH_HTML_ENTITIES = /[\u2028\u2029><&]/u
@@ -68,7 +70,8 @@ module ActiveSupport
:ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, :EscapedString
# Convert an object into a "JSON-ready" representation composed of
- # primitives like Hash, Array, String, Numeric, and true/false/nil.
+ # primitives like Hash, Array, String, Numeric,
+ # and +true+/+false+/+nil+.
# Recursively calls #as_json to the object to recursively build a
# fully JSON-ready object.
#
@@ -84,7 +87,7 @@ module ActiveSupport
when String
EscapedString.new(value)
when Numeric, NilClass, TrueClass, FalseClass
- value
+ value.as_json
when Hash
Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }]
when Array
diff --git a/activesupport/lib/active_support/key_generator.rb b/activesupport/lib/active_support/key_generator.rb
index 7f73f9ddfc..78f7d7ca8d 100644
--- a/activesupport/lib/active_support/key_generator.rb
+++ b/activesupport/lib/active_support/key_generator.rb
@@ -1,5 +1,7 @@
-require 'concurrent/map'
-require 'openssl'
+# frozen_string_literal: true
+
+require "concurrent/map"
+require "openssl"
module ActiveSupport
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2.
@@ -17,7 +19,7 @@ module ActiveSupport
# Returns a derived key suitable for use. The default key_size is chosen
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
# i.e. OpenSSL::Digest::SHA1#block_length
- def generate_key(salt, key_size=64)
+ def generate_key(salt, key_size = 64)
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
end
end
@@ -31,11 +33,9 @@ module ActiveSupport
@cache_keys = Concurrent::Map.new
end
- # Returns a derived key suitable for use. The default key_size is chosen
- # to be compatible with the default settings of ActiveSupport::MessageVerifier.
- # i.e. OpenSSL::Digest::SHA1#block_length
- def generate_key(salt, key_size=64)
- @cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
+ # Returns a derived key suitable for use.
+ def generate_key(*args)
+ @cache_keys[args.join] ||= @key_generator.generate_key(*args)
end
end
@@ -53,21 +53,21 @@ module ActiveSupport
private
- # To prevent users from using something insecure like "Password" we make sure that the
- # secret they've provided is at least 30 characters in length.
- def ensure_secret_secure(secret)
- if secret.blank?
- raise ArgumentError, "A secret is required to generate an integrity hash " \
- "for cookie session data. Set a secret_key_base of at least " \
- "#{SECRET_MIN_LENGTH} characters in config/secrets.yml."
- end
+ # To prevent users from using something insecure like "Password" we make sure that the
+ # secret they've provided is at least 30 characters in length.
+ def ensure_secret_secure(secret)
+ if secret.blank?
+ raise ArgumentError, "A secret is required to generate an integrity hash " \
+ "for cookie session data. Set a secret_key_base of at least " \
+ "#{SECRET_MIN_LENGTH} characters in via `bin/rails credentials:edit`."
+ end
- if secret.length < SECRET_MIN_LENGTH
- raise ArgumentError, "Secret should be something secure, " \
- "like \"#{SecureRandom.hex(16)}\". The value you " \
- "provided, \"#{secret}\", is shorter than the minimum length " \
- "of #{SECRET_MIN_LENGTH} characters."
+ if secret.length < SECRET_MIN_LENGTH
+ raise ArgumentError, "Secret should be something secure, " \
+ "like \"#{SecureRandom.hex(16)}\". The value you " \
+ "provided, \"#{secret}\", is shorter than the minimum length " \
+ "of #{SECRET_MIN_LENGTH} characters."
+ end
end
- end
end
end
diff --git a/activesupport/lib/active_support/lazy_load_hooks.rb b/activesupport/lib/active_support/lazy_load_hooks.rb
index e2b8f0f648..dc8080c469 100644
--- a/activesupport/lib/active_support/lazy_load_hooks.rb
+++ b/activesupport/lib/active_support/lazy_load_hooks.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# lazy_load_hooks allows Rails to lazily load a lot of components and thus
# making the app boot faster. Because of this feature now there is no need to
@@ -15,34 +17,62 @@ module ActiveSupport
# end
# end
#
- # When the entirety of +activerecord/lib/active_record/base.rb+ has been
+ # When the entirety of +ActiveRecord::Base+ has been
# evaluated then +run_load_hooks+ is invoked. The very last line of
- # +activerecord/lib/active_record/base.rb+ is:
+ # +ActiveRecord::Base+ is:
#
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
- @load_hooks = Hash.new { |h,k| h[k] = [] }
- @loaded = Hash.new { |h,k| h[k] = [] }
-
- def self.on_load(name, options = {}, &block)
- @loaded[name].each do |base|
- execute_hook(base, options, block)
+ module LazyLoadHooks
+ def self.extended(base) # :nodoc:
+ base.class_eval do
+ @load_hooks = Hash.new { |h, k| h[k] = [] }
+ @loaded = Hash.new { |h, k| h[k] = [] }
+ @run_once = Hash.new { |h, k| h[k] = [] }
+ end
end
- @load_hooks[name] << [block, options]
- end
+ # Declares a block that will be executed when a Rails component is fully
+ # loaded.
+ #
+ # Options:
+ #
+ # * <tt>:yield</tt> - Yields the object that run_load_hooks to +block+.
+ # * <tt>:run_once</tt> - Given +block+ will run only once.
+ def on_load(name, options = {}, &block)
+ @loaded[name].each do |base|
+ execute_hook(name, base, options, block)
+ end
- def self.execute_hook(base, options, block)
- if options[:yield]
- block.call(base)
- else
- base.instance_eval(&block)
+ @load_hooks[name] << [block, options]
end
- end
- def self.run_load_hooks(name, base = Object)
- @loaded[name] << base
- @load_hooks[name].each do |hook, options|
- execute_hook(base, options, hook)
+ def run_load_hooks(name, base = Object)
+ @loaded[name] << base
+ @load_hooks[name].each do |hook, options|
+ execute_hook(name, base, options, hook)
+ end
end
+
+ private
+
+ def with_execution_control(name, block, once)
+ unless @run_once[name].include?(block)
+ @run_once[name] << block if once
+
+ yield
+ end
+ end
+
+ def execute_hook(name, base, options, block)
+ with_execution_control(name, block, options[:run_once]) do
+ if options[:yield]
+ block.call(base)
+ else
+ base.instance_eval(&block)
+ end
+ end
+ end
end
+
+ extend LazyLoadHooks
end
diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb
index e782cd2d4b..0f7be06c8e 100644
--- a/activesupport/lib/active_support/log_subscriber.rb
+++ b/activesupport/lib/active_support/log_subscriber.rb
@@ -1,6 +1,8 @@
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/class/attribute'
-require 'active_support/subscriber'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/attribute_accessors"
+require "active_support/core_ext/class/attribute"
+require "active_support/subscriber"
module ActiveSupport
# ActiveSupport::LogSubscriber is an object set to consume
@@ -49,8 +51,7 @@ module ActiveSupport
CYAN = "\e[36m"
WHITE = "\e[37m"
- mattr_accessor :colorize_logging
- self.colorize_logging = true
+ mattr_accessor :colorize_logging, default: true
class << self
def logger
@@ -81,11 +82,13 @@ module ActiveSupport
def finish(name, id, payload)
super if logger
- rescue Exception => e
- logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
+ rescue => e
+ if logger
+ logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
+ end
end
- protected
+ private
%w(info debug warn error fatal unknown).each do |level|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
@@ -99,7 +102,7 @@ module ActiveSupport
# option is set to +true+, it also adds bold to the string. This is based
# on the Highline implementation and will automatically append CLEAR to the
# end of the returned String.
- def color(text, color, bold=false)
+ def color(text, color, bold = false) # :doc:
return text unless colorize_logging
color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
bold = bold ? BOLD : ""
diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb
index 588ed67c81..3f19ef5009 100644
--- a/activesupport/lib/active_support/log_subscriber/test_helper.rb
+++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb
@@ -1,6 +1,8 @@
-require 'active_support/log_subscriber'
-require 'active_support/logger'
-require 'active_support/notifications'
+# frozen_string_literal: true
+
+require "active_support/log_subscriber"
+require "active_support/logger"
+require "active_support/notifications"
module ActiveSupport
class LogSubscriber
@@ -58,15 +60,15 @@ module ActiveSupport
def initialize(level = DEBUG)
@flush_count = 0
@level = level
- @logged = Hash.new { |h,k| h[k] = [] }
+ @logged = Hash.new { |h, k| h[k] = [] }
end
def method_missing(level, message = nil)
- if block_given?
- @logged[level] << yield
- else
- @logged[level] << message
- end
+ if block_given?
+ @logged[level] << yield
+ else
+ @logged[level] << message
+ end
end
def logged(level)
diff --git a/activesupport/lib/active_support/logger.rb b/activesupport/lib/active_support/logger.rb
index de48e717b6..8152a182b4 100644
--- a/activesupport/lib/active_support/logger.rb
+++ b/activesupport/lib/active_support/logger.rb
@@ -1,6 +1,8 @@
-require 'active_support/logger_silence'
-require 'active_support/logger_thread_safe_level'
-require 'logger'
+# frozen_string_literal: true
+
+require "active_support/logger_silence"
+require "active_support/logger_thread_safe_level"
+require "logger"
module ActiveSupport
class Logger < ::Logger
@@ -55,6 +57,24 @@ module ActiveSupport
logger.local_level = level if logger.respond_to?(:local_level=)
super(level) if respond_to?(:local_level=)
end
+
+ define_method(:silence) do |level = Logger::ERROR, &block|
+ if logger.respond_to?(:silence)
+ logger.silence(level) do
+ if defined?(super)
+ super(level, &block)
+ else
+ block.call(self)
+ end
+ end
+ else
+ if defined?(super)
+ super(level, &block)
+ else
+ block.call(self)
+ end
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/logger_silence.rb b/activesupport/lib/active_support/logger_silence.rb
index 3eb8098c77..89f32b6782 100644
--- a/activesupport/lib/active_support/logger_silence.rb
+++ b/activesupport/lib/active_support/logger_silence.rb
@@ -1,13 +1,14 @@
-require 'active_support/concern'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'concurrent'
+# frozen_string_literal: true
+
+require "active_support/concern"
+require "active_support/core_ext/module/attribute_accessors"
+require "concurrent"
module LoggerSilence
extend ActiveSupport::Concern
included do
- cattr_accessor :silencer
- self.silencer = true
+ cattr_accessor :silencer, default: true
end
# Silences the logger for the duration of the block.
diff --git a/activesupport/lib/active_support/logger_thread_safe_level.rb b/activesupport/lib/active_support/logger_thread_safe_level.rb
index 5fedb5e689..ba32813d3d 100644
--- a/activesupport/lib/active_support/logger_thread_safe_level.rb
+++ b/activesupport/lib/active_support/logger_thread_safe_level.rb
@@ -1,4 +1,6 @@
-require 'active_support/concern'
+# frozen_string_literal: true
+
+require "active_support/concern"
module ActiveSupport
module LoggerThreadSafeLevel # :nodoc:
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
index 2dde01c844..5236c776dd 100644
--- a/activesupport/lib/active_support/message_encryptor.rb
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -1,6 +1,10 @@
-require 'openssl'
-require 'base64'
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "openssl"
+require "base64"
+require "active_support/core_ext/array/extract_options"
+require "active_support/message_verifier"
+require "active_support/messages/metadata"
module ActiveSupport
# MessageEncryptor is a simple way to encrypt values which get stored
@@ -12,12 +16,83 @@ module ActiveSupport
# This can be used in situations similar to the <tt>MessageVerifier</tt>, but
# where you don't want users to be able to determine the value of the payload.
#
- # salt = SecureRandom.random_bytes(64)
- # key = ActiveSupport::KeyGenerator.new('password').generate_key(salt) # => "\x89\xE0\x156\xAC..."
- # crypt = ActiveSupport::MessageEncryptor.new(key) # => #<ActiveSupport::MessageEncryptor ...>
- # encrypted_data = crypt.encrypt_and_sign('my secret data') # => "NlFBTTMwOUV5UlA1QlNEN2xkY2d6eThYWWh..."
- # crypt.decrypt_and_verify(encrypted_data) # => "my secret data"
+ # len = ActiveSupport::MessageEncryptor.key_len
+ # salt = SecureRandom.random_bytes(len)
+ # key = ActiveSupport::KeyGenerator.new('password').generate_key(salt, len) # => "\x89\xE0\x156\xAC..."
+ # crypt = ActiveSupport::MessageEncryptor.new(key) # => #<ActiveSupport::MessageEncryptor ...>
+ # encrypted_data = crypt.encrypt_and_sign('my secret data') # => "NlFBTTMwOUV5UlA1QlNEN2xkY2d6eThYWWh..."
+ # crypt.decrypt_and_verify(encrypted_data) # => "my secret data"
+ #
+ # === Confining messages to a specific purpose
+ #
+ # By default any message can be used throughout your app. But they can also be
+ # confined to a specific +:purpose+.
+ #
+ # token = crypt.encrypt_and_sign("this is the chair", purpose: :login)
+ #
+ # Then that same purpose must be passed when verifying to get the data back out:
+ #
+ # crypt.decrypt_and_verify(token, purpose: :login) # => "this is the chair"
+ # crypt.decrypt_and_verify(token, purpose: :shipping) # => nil
+ # crypt.decrypt_and_verify(token) # => nil
+ #
+ # Likewise, if a message has no purpose it won't be returned when verifying with
+ # a specific purpose.
+ #
+ # token = crypt.encrypt_and_sign("the conversation is lively")
+ # crypt.decrypt_and_verify(token, purpose: :scare_tactics) # => nil
+ # crypt.decrypt_and_verify(token) # => "the conversation is lively"
+ #
+ # === Making messages expire
+ #
+ # By default messages last forever and verifying one year from now will still
+ # return the original value. But messages can be set to expire at a given
+ # time with +:expires_in+ or +:expires_at+.
+ #
+ # crypt.encrypt_and_sign(parcel, expires_in: 1.month)
+ # crypt.encrypt_and_sign(doowad, expires_at: Time.now.end_of_year)
+ #
+ # Then the messages can be verified and returned upto the expire time.
+ # Thereafter, verifying returns +nil+.
+ #
+ # === Rotating keys
+ #
+ # MessageEncryptor also supports rotating out old configurations by falling
+ # back to a stack of encryptors. Call +rotate+ to build and add an encryptor
+ # so +decrypt_and_verify+ will also try the fallback.
+ #
+ # By default any rotated encryptors use the values of the primary
+ # encryptor unless specified otherwise.
+ #
+ # You'd give your encryptor the new defaults:
+ #
+ # crypt = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
+ #
+ # Then gradually rotate the old values out by adding them as fallbacks. Any message
+ # generated with the old values will then work until the rotation is removed.
+ #
+ # crypt.rotate old_secret # Fallback to an old secret instead of @secret.
+ # crypt.rotate cipher: "aes-256-cbc" # Fallback to an old cipher instead of aes-256-gcm.
+ #
+ # Though if both the secret and the cipher was changed at the same time,
+ # the above should be combined into:
+ #
+ # crypt.rotate old_secret, cipher: "aes-256-cbc"
class MessageEncryptor
+ prepend Messages::Rotator::Encryptor
+
+ cattr_accessor :use_authenticated_message_encryption, instance_accessor: false, default: false
+
+ class << self
+ def default_cipher #:nodoc:
+ if use_authenticated_message_encryption
+ "aes-256-gcm"
+ else
+ "aes-256-cbc"
+ end
+ end
+ end
+
module NullSerializer #:nodoc:
def self.load(value)
value
@@ -28,80 +103,126 @@ module ActiveSupport
end
end
+ module NullVerifier #:nodoc:
+ def self.verify(value)
+ value
+ end
+
+ def self.generate(value)
+ value
+ end
+ end
+
class InvalidMessage < StandardError; end
OpenSSLCipherError = OpenSSL::Cipher::CipherError
# Initialize a new MessageEncryptor. +secret+ must be at least as long as
- # the cipher key size. For the default 'aes-256-cbc' cipher, this is 256
+ # the cipher key size. For the default 'aes-256-gcm' cipher, this is 256
# bits. If you are using a user-entered secret, you can generate a suitable
# key by using <tt>ActiveSupport::KeyGenerator</tt> or a similar key
# derivation function.
#
+ # First additional parameter is used as the signature key for +MessageVerifier+.
+ # This allows you to specify keys to encrypt and sign data.
+ #
+ # ActiveSupport::MessageEncryptor.new('secret', 'signature_secret')
+ #
# Options:
# * <tt>:cipher</tt> - Cipher to use. Can be any cipher returned by
- # <tt>OpenSSL::Cipher.ciphers</tt>. Default is 'aes-256-cbc'.
- # * <tt>:digest</tt> - String of digest to use for signing. Default is +SHA1+.
+ # <tt>OpenSSL::Cipher.ciphers</tt>. Default is 'aes-256-gcm'.
+ # * <tt>:digest</tt> - String of digest to use for signing. Default is
+ # +SHA1+. Ignored when using an AEAD cipher like 'aes-256-gcm'.
# * <tt>:serializer</tt> - Object serializer to use. Default is +Marshal+.
def initialize(secret, *signature_key_or_options)
options = signature_key_or_options.extract_options!
sign_secret = signature_key_or_options.first
@secret = secret
@sign_secret = sign_secret
- @cipher = options[:cipher] || 'aes-256-cbc'
- @verifier = MessageVerifier.new(@sign_secret || @secret, digest: options[:digest] || 'SHA1', serializer: NullSerializer)
+ @cipher = options[:cipher] || self.class.default_cipher
+ @digest = options[:digest] || "SHA1" unless aead_mode?
+ @verifier = resolve_verifier
@serializer = options[:serializer] || Marshal
end
# Encrypt and sign a message. We need to sign the message in order to avoid
- # padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks.
- def encrypt_and_sign(value)
- verifier.generate(_encrypt(value))
+ # padding attacks. Reference: https://www.limited-entropy.com/padding-oracle-attacks/.
+ def encrypt_and_sign(value, expires_at: nil, expires_in: nil, purpose: nil)
+ verifier.generate(_encrypt(value, expires_at: expires_at, expires_in: expires_in, purpose: purpose))
end
# Decrypt and verify a message. We need to verify the message in order to
- # avoid padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks.
- def decrypt_and_verify(value)
- _decrypt(verifier.verify(value))
+ # avoid padding attacks. Reference: https://www.limited-entropy.com/padding-oracle-attacks/.
+ def decrypt_and_verify(data, purpose: nil, **)
+ _decrypt(verifier.verify(data), purpose)
end
- private
-
- def _encrypt(value)
- cipher = new_cipher
- cipher.encrypt
- cipher.key = @secret
+ # Given a cipher, returns the key length of the cipher to help generate the key of desired size
+ def self.key_len(cipher = default_cipher)
+ OpenSSL::Cipher.new(cipher).key_len
+ end
- # Rely on OpenSSL for the initialization vector
- iv = cipher.random_iv
+ private
+ def _encrypt(value, **metadata_options)
+ cipher = new_cipher
+ cipher.encrypt
+ cipher.key = @secret
- encrypted_data = cipher.update(@serializer.dump(value))
- encrypted_data << cipher.final
+ # Rely on OpenSSL for the initialization vector
+ iv = cipher.random_iv
+ cipher.auth_data = "" if aead_mode?
- "#{::Base64.strict_encode64 encrypted_data}--#{::Base64.strict_encode64 iv}"
- end
+ encrypted_data = cipher.update(Messages::Metadata.wrap(@serializer.dump(value), metadata_options))
+ encrypted_data << cipher.final
- def _decrypt(encrypted_message)
- cipher = new_cipher
- encrypted_data, iv = encrypted_message.split("--".freeze).map {|v| ::Base64.strict_decode64(v)}
+ blob = "#{::Base64.strict_encode64 encrypted_data}--#{::Base64.strict_encode64 iv}"
+ blob = "#{blob}--#{::Base64.strict_encode64 cipher.auth_tag}" if aead_mode?
+ blob
+ end
- cipher.decrypt
- cipher.key = @secret
- cipher.iv = iv
+ def _decrypt(encrypted_message, purpose)
+ cipher = new_cipher
+ encrypted_data, iv, auth_tag = encrypted_message.split("--".freeze).map { |v| ::Base64.strict_decode64(v) }
+
+ # Currently the OpenSSL bindings do not raise an error if auth_tag is
+ # truncated, which would allow an attacker to easily forge it. See
+ # https://github.com/ruby/openssl/issues/63
+ raise InvalidMessage if aead_mode? && (auth_tag.nil? || auth_tag.bytes.length != 16)
+
+ cipher.decrypt
+ cipher.key = @secret
+ cipher.iv = iv
+ if aead_mode?
+ cipher.auth_tag = auth_tag
+ cipher.auth_data = ""
+ end
+
+ decrypted_data = cipher.update(encrypted_data)
+ decrypted_data << cipher.final
+
+ message = Messages::Metadata.verify(decrypted_data, purpose)
+ @serializer.load(message) if message
+ rescue OpenSSLCipherError, TypeError, ArgumentError
+ raise InvalidMessage
+ end
- decrypted_data = cipher.update(encrypted_data)
- decrypted_data << cipher.final
+ def new_cipher
+ OpenSSL::Cipher.new(@cipher)
+ end
- @serializer.load(decrypted_data)
- rescue OpenSSLCipherError, TypeError, ArgumentError
- raise InvalidMessage
- end
+ def verifier
+ @verifier
+ end
- def new_cipher
- OpenSSL::Cipher::Cipher.new(@cipher)
- end
+ def aead_mode?
+ @aead_mode ||= new_cipher.authenticated?
+ end
- def verifier
- @verifier
- end
+ def resolve_verifier
+ if aead_mode?
+ NullVerifier
+ else
+ MessageVerifier.new(@sign_secret || @secret, digest: @digest, serializer: NullSerializer)
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 4c3deffe6e..83c39c0a86 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -1,6 +1,10 @@
-require 'base64'
-require 'active_support/core_ext/object/blank'
-require 'active_support/security_utils'
+# frozen_string_literal: true
+
+require "base64"
+require "active_support/core_ext/object/blank"
+require "active_support/security_utils"
+require "active_support/messages/metadata"
+require "active_support/messages/rotator"
module ActiveSupport
# +MessageVerifier+ makes it easy to generate and verify messages which are
@@ -27,16 +31,82 @@ module ActiveSupport
#
# +MessageVerifier+ creates HMAC signatures using SHA1 hash algorithm by default.
# If you want to use a different hash algorithm, you can change it by providing
- # `:digest` key as an option while initializing the verifier:
+ # +:digest+ key as an option while initializing the verifier:
#
# @verifier = ActiveSupport::MessageVerifier.new('s3Krit', digest: 'SHA256')
+ #
+ # === Confining messages to a specific purpose
+ #
+ # By default any message can be used throughout your app. But they can also be
+ # confined to a specific +:purpose+.
+ #
+ # token = @verifier.generate("this is the chair", purpose: :login)
+ #
+ # Then that same purpose must be passed when verifying to get the data back out:
+ #
+ # @verifier.verified(token, purpose: :login) # => "this is the chair"
+ # @verifier.verified(token, purpose: :shipping) # => nil
+ # @verifier.verified(token) # => nil
+ #
+ # @verifier.verify(token, purpose: :login) # => "this is the chair"
+ # @verifier.verify(token, purpose: :shipping) # => ActiveSupport::MessageVerifier::InvalidSignature
+ # @verifier.verify(token) # => ActiveSupport::MessageVerifier::InvalidSignature
+ #
+ # Likewise, if a message has no purpose it won't be returned when verifying with
+ # a specific purpose.
+ #
+ # token = @verifier.generate("the conversation is lively")
+ # @verifier.verified(token, purpose: :scare_tactics) # => nil
+ # @verifier.verified(token) # => "the conversation is lively"
+ #
+ # @verifier.verify(token, purpose: :scare_tactics) # => ActiveSupport::MessageVerifier::InvalidSignature
+ # @verifier.verify(token) # => "the conversation is lively"
+ #
+ # === Making messages expire
+ #
+ # By default messages last forever and verifying one year from now will still
+ # return the original value. But messages can be set to expire at a given
+ # time with +:expires_in+ or +:expires_at+.
+ #
+ # @verifier.generate(parcel, expires_in: 1.month)
+ # @verifier.generate(doowad, expires_at: Time.now.end_of_year)
+ #
+ # Then the messages can be verified and returned upto the expire time.
+ # Thereafter, the +verified+ method returns +nil+ while +verify+ raises
+ # <tt>ActiveSupport::MessageVerifier::InvalidSignature</tt>.
+ #
+ # === Rotating keys
+ #
+ # MessageVerifier also supports rotating out old configurations by falling
+ # back to a stack of verifiers. Call +rotate+ to build and add a verifier to
+ # so either +verified+ or +verify+ will also try verifying with the fallback.
+ #
+ # By default any rotated verifiers use the values of the primary
+ # verifier unless specified otherwise.
+ #
+ # You'd give your verifier the new defaults:
+ #
+ # verifier = ActiveSupport::MessageVerifier.new(@secret, digest: "SHA512", serializer: JSON)
+ #
+ # Then gradually rotate the old values out by adding them as fallbacks. Any message
+ # generated with the old values will then work until the rotation is removed.
+ #
+ # verifier.rotate old_secret # Fallback to an old secret instead of @secret.
+ # verifier.rotate digest: "SHA256" # Fallback to an old digest instead of SHA512.
+ # verifier.rotate serializer: Marshal # Fallback to an old serializer instead of JSON.
+ #
+ # Though the above would most likely be combined into one rotation:
+ #
+ # verifier.rotate old_secret, digest: "SHA256", serializer: Marshal
class MessageVerifier
+ prepend Messages::Rotator::Verifier
+
class InvalidSignature < StandardError; end
def initialize(secret, options = {})
- raise ArgumentError, 'Secret should not be nil.' unless secret
+ raise ArgumentError, "Secret should not be nil." unless secret
@secret = secret
- @digest = options[:digest] || 'SHA1'
+ @digest = options[:digest] || "SHA1"
@serializer = options[:serializer] || Marshal
end
@@ -77,13 +147,14 @@ module ActiveSupport
#
# incompatible_message = "test--dad7b06c94abba8d46a15fafaef56c327665d5ff"
# verifier.verified(incompatible_message) # => TypeError: incompatible marshal file format
- def verified(signed_message)
+ def verified(signed_message, purpose: nil, **)
if valid_message?(signed_message)
begin
data = signed_message.split("--".freeze)[0]
- @serializer.load(decode(data))
+ message = Messages::Metadata.verify(decode(data), purpose)
+ @serializer.load(message) if message
rescue ArgumentError => argument_error
- return if argument_error.message =~ %r{invalid base64}
+ return if argument_error.message.include?("invalid base64")
raise
end
end
@@ -101,8 +172,8 @@ module ActiveSupport
#
# other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit'
# other_verifier.verify(signed_message) # => ActiveSupport::MessageVerifier::InvalidSignature
- def verify(signed_message)
- verified(signed_message) || raise(InvalidSignature)
+ def verify(*args)
+ verified(*args) || raise(InvalidSignature)
end
# Generates a signed message for the provided value.
@@ -112,8 +183,8 @@ module ActiveSupport
#
# verifier = ActiveSupport::MessageVerifier.new 's3Krit'
# verifier.generate 'a private message' # => "BAhJIhRwcml2YXRlLW1lc3NhZ2UGOgZFVA==--e2d724331ebdee96a10fb99b089508d1c72bd772"
- def generate(value)
- data = encode(@serializer.dump(value))
+ def generate(value, expires_at: nil, expires_in: nil, purpose: nil)
+ data = encode(Messages::Metadata.wrap(@serializer.dump(value), expires_at: expires_at, expires_in: expires_in, purpose: purpose))
"#{data}--#{generate_digest(data)}"
end
@@ -127,7 +198,7 @@ module ActiveSupport
end
def generate_digest(data)
- require 'openssl' unless defined?(OpenSSL)
+ require "openssl" unless defined?(OpenSSL)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
end
end
diff --git a/activesupport/lib/active_support/messages/metadata.rb b/activesupport/lib/active_support/messages/metadata.rb
new file mode 100644
index 0000000000..e97caac766
--- /dev/null
+++ b/activesupport/lib/active_support/messages/metadata.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+require "time"
+
+module ActiveSupport
+ module Messages #:nodoc:
+ class Metadata #:nodoc:
+ def initialize(message, expires_at = nil, purpose = nil)
+ @message, @expires_at, @purpose = message, expires_at, purpose
+ end
+
+ def as_json(options = {})
+ { _rails: { message: @message, exp: @expires_at, pur: @purpose } }
+ end
+
+ class << self
+ def wrap(message, expires_at: nil, expires_in: nil, purpose: nil)
+ if expires_at || expires_in || purpose
+ JSON.encode new(encode(message), pick_expiry(expires_at, expires_in), purpose)
+ else
+ message
+ end
+ end
+
+ def verify(message, purpose)
+ extract_metadata(message).verify(purpose)
+ end
+
+ private
+ def pick_expiry(expires_at, expires_in)
+ if expires_at
+ expires_at.utc.iso8601(3)
+ elsif expires_in
+ Time.now.utc.advance(seconds: expires_in).iso8601(3)
+ end
+ end
+
+ def extract_metadata(message)
+ data = JSON.decode(message) rescue nil
+
+ if data.is_a?(Hash) && data.key?("_rails")
+ new(decode(data["_rails"]["message"]), data["_rails"]["exp"], data["_rails"]["pur"])
+ else
+ new(message)
+ end
+ end
+
+ def encode(message)
+ ::Base64.strict_encode64(message)
+ end
+
+ def decode(message)
+ ::Base64.strict_decode64(message)
+ end
+ end
+
+ def verify(purpose)
+ @message if match?(purpose) && fresh?
+ end
+
+ private
+ def match?(purpose)
+ @purpose.to_s == purpose.to_s
+ end
+
+ def fresh?
+ @expires_at.nil? || Time.now.utc < Time.iso8601(@expires_at)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/messages/rotation_configuration.rb b/activesupport/lib/active_support/messages/rotation_configuration.rb
new file mode 100644
index 0000000000..bd50d6d348
--- /dev/null
+++ b/activesupport/lib/active_support/messages/rotation_configuration.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module ActiveSupport
+ module Messages
+ class RotationConfiguration # :nodoc:
+ attr_reader :signed, :encrypted
+
+ def initialize
+ @signed, @encrypted = [], []
+ end
+
+ def rotate(kind, *args)
+ case kind
+ when :signed
+ @signed << args
+ when :encrypted
+ @encrypted << args
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/messages/rotator.rb b/activesupport/lib/active_support/messages/rotator.rb
new file mode 100644
index 0000000000..823a399d67
--- /dev/null
+++ b/activesupport/lib/active_support/messages/rotator.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module ActiveSupport
+ module Messages
+ module Rotator # :nodoc:
+ def initialize(*, **options)
+ super
+
+ @options = options
+ @rotations = []
+ end
+
+ def rotate(*secrets, **options)
+ @rotations << build_rotation(*secrets, @options.merge(options))
+ end
+
+ module Encryptor
+ include Rotator
+
+ def decrypt_and_verify(*args, on_rotation: nil, **options)
+ super
+ rescue MessageEncryptor::InvalidMessage, MessageVerifier::InvalidSignature
+ run_rotations(on_rotation) { |encryptor| encryptor.decrypt_and_verify(*args, options) } || raise
+ end
+
+ private
+ def build_rotation(secret = @secret, sign_secret = @sign_secret, options)
+ self.class.new(secret, sign_secret, options)
+ end
+ end
+
+ module Verifier
+ include Rotator
+
+ def verified(*args, on_rotation: nil, **options)
+ super || run_rotations(on_rotation) { |verifier| verifier.verified(*args, options) }
+ end
+
+ private
+ def build_rotation(secret = @secret, options)
+ self.class.new(secret, options)
+ end
+ end
+
+ private
+ def run_rotations(on_rotation)
+ @rotations.find do |rotation|
+ if message = yield(rotation) rescue next
+ on_rotation.call if on_rotation
+ return message
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb
index ffebd9a60b..3fe3a05e93 100644
--- a/activesupport/lib/active_support/multibyte.rb
+++ b/activesupport/lib/active_support/multibyte.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
module ActiveSupport #:nodoc:
module Multibyte
- autoload :Chars, 'active_support/multibyte/chars'
- autoload :Unicode, 'active_support/multibyte/unicode'
+ autoload :Chars, "active_support/multibyte/chars"
+ autoload :Unicode, "active_support/multibyte/unicode"
# The proxy class returned when calling mb_chars. You can use this accessor
# to configure your own proxy class so you can support other encodings. See
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index 707cf200b5..8152b8fd22 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -1,7 +1,10 @@
-require 'active_support/json'
-require 'active_support/core_ext/string/access'
-require 'active_support/core_ext/string/behavior'
-require 'active_support/core_ext/module/delegation'
+# frozen_string_literal: true
+
+require "active_support/json"
+require "active_support/core_ext/string/access"
+require "active_support/core_ext/string/behavior"
+require "active_support/core_ext/module/delegation"
+require "active_support/core_ext/regexp"
module ActiveSupport #:nodoc:
module Multibyte #:nodoc:
@@ -15,7 +18,8 @@ module ActiveSupport #:nodoc:
# through the +mb_chars+ method. Methods which would normally return a
# String object now return a Chars object so methods can be chained.
#
- # 'The Perfect String '.mb_chars.downcase.strip.normalize # => "the perfect string"
+ # 'The Perfect String '.mb_chars.downcase.strip.normalize
+ # # => #<ActiveSupport::Multibyte::Chars:0x007fdc434ccc10 @wrapped_string="the perfect string">
#
# Chars objects are perfectly interchangeable with String objects as long as
# no explicit class checks are made. If certain methods do explicitly check
@@ -45,7 +49,7 @@ module ActiveSupport #:nodoc:
alias to_s wrapped_string
alias to_str wrapped_string
- delegate :<=>, :=~, :acts_like_string?, :to => :wrapped_string
+ delegate :<=>, :=~, :acts_like_string?, to: :wrapped_string
# Creates a new Chars instance by wrapping _string_.
def initialize(string)
@@ -56,7 +60,7 @@ module ActiveSupport #:nodoc:
# Forward all undefined methods to the wrapped string.
def method_missing(method, *args, &block)
result = @wrapped_string.__send__(method, *args, &block)
- if method.to_s =~ /!$/
+ if /!$/.match?(method)
self if result
else
result.kind_of?(String) ? chars(result) : result
@@ -86,7 +90,7 @@ module ActiveSupport #:nodoc:
end
# Works like <tt>String#slice!</tt>, but returns an instance of
- # Chars, or nil if the string was not modified. The string will not be
+ # Chars, or +nil+ if the string was not modified. The string will not be
# modified if the range given is out of bounds
#
# string = 'Welcome'
@@ -105,7 +109,7 @@ module ActiveSupport #:nodoc:
#
# 'Café'.mb_chars.reverse.to_s # => 'éfaC'
def reverse
- chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*'))
+ chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack("U*"))
end
# Limits the byte size of the string to a number of bytes without breaking
@@ -133,7 +137,7 @@ module ActiveSupport #:nodoc:
# Converts characters in the string to the opposite case.
#
- # 'El Cañón".mb_chars.swapcase.to_s # => "eL cAÑÓN"
+ # 'El Cañón'.mb_chars.swapcase.to_s # => "eL cAÑÓN"
def swapcase
chars Unicode.swapcase(@wrapped_string)
end
@@ -142,15 +146,15 @@ module ActiveSupport #:nodoc:
#
# 'über'.mb_chars.capitalize.to_s # => "Über"
def capitalize
- (slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
+ (slice(0) || chars("")).upcase + (slice(1..-1) || chars("")).downcase
end
# Capitalizes the first letter of every word, when possible.
#
- # "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
- # "日本語".mb_chars.titleize # => "日本語"
+ # "ÉL QUE SE ENTERÓ".mb_chars.titleize.to_s # => "Él Que Se Enteró"
+ # "日本語".mb_chars.titleize.to_s # => "日本語"
def titleize
- chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
+ chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1) })
end
alias_method :titlecase, :titleize
@@ -170,7 +174,7 @@ module ActiveSupport #:nodoc:
# 'é'.length # => 2
# 'é'.mb_chars.decompose.to_s.length # => 3
def decompose
- chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack('U*'))
+ chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack("U*"))
end
# Performs composition on all the characters.
@@ -178,7 +182,7 @@ module ActiveSupport #:nodoc:
# 'é'.length # => 3
# 'é'.mb_chars.compose.to_s.length # => 2
def compose
- chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack('U*'))
+ chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack("U*"))
end
# Returns the number of grapheme clusters in the string.
@@ -209,21 +213,21 @@ module ActiveSupport #:nodoc:
end
end
- protected
+ private
- def translate_offset(byte_offset) #:nodoc:
+ def translate_offset(byte_offset)
return nil if byte_offset.nil?
- return 0 if @wrapped_string == ''
+ return 0 if @wrapped_string == ""
begin
- @wrapped_string.byteslice(0...byte_offset).unpack('U*').length
+ @wrapped_string.byteslice(0...byte_offset).unpack("U*").length
rescue ArgumentError
byte_offset -= 1
retry
end
end
- def chars(string) #:nodoc:
+ def chars(string)
self.class.new(string)
end
end
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
index 72b20fff06..a64223c0e0 100644
--- a/activesupport/lib/active_support/multibyte/unicode.rb
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -1,7 +1,8 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Multibyte
module Unicode
-
extend self
# A list of all available normalization forms.
@@ -10,7 +11,7 @@ module ActiveSupport
NORMALIZATION_FORMS = [:c, :kc, :d, :kd]
# The Unicode version that is supported by the implementation
- UNICODE_VERSION = '8.0.0'
+ UNICODE_VERSION = "9.0.0"
# The default normalization used for operations that require
# normalization. It can be set to any of the normalizations
@@ -31,36 +32,6 @@ module ActiveSupport
HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT
HANGUL_SCOUNT = 11172
HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT
- HANGUL_JAMO_FIRST = 0x1100
- HANGUL_JAMO_LAST = 0x11FF
-
- # All the unicode whitespace
- WHITESPACE = [
- (0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D>
- 0x0020, # White_Space # Zs SPACE
- 0x0085, # White_Space # Cc <control-0085>
- 0x00A0, # White_Space # Zs NO-BREAK SPACE
- 0x1680, # White_Space # Zs OGHAM SPACE MARK
- (0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE
- 0x2028, # White_Space # Zl LINE SEPARATOR
- 0x2029, # White_Space # Zp PARAGRAPH SEPARATOR
- 0x202F, # White_Space # Zs NARROW NO-BREAK SPACE
- 0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE
- 0x3000, # White_Space # Zs IDEOGRAPHIC SPACE
- ].flatten.freeze
-
- # BOM (byte order mark) can also be seen as whitespace, it's a
- # non-rendering character used to distinguish between little and big
- # endian. This is not an issue in utf-8, so it must be ignored.
- LEADERS_AND_TRAILERS = WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM
-
- # Returns a regular expression pattern that matches the passed Unicode
- # codepoints.
- def self.codepoints_to_pattern(array_of_codepoints) #:nodoc:
- array_of_codepoints.collect{ |e| [e].pack 'U*'.freeze }.join('|'.freeze)
- end
- TRAILERS_PAT = /(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+\Z/u
- LEADERS_PAT = /\A(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+/u
# Detect whether the codepoint is in a certain character class. Returns
# +true+ when it's in the specified character class and +false+ otherwise.
@@ -83,35 +54,35 @@ module ActiveSupport
pos = 0
marker = 0
eoc = codepoints.length
- while(pos < eoc)
+ while (pos < eoc)
pos += 1
- previous = codepoints[pos-1]
+ previous = codepoints[pos - 1]
current = codepoints[pos]
+ # See http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
should_break =
+ if pos == eoc
+ true
# GB3. CR X LF
- if previous == database.boundary[:cr] and current == database.boundary[:lf]
+ elsif previous == database.boundary[:cr] && current == database.boundary[:lf]
false
# GB4. (Control|CR|LF) ÷
- elsif previous and in_char_class?(previous, [:control,:cr,:lf])
+ elsif previous && in_char_class?(previous, [:control, :cr, :lf])
true
# GB5. ÷ (Control|CR|LF)
- elsif in_char_class?(current, [:control,:cr,:lf])
+ elsif in_char_class?(current, [:control, :cr, :lf])
true
# GB6. L X (L|V|LV|LVT)
- elsif database.boundary[:l] === previous and in_char_class?(current, [:l,:v,:lv,:lvt])
+ elsif database.boundary[:l] === previous && in_char_class?(current, [:l, :v, :lv, :lvt])
false
# GB7. (LV|V) X (V|T)
- elsif in_char_class?(previous, [:lv,:v]) and in_char_class?(current, [:v,:t])
+ elsif in_char_class?(previous, [:lv, :v]) && in_char_class?(current, [:v, :t])
false
# GB8. (LVT|T) X (T)
- elsif in_char_class?(previous, [:lvt,:t]) and database.boundary[:t] === current
- false
- # GB8a. Regional_Indicator X Regional_Indicator
- elsif database.boundary[:regional_indicator] === previous and database.boundary[:regional_indicator] === current
+ elsif in_char_class?(previous, [:lvt, :t]) && database.boundary[:t] === current
false
- # GB9. X Extend
- elsif database.boundary[:extend] === current
+ # GB9. X (Extend | ZWJ)
+ elsif in_char_class?(current, [:extend, :zwj])
false
# GB9a. X SpacingMark
elsif database.boundary[:spacingmark] === current
@@ -119,13 +90,23 @@ module ActiveSupport
# GB9b. Prepend X
elsif database.boundary[:prepend] === previous
false
- # GB10. Any ÷ Any
+ # GB10. (E_Base | EBG) Extend* X E_Modifier
+ elsif (marker...pos).any? { |i| in_char_class?(codepoints[i], [:e_base, :e_base_gaz]) && codepoints[i + 1...pos].all? { |c| database.boundary[:extend] === c } } && database.boundary[:e_modifier] === current
+ false
+ # GB11. ZWJ X (Glue_After_Zwj | EBG)
+ elsif database.boundary[:zwj] === previous && in_char_class?(current, [:glue_after_zwj, :e_base_gaz])
+ false
+ # GB12. ^ (RI RI)* RI X RI
+ # GB13. [^RI] (RI RI)* RI X RI
+ elsif codepoints[marker..pos].all? { |c| database.boundary[:regional_indicator] === c } && codepoints[marker..pos].count { |c| database.boundary[:regional_indicator] === c }.even?
+ false
+ # GB999. Any ÷ Any
else
true
end
if should_break
- unpacked << codepoints[marker..pos-1]
+ unpacked << codepoints[marker..pos - 1]
marker = pos
end
end
@@ -136,17 +117,17 @@ module ActiveSupport
#
# Unicode.pack_graphemes(Unicode.unpack_graphemes('क्षि')) # => 'क्षि'
def pack_graphemes(unpacked)
- unpacked.flatten.pack('U*')
+ unpacked.flatten.pack("U*")
end
# Re-order codepoints so the string becomes canonical.
def reorder_characters(codepoints)
- length = codepoints.length- 1
+ length = codepoints.length - 1
pos = 0
while pos < length do
- cp1, cp2 = database.codepoints[codepoints[pos]], database.codepoints[codepoints[pos+1]]
+ cp1, cp2 = database.codepoints[codepoints[pos]], database.codepoints[codepoints[pos + 1]]
if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0)
- codepoints[pos..pos+1] = cp2.code, cp1.code
+ codepoints[pos..pos + 1] = cp2.code, cp1.code
pos += (pos > 0 ? -1 : 1)
else
pos += 1
@@ -159,7 +140,7 @@ module ActiveSupport
def decompose(type, codepoints)
codepoints.inject([]) do |decomposed, cp|
# if it's a hangul syllable starter character
- if HANGUL_SBASE <= cp and cp < HANGUL_SLAST
+ if HANGUL_SBASE <= cp && cp < HANGUL_SLAST
sindex = cp - HANGUL_SBASE
ncp = [] # new codepoints
ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT
@@ -168,7 +149,7 @@ module ActiveSupport
ncp << (HANGUL_TBASE + tindex) unless tindex == 0
decomposed.concat ncp
# if the codepoint is decomposable in with the current decomposition type
- elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatibility)
+ elsif (ncp = database.codepoints[cp].decomp_mapping) && (!database.codepoints[cp].decomp_type || type == :compatibility)
decomposed.concat decompose(type, ncp.dup)
else
decomposed << cp
@@ -187,11 +168,11 @@ module ActiveSupport
pos += 1
lindex = starter_char - HANGUL_LBASE
# -- Hangul
- if 0 <= lindex and lindex < HANGUL_LCOUNT
- vindex = codepoints[starter_pos+1] - HANGUL_VBASE rescue vindex = -1
- if 0 <= vindex and vindex < HANGUL_VCOUNT
- tindex = codepoints[starter_pos+2] - HANGUL_TBASE rescue tindex = -1
- if 0 <= tindex and tindex < HANGUL_TCOUNT
+ if 0 <= lindex && lindex < HANGUL_LCOUNT
+ vindex = codepoints[starter_pos + 1] - HANGUL_VBASE rescue vindex = -1
+ if 0 <= vindex && vindex < HANGUL_VCOUNT
+ tindex = codepoints[starter_pos + 2] - HANGUL_TBASE rescue tindex = -1
+ if 0 <= tindex && tindex < HANGUL_TCOUNT
j = starter_pos + 2
eoa -= 2
else
@@ -259,7 +240,7 @@ module ActiveSupport
reader = Encoding::Converter.new(Encoding::UTF_8, Encoding::UTF_16LE)
source = string.dup
- out = ''.force_encoding(Encoding::UTF_16LE)
+ out = "".force_encoding(Encoding::UTF_16LE)
loop do
reader.primitive_convert(source, out)
@@ -282,22 +263,22 @@ module ActiveSupport
# * <tt>form</tt> - The form you want to normalize in. Should be one of
# the following: <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>.
# Default is ActiveSupport::Multibyte::Unicode.default_normalization_form.
- def normalize(string, form=nil)
+ def normalize(string, form = nil)
form ||= @default_normalization_form
# See http://www.unicode.org/reports/tr15, Table 1
codepoints = string.codepoints.to_a
case form
- when :d
- reorder_characters(decompose(:canonical, codepoints))
- when :c
- compose(reorder_characters(decompose(:canonical, codepoints)))
- when :kd
- reorder_characters(decompose(:compatibility, codepoints))
- when :kc
- compose(reorder_characters(decompose(:compatibility, codepoints)))
+ when :d
+ reorder_characters(decompose(:canonical, codepoints))
+ when :c
+ compose(reorder_characters(decompose(:canonical, codepoints)))
+ when :kd
+ reorder_characters(decompose(:compatibility, codepoints))
+ when :kc
+ compose(reorder_characters(decompose(:compatibility, codepoints)))
else
- raise ArgumentError, "#{form} is not a valid normalization variant", caller
- end.pack('U*'.freeze)
+ raise ArgumentError, "#{form} is not a valid normalization variant", caller
+ end.pack("U*".freeze)
end
def downcase(string)
@@ -356,7 +337,7 @@ module ActiveSupport
# UnicodeDatabase.
def load
begin
- @codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, 'rb') { |f| Marshal.load f.read }
+ @codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, "rb") { |f| Marshal.load f.read }
rescue => e
raise IOError.new("Couldn't load the Unicode tables for UTF8Handler (#{e.message}), ActiveSupport::Multibyte is unusable")
end
@@ -378,7 +359,7 @@ module ActiveSupport
# Returns the directory in which the data files are stored.
def self.dirname
- File.dirname(__FILE__) + '/../values/'
+ File.expand_path("../values", __dir__)
end
# Returns the filename for the data file for this version.
@@ -389,25 +370,25 @@ module ActiveSupport
private
- def apply_mapping(string, mapping) #:nodoc:
- database.codepoints
- string.each_codepoint.map do |codepoint|
- cp = database.codepoints[codepoint]
- if cp and (ncp = cp.send(mapping)) and ncp > 0
- ncp
- else
- codepoint
- end
- end.pack('U*')
- end
+ def apply_mapping(string, mapping)
+ database.codepoints
+ string.each_codepoint.map do |codepoint|
+ cp = database.codepoints[codepoint]
+ if cp && (ncp = cp.send(mapping)) && ncp > 0
+ ncp
+ else
+ codepoint
+ end
+ end.pack("U*")
+ end
- def recode_windows1252_chars(string)
- string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace)
- end
+ def recode_windows1252_chars(string)
+ string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace)
+ end
- def database
- @database ||= UnicodeDatabase.new
- end
+ def database
+ @database ||= UnicodeDatabase.new
+ end
end
end
end
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index 823d68e507..6207de8094 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -1,6 +1,8 @@
-require 'active_support/notifications/instrumenter'
-require 'active_support/notifications/fanout'
-require 'active_support/per_thread_registry'
+# frozen_string_literal: true
+
+require "active_support/notifications/instrumenter"
+require "active_support/notifications/fanout"
+require "active_support/per_thread_registry"
module ActiveSupport
# = Notifications
@@ -13,7 +15,7 @@ module ActiveSupport
# To instrument an event you just need to do:
#
# ActiveSupport::Notifications.instrument('render', extra: :information) do
- # render text: 'Foo'
+ # render plain: 'Foo'
# end
#
# That first executes the block and then notifies all subscribers once done.
@@ -48,7 +50,7 @@ module ActiveSupport
# The block is saved and will be called whenever someone instruments "render":
#
# ActiveSupport::Notifications.instrument('render', extra: :information) do
- # render text: 'Foo'
+ # render plain: 'Foo'
# end
#
# event = events.first
@@ -64,6 +66,8 @@ module ActiveSupport
# If an exception happens during that particular instrumentation the payload will
# have a key <tt>:exception</tt> with an array of two elements as value: a string with
# the name of the exception class, and the exception message.
+ # The <tt>:exception_object</tt> key of the payload will have the exception
+ # itself as the value.
#
# As the previous example depicts, the class <tt>ActiveSupport::Notifications::Event</tt>
# is able to take the arguments as they come and provide an object-oriented
diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb
index c53f9c1039..25aab175b4 100644
--- a/activesupport/lib/active_support/notifications/fanout.rb
+++ b/activesupport/lib/active_support/notifications/fanout.rb
@@ -1,5 +1,7 @@
-require 'mutex_m'
-require 'concurrent/map'
+# frozen_string_literal: true
+
+require "mutex_m"
+require "concurrent/map"
module ActiveSupport
module Notifications
@@ -68,7 +70,7 @@ module ActiveSupport
module Subscribers # :nodoc:
def self.new(pattern, listener)
- if listener.respond_to?(:start) and listener.respond_to?(:finish)
+ if listener.respond_to?(:start) && listener.respond_to?(:finish)
subscriber = Evented.new pattern, listener
else
subscriber = Timed.new pattern, listener
diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb
index 91f94cb2d7..e99f5ee688 100644
--- a/activesupport/lib/active_support/notifications/instrumenter.rb
+++ b/activesupport/lib/active_support/notifications/instrumenter.rb
@@ -1,4 +1,6 @@
-require 'securerandom'
+# frozen_string_literal: true
+
+require "securerandom"
module ActiveSupport
module Notifications
@@ -14,7 +16,7 @@ module ActiveSupport
# Instrument the given block by measuring the time taken to execute it
# and publish it. Notice that events get sent even if an error occurs
# in the passed-in block.
- def instrument(name, payload={})
+ def instrument(name, payload = {})
# some of the listeners might have state
listeners_state = start name, payload
begin
@@ -44,9 +46,9 @@ module ActiveSupport
private
- def unique_id
- SecureRandom.hex(10)
- end
+ def unique_id
+ SecureRandom.hex(10)
+ end
end
class Event
diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb
index 7a49bbb960..8fd6e932f1 100644
--- a/activesupport/lib/active_support/number_helper.rb
+++ b/activesupport/lib/active_support/number_helper.rb
@@ -1,9 +1,12 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
extend ActiveSupport::Autoload
eager_autoload do
autoload :NumberConverter
+ autoload :RoundingHelper
autoload :NumberToRoundedConverter
autoload :NumberToDelimitedConverter
autoload :NumberToHumanConverter
@@ -45,7 +48,7 @@ module ActiveSupport
#
# number_to_phone(75561234567, pattern: /(\d{1,4})(\d{4})(\d{4})$/, area_code: true)
# # => "(755) 6123-4567"
- # number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/))
+ # number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/)
# # => "133-1234-5678"
def number_to_phone(number, options = {})
NumberToPhoneConverter.convert(number, options)
@@ -78,7 +81,7 @@ module ActiveSupport
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
# currency, and <tt>%n</tt> for the number.
# * <tt>:negative_format</tt> - Sets the format for negative
- # numbers (defaults to prepending an hyphen to the formatted
+ # numbers (defaults to prepending a hyphen to the formatted
# number given by <tt>:format</tt>). Accepts the same fields
# than <tt>:format</tt>, except <tt>%n</tt> is here the
# absolute value of the number.
@@ -109,7 +112,7 @@ module ActiveSupport
# * <tt>:locale</tt> - Sets the locale to be used for formatting
# (defaults to current locale).
# * <tt>:precision</tt> - Sets the precision of the number
- # (defaults to 3). Keeps the number's precision if nil.
+ # (defaults to 3). Keeps the number's precision if +nil+.
# * <tt>:significant</tt> - If +true+, precision will be the number
# of significant_digits. If +false+, the number of fractional
# digits (defaults to +false+).
@@ -183,7 +186,7 @@ module ActiveSupport
# * <tt>:locale</tt> - Sets the locale to be used for formatting
# (defaults to current locale).
# * <tt>:precision</tt> - Sets the precision of the number
- # (defaults to 3). Keeps the number's precision if nil.
+ # (defaults to 3). Keeps the number's precision if +nil+.
# * <tt>:significant</tt> - If +true+, precision will be the number
# of significant_digits. If +false+, the number of fractional
# digits (defaults to +false+).
diff --git a/activesupport/lib/active_support/number_helper/number_converter.rb b/activesupport/lib/active_support/number_helper/number_converter.rb
index 9d976f1831..06ba797a13 100644
--- a/activesupport/lib/active_support/number_helper/number_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_converter.rb
@@ -1,8 +1,10 @@
-require 'active_support/core_ext/big_decimal/conversions'
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/hash/keys'
-require 'active_support/i18n'
-require 'active_support/core_ext/class/attribute'
+# frozen_string_literal: true
+
+require "active_support/core_ext/big_decimal/conversions"
+require "active_support/core_ext/object/blank"
+require "active_support/core_ext/hash/keys"
+require "active_support/i18n"
+require "active_support/core_ext/class/attribute"
module ActiveSupport
module NumberHelper
@@ -139,17 +141,17 @@ module ActiveSupport
@options ||= format_options.merge(opts)
end
- def format_options #:nodoc:
+ def format_options
default_format_options.merge!(i18n_format_options)
end
- def default_format_options #:nodoc:
+ def default_format_options
options = DEFAULTS[:format].dup
options.merge!(DEFAULTS[namespace][:format]) if namespace
options
end
- def i18n_format_options #:nodoc:
+ def i18n_format_options
locale = opts[:locale]
options = I18n.translate(:'number.format', locale: locale, default: {}).dup
@@ -160,7 +162,7 @@ module ActiveSupport
options
end
- def translate_number_value_with_default(key, i18n_options = {}) #:nodoc:
+ def translate_number_value_with_default(key, i18n_options = {})
I18n.translate(key, { default: default_value(key), scope: :number }.merge!(i18n_options))
end
@@ -169,10 +171,10 @@ module ActiveSupport
end
def default_value(key)
- key.split('.').reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] }
+ key.split(".").reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] }
end
- def valid_float? #:nodoc:
+ def valid_float?
Float(number)
rescue ArgumentError, TypeError
false
diff --git a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb
index 57f40f33bf..3f037c73ed 100644
--- a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/numeric/inquiry'
+# frozen_string_literal: true
+
+require "active_support/core_ext/numeric/inquiry"
module ActiveSupport
module NumberHelper
@@ -15,13 +17,13 @@ module ActiveSupport
end
rounded_number = NumberToRoundedConverter.convert(number, options)
- format.gsub('%n'.freeze, rounded_number).gsub('%u'.freeze, options[:unit])
+ format.gsub("%n".freeze, rounded_number).gsub("%u".freeze, options[:unit])
end
private
def absolute_value(number)
- number.respond_to?(:abs) ? number.abs : number.sub(/\A-/, '')
+ number.respond_to?(:abs) ? number.abs : number.sub(/\A-/, "")
end
def options
diff --git a/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb b/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb
index 43c5540b6f..d5b5706705 100644
--- a/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
class NumberToDelimitedConverter < NumberConverter #:nodoc:
@@ -12,7 +14,7 @@ module ActiveSupport
private
def parts
- left, right = number.to_s.split('.'.freeze)
+ left, right = number.to_s.split(".".freeze)
left.gsub!(delimiter_pattern) do |digit_to_delimit|
"#{digit_to_delimit}#{options[:delimiter]}"
end
@@ -22,7 +24,6 @@ module ActiveSupport
def delimiter_pattern
options.fetch(:delimiter_pattern, DEFAULT_DELIMITER_REGEX)
end
-
end
end
end
diff --git a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
index 7a1f8171c0..03eb6671ec 100644
--- a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
class NumberToHumanConverter < NumberConverter # :nodoc:
@@ -9,6 +11,7 @@ module ActiveSupport
self.validate_float = true
def convert # :nodoc:
+ @number = RoundingHelper.new(options).round(number)
@number = Float(number)
# for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
@@ -18,29 +21,26 @@ module ActiveSupport
units = opts[:units]
exponent = calculate_exponent(units)
- @number = number / (10 ** exponent)
+ @number = number / (10**exponent)
- until (rounded_number = NumberToRoundedConverter.convert(number, options)) != NumberToRoundedConverter.convert(1000, options)
- @number = number / 1000.0
- exponent += 3
- end
+ rounded_number = NumberToRoundedConverter.convert(number, options)
unit = determine_unit(units, exponent)
- format.gsub('%n'.freeze, rounded_number).gsub('%u'.freeze, unit).strip
+ format.gsub("%n".freeze, rounded_number).gsub("%u".freeze, unit).strip
end
private
def format
- options[:format] || translate_in_locale('human.decimal_units.format')
+ options[:format] || translate_in_locale("human.decimal_units.format")
end
def determine_unit(units, exponent)
exp = DECIMAL_UNITS[exponent]
case units
when Hash
- units[exp] || ''
+ units[exp] || ""
when String, Symbol
- I18n.translate("#{units}.#{exp}", :locale => options[:locale], :count => number.to_i)
+ I18n.translate("#{units}.#{exp}", locale: options[:locale], count: number.to_i)
else
translate_in_locale("human.decimal_units.units.#{exp}", count: number.to_i)
end
@@ -56,7 +56,7 @@ module ActiveSupport
when Hash
units
when String, Symbol
- I18n.translate(units.to_s, :locale => options[:locale], :raise => true)
+ I18n.translate(units.to_s, locale: options[:locale], raise: true)
when nil
translate_in_locale("human.decimal_units.units", raise: true)
else
diff --git a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb
index a83b368b7f..842f2fc8df 100644
--- a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
class NumberToHumanSizeConverter < NumberConverter #:nodoc:
@@ -7,10 +9,6 @@ module ActiveSupport
self.validate_float = true
def convert
- if opts.key?(:prefix)
- ActiveSupport::Deprecation.warn('The :prefix option of `number_to_human_size` is deprecated and will be removed in Rails 5.1 with no replacement.')
- end
-
@number = Float(number)
# for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
@@ -21,24 +19,24 @@ module ActiveSupport
if smaller_than_base?
number_to_format = number.to_i.to_s
else
- human_size = number / (base ** exponent)
+ human_size = number / (base**exponent)
number_to_format = NumberToRoundedConverter.convert(human_size, options)
end
- conversion_format.gsub('%n'.freeze, number_to_format).gsub('%u'.freeze, unit)
+ conversion_format.gsub("%n".freeze, number_to_format).gsub("%u".freeze, unit)
end
private
def conversion_format
- translate_number_value_with_default('human.storage_units.format', :locale => options[:locale], :raise => true)
+ translate_number_value_with_default("human.storage_units.format", locale: options[:locale], raise: true)
end
def unit
- translate_number_value_with_default(storage_unit_key, :locale => options[:locale], :count => number.to_i, :raise => true)
+ translate_number_value_with_default(storage_unit_key, locale: options[:locale], count: number.to_i, raise: true)
end
def storage_unit_key
- key_end = smaller_than_base? ? 'byte' : STORAGE_UNITS[exponent]
+ key_end = smaller_than_base? ? "byte" : STORAGE_UNITS[exponent]
"human.storage_units.units.#{key_end}"
end
@@ -54,9 +52,8 @@ module ActiveSupport
end
def base
- opts[:prefix] == :si ? 1000 : 1024
+ 1024
end
end
end
end
-
diff --git a/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb b/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb
index 4c04d40c19..4dcdad2e2c 100644
--- a/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
class NumberToPercentageConverter < NumberConverter # :nodoc:
@@ -5,7 +7,7 @@ module ActiveSupport
def convert
rounded_number = NumberToRoundedConverter.convert(number, options)
- options[:format].gsub('%n'.freeze, rounded_number)
+ options[:format].gsub("%n".freeze, rounded_number)
end
end
end
diff --git a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb
index dee74fa7a6..96410f4995 100644
--- a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb
@@ -1,8 +1,10 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
class NumberToPhoneConverter < NumberConverter #:nodoc:
def convert
- str = country_code(opts[:country_code])
+ str = country_code(opts[:country_code]).dup
str << convert_to_phone_number(number.to_s.strip)
str << phone_ext(opts[:extension])
end
@@ -51,8 +53,6 @@ module ActiveSupport
def regexp_pattern(default_pattern)
opts.fetch :pattern, default_pattern
end
-
end
end
end
-
diff --git a/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb b/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb
index 9fb7dfb779..eb528a0583 100644
--- a/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module NumberHelper
class NumberToRoundedConverter < NumberConverter # :nodoc:
@@ -5,40 +7,28 @@ module ActiveSupport
self.validate_float = true
def convert
- precision = options.delete :precision
+ helper = RoundingHelper.new(options)
+ rounded_number = helper.round(number)
- if precision
- case number
- when Float, String
- @number = BigDecimal(number.to_s)
- when Rational
- @number = BigDecimal(number, digit_count(number.to_i) + precision)
- else
- @number = number.to_d
- end
-
- if options.delete(:significant) && precision > 0
- digits, rounded_number = digits_and_rounded_number(precision)
+ if precision = options[:precision]
+ if options[:significant] && precision > 0
+ digits = helper.digit_count(rounded_number)
precision -= digits
precision = 0 if precision < 0 # don't let it be negative
- else
- rounded_number = number.round(precision)
- rounded_number = rounded_number.to_i if precision == 0 && rounded_number.finite?
- rounded_number = rounded_number.abs if rounded_number.zero? # prevent showing negative zeros
end
formatted_string =
if BigDecimal === rounded_number && rounded_number.finite?
- s = rounded_number.to_s('F')
- s << '0'.freeze * precision
- a, b = s.split('.'.freeze, 2)
- a << '.'.freeze
+ s = rounded_number.to_s("F")
+ s << "0".freeze * precision
+ a, b = s.split(".".freeze, 2)
+ a << ".".freeze
a << b[0, precision]
else
"%00.#{precision}f" % rounded_number
end
else
- formatted_string = number
+ formatted_string = rounded_number
end
delimited_number = NumberToDelimitedConverter.convert(formatted_string, options)
@@ -47,26 +37,6 @@ module ActiveSupport
private
- def digits_and_rounded_number(precision)
- if zero?
- [1, 0]
- else
- digits = digit_count(number)
- multiplier = 10 ** (digits - precision)
- rounded_number = calculate_rounded_number(multiplier)
- digits = digit_count(rounded_number) # After rounding, the number of digits may have changed
- [digits, rounded_number]
- end
- end
-
- def calculate_rounded_number(multiplier)
- (number / BigDecimal.new(multiplier.to_f.to_s)).round * multiplier
- end
-
- def digit_count(number)
- number.zero? ? 1 : (Math.log10(absolute_number(number)) + 1).floor
- end
-
def strip_insignificant_zeros
options[:strip_insignificant_zeros]
end
@@ -74,19 +44,11 @@ module ActiveSupport
def format_number(number)
if strip_insignificant_zeros
escaped_separator = Regexp.escape(options[:separator])
- number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
+ number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "")
else
number
end
end
-
- def absolute_number(number)
- number.respond_to?(:abs) ? number.abs : number.to_d.abs
- end
-
- def zero?
- number.respond_to?(:zero?) ? number.zero? : number.to_d.zero?
- end
end
end
end
diff --git a/activesupport/lib/active_support/number_helper/rounding_helper.rb b/activesupport/lib/active_support/number_helper/rounding_helper.rb
new file mode 100644
index 0000000000..2ad8d49c4e
--- /dev/null
+++ b/activesupport/lib/active_support/number_helper/rounding_helper.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module ActiveSupport
+ module NumberHelper
+ class RoundingHelper # :nodoc:
+ attr_reader :options
+
+ def initialize(options)
+ @options = options
+ end
+
+ def round(number)
+ return number unless precision
+ number = convert_to_decimal(number)
+ if significant && precision > 0
+ round_significant(number)
+ else
+ round_without_significant(number)
+ end
+ end
+
+ def digit_count(number)
+ return 1 if number.zero?
+ (Math.log10(absolute_number(number)) + 1).floor
+ end
+
+ private
+ def round_without_significant(number)
+ number = number.round(precision)
+ number = number.to_i if precision == 0 && number.finite?
+ number = number.abs if number.zero? # prevent showing negative zeros
+ number
+ end
+
+ def round_significant(number)
+ return 0 if number.zero?
+ digits = digit_count(number)
+ multiplier = 10**(digits - precision)
+ (number / BigDecimal(multiplier.to_f.to_s)).round * multiplier
+ end
+
+ def convert_to_decimal(number)
+ case number
+ when Float, String
+ BigDecimal(number.to_s)
+ when Rational
+ BigDecimal(number, digit_count(number.to_i) + precision)
+ else
+ number.to_d
+ end
+ end
+
+ def precision
+ options[:precision]
+ end
+
+ def significant
+ options[:significant]
+ end
+
+ def absolute_number(number)
+ number.respond_to?(:abs) ? number.abs : number.to_d.abs
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/option_merger.rb b/activesupport/lib/active_support/option_merger.rb
index dea84e437f..ab9ca727f6 100644
--- a/activesupport/lib/active_support/option_merger.rb
+++ b/activesupport/lib/active_support/option_merger.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/hash/deep_merge'
+# frozen_string_literal: true
+
+require "active_support/core_ext/hash/deep_merge"
module ActiveSupport
class OptionMerger #:nodoc:
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index b1658f0f27..5758513021 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -1,7 +1,9 @@
-require 'yaml'
+# frozen_string_literal: true
+
+require "yaml"
YAML.add_builtin_type("omap") do |type, val|
- ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
+ ActiveSupport::OrderedHash[val.map { |v| v.to_a.first }]
end
module ActiveSupport
@@ -25,7 +27,7 @@ module ActiveSupport
end
def encode_with(coder)
- coder.represent_seq '!omap', map { |k,v| { k => v } }
+ coder.represent_seq "!omap", map { |k, v| { k => v } }
end
def select(*args, &block)
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index 53a55bd986..c4e419f546 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -1,3 +1,7 @@
+# frozen_string_literal: true
+
+require "active_support/core_ext/object/blank"
+
module ActiveSupport
# Usually key value pairs are handled something like this:
#
@@ -20,7 +24,7 @@ module ActiveSupport
# To raise an exception when the value is blank, append a
# bang to the key name, like:
#
- # h.dog! # => raises KeyError: key not found: :dog
+ # h.dog! # => raises KeyError: :dog is blank
#
class OrderedOptions < Hash
alias_method :_get, :[] # preserve the original #[] method
@@ -36,13 +40,13 @@ module ActiveSupport
def method_missing(name, *args)
name_string = name.to_s
- if name_string.chomp!('=')
+ if name_string.chomp!("=")
self[name_string] = args.first
else
- bangs = name_string.chomp!('!')
+ bangs = name_string.chomp!("!")
if bangs
- fetch(name_string.to_sym).presence || raise(KeyError.new("#{name_string} is blank."))
+ self[name_string].presence || raise(KeyError.new(":#{name_string} is blank"))
else
self[name_string]
end
@@ -66,9 +70,9 @@ module ActiveSupport
def initialize(parent = nil)
if parent.kind_of?(OrderedOptions)
# use the faster _get when dealing with OrderedOptions
- super() { |h,k| parent._get(k) }
+ super() { |h, k| parent._get(k) }
elsif parent
- super() { |h,k| parent[k] }
+ super() { |h, k| parent[k] }
else
super()
end
diff --git a/activesupport/lib/active_support/per_thread_registry.rb b/activesupport/lib/active_support/per_thread_registry.rb
index 88e2b12cc7..eb92fb4371 100644
--- a/activesupport/lib/active_support/per_thread_registry.rb
+++ b/activesupport/lib/active_support/per_thread_registry.rb
@@ -1,7 +1,9 @@
-require 'active_support/core_ext/module/delegation'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/delegation"
module ActiveSupport
- # NOTE: This approach has been deprecated for end-user code in favor of thread_mattr_accessor and friends.
+ # NOTE: This approach has been deprecated for end-user code in favor of {thread_mattr_accessor}[rdoc-ref:Module#thread_mattr_accessor] and friends.
# Please use that approach instead.
#
# This module is used to encapsulate access to thread local variables.
@@ -38,15 +40,15 @@ module ActiveSupport
# If the class has an initializer, it must accept no arguments.
module PerThreadRegistry
def self.extended(object)
- object.instance_variable_set '@per_thread_registry_key', object.name.freeze
+ object.instance_variable_set "@per_thread_registry_key", object.name.freeze
end
def instance
Thread.current[@per_thread_registry_key] ||= new
end
- protected
- def method_missing(name, *args, &block) # :nodoc:
+ private
+ def method_missing(name, *args, &block)
# Caches the method definition as a singleton method of the receiver.
#
# By letting #delegate handle it, we avoid an enclosure that'll capture args.
diff --git a/activesupport/lib/active_support/proxy_object.rb b/activesupport/lib/active_support/proxy_object.rb
index 20a0fd8e62..0965fcd2d9 100644
--- a/activesupport/lib/active_support/proxy_object.rb
+++ b/activesupport/lib/active_support/proxy_object.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# A class with no predefined methods that behaves similarly to Builder's
# BlankSlate. Used for proxy classes.
diff --git a/activesupport/lib/active_support/rails.rb b/activesupport/lib/active_support/rails.rb
index c8e3a4bf53..5c34a0abb3 100644
--- a/activesupport/lib/active_support/rails.rb
+++ b/activesupport/lib/active_support/rails.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
# This is private interface.
#
# Rails components cherry pick from Active Support as needed, but there are a
@@ -9,19 +11,25 @@
# Rails and can change anytime.
# Defines Object#blank? and Object#present?.
-require 'active_support/core_ext/object/blank'
+require "active_support/core_ext/object/blank"
# Rails own autoload, eager_load, etc.
-require 'active_support/dependencies/autoload'
+require "active_support/dependencies/autoload"
# Support for ClassMethods and the included macro.
-require 'active_support/concern'
+require "active_support/concern"
# Defines Class#class_attribute.
-require 'active_support/core_ext/class/attribute'
+require "active_support/core_ext/class/attribute"
# Defines Module#delegate.
-require 'active_support/core_ext/module/delegation'
+require "active_support/core_ext/module/delegation"
# Defines ActiveSupport::Deprecation.
-require 'active_support/deprecation'
+require "active_support/deprecation"
+
+# Defines Regexp#match?.
+#
+# This should be removed when Rails needs Ruby 2.4 or later, and the require
+# added where other Regexp extensions are being used (easy to grep).
+require "active_support/core_ext/regexp"
diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb
index 845788b669..6b8fa676a9 100644
--- a/activesupport/lib/active_support/railtie.rb
+++ b/activesupport/lib/active_support/railtie.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
require "active_support"
require "active_support/i18n_railtie"
@@ -7,6 +9,21 @@ module ActiveSupport
config.eager_load_namespaces << ActiveSupport
+ initializer "active_support.set_authenticated_message_encryption" do |app|
+ config.after_initialize do
+ unless app.config.active_support.use_authenticated_message_encryption.nil?
+ ActiveSupport::MessageEncryptor.use_authenticated_message_encryption =
+ app.config.active_support.use_authenticated_message_encryption
+ end
+ end
+ end
+
+ initializer "active_support.reset_all_current_attributes_instances" do |app|
+ app.reloader.before_class_unload { ActiveSupport::CurrentAttributes.clear_all }
+ app.executor.to_run { ActiveSupport::CurrentAttributes.reset_all }
+ app.executor.to_complete { ActiveSupport::CurrentAttributes.reset_all }
+ end
+
initializer "active_support.deprecation_behavior" do |app|
if deprecation = app.config.active_support.deprecation
ActiveSupport::Deprecation.behavior = deprecation
@@ -21,31 +38,42 @@ module ActiveSupport
rescue TZInfo::DataSourceNotFound => e
raise e.exception "tzinfo-data is not present. Please add gem 'tzinfo-data' to your Gemfile and run bundle install"
end
- require 'active_support/core_ext/time/zones'
- zone_default = Time.find_zone!(app.config.time_zone)
-
- unless zone_default
- raise 'Value assigned to config.time_zone not recognized. ' \
- 'Run "rake time:zones:all" for a time zone names list.'
- end
-
- Time.zone_default = zone_default
+ require "active_support/core_ext/time/zones"
+ Time.zone_default = Time.find_zone!(app.config.time_zone)
end
# Sets the default week start
# If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised.
initializer "active_support.initialize_beginning_of_week" do |app|
- require 'active_support/core_ext/date/calculations'
+ require "active_support/core_ext/date/calculations"
beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week)
Date.beginning_of_week_default = beginning_of_week_default
end
+ initializer "active_support.require_master_key" do |app|
+ if app.config.respond_to?(:require_master_key) && app.config.require_master_key
+ begin
+ app.credentials.key
+ rescue ActiveSupport::EncryptedFile::MissingKeyError => error
+ $stderr.puts error.message
+ exit 1
+ end
+ end
+ end
+
initializer "active_support.set_configs" do |app|
app.config.active_support.each do |k, v|
k = "#{k}="
ActiveSupport.send(k, v) if ActiveSupport.respond_to? k
end
end
+
+ initializer "active_support.set_hash_digest_class" do |app|
+ if app.config.active_support.hash_digest_class
+ ActiveSupport::Digest.hash_digest_class =
+ app.config.active_support.hash_digest_class
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/reloader.rb b/activesupport/lib/active_support/reloader.rb
index 5623bdd349..b26d9c3665 100644
--- a/activesupport/lib/active_support/reloader.rb
+++ b/activesupport/lib/active_support/reloader.rb
@@ -1,4 +1,6 @@
-require 'active_support/execution_wrapper'
+# frozen_string_literal: true
+
+require "active_support/execution_wrapper"
module ActiveSupport
#--
@@ -26,14 +28,17 @@ module ActiveSupport
define_callbacks :class_unload
+ # Registers a callback that will run once at application startup and every time the code is reloaded.
def self.to_prepare(*args, &block)
set_callback(:prepare, *args, &block)
end
+ # Registers a callback that will run immediately before the classes are unloaded.
def self.before_class_unload(*args, &block)
set_callback(:class_unload, *args, &block)
end
+ # Registers a callback that will run immediately after the classes are unloaded.
def self.after_class_unload(*args, &block)
set_callback(:class_unload, :after, *args, &block)
end
@@ -69,11 +74,8 @@ module ActiveSupport
end
end
- class_attribute :executor
- class_attribute :check
-
- self.executor = Executor
- self.check = lambda { false }
+ class_attribute :executor, default: Executor
+ class_attribute :check, default: lambda { false }
def self.check! # :nodoc:
@should_reload ||= check.call
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index 73bc52b56f..e0fa29cacb 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -1,7 +1,8 @@
-require 'active_support/concern'
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "active_support/concern"
+require "active_support/core_ext/class/attribute"
+require "active_support/core_ext/string/inflections"
module ActiveSupport
# Rescuable module adds support for easier exception handling.
@@ -9,8 +10,7 @@ module ActiveSupport
extend Concern
included do
- class_attribute :rescue_handlers
- self.rescue_handlers = []
+ class_attribute :rescue_handlers, default: []
end
module ClassMethods
@@ -37,7 +37,7 @@ module ActiveSupport
# render xml: exception, status: 500
# end
#
- # protected
+ # private
# def deny_access
# ...
# end
@@ -48,14 +48,12 @@ module ActiveSupport
# end
#
# Exceptions raised inside exception handlers are not propagated up.
- def rescue_from(*klasses, &block)
- options = klasses.extract_options!
-
- unless options.has_key?(:with)
+ def rescue_from(*klasses, with: nil, &block)
+ unless with
if block_given?
- options[:with] = block
+ with = block
else
- raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
+ raise ArgumentError, "Need a handler. Pass the with: keyword argument or provide a block."
end
end
@@ -65,65 +63,112 @@ module ActiveSupport
elsif klass.is_a?(String)
klass
else
- raise ArgumentError, "#{klass} is neither an Exception nor a String"
+ raise ArgumentError, "#{klass.inspect} must be an Exception class or a String referencing an Exception class"
end
# Put the new handler at the end because the list is read in reverse.
- self.rescue_handlers += [[key, options[:with]]]
+ self.rescue_handlers += [[key, with]]
end
end
- end
- # Tries to rescue the exception by looking up and calling a registered handler.
- def rescue_with_handler(exception)
- if handler = handler_for_rescue(exception)
- handler.arity != 0 ? handler.call(exception) : handler.call
- true # don't rely on the return value of the handler
- end
- end
+ # Matches an exception to a handler based on the exception class.
+ #
+ # If no handler matches the exception, check for a handler matching the
+ # (optional) exception.cause. If no handler matches the exception or its
+ # cause, this returns +nil+, so you can deal with unhandled exceptions.
+ # Be sure to re-raise unhandled exceptions if this is what you expect.
+ #
+ # begin
+ # …
+ # rescue => exception
+ # rescue_with_handler(exception) || raise
+ # end
+ #
+ # Returns the exception if it was handled and +nil+ if it was not.
+ def rescue_with_handler(exception, object: self, visited_exceptions: [])
+ visited_exceptions << exception
- def handler_for_rescue(exception)
- # We go from right to left because pairs are pushed onto rescue_handlers
- # as rescue_from declarations are found.
- _, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
- # The purpose of allowing strings in rescue_from is to support the
- # declaration of handler associations for exception classes whose
- # definition is yet unknown.
- #
- # Since this loop needs the constants it would be inconsistent to
- # assume they should exist at this point. An early raised exception
- # could trigger some other handler and the array could include
- # precisely a string whose corresponding constant has not yet been
- # seen. This is why we are tolerant to unknown constants.
- #
- # Note that this tolerance only matters if the exception was given as
- # a string, otherwise a NameError will be raised by the interpreter
- # itself when rescue_from CONSTANT is executed.
- klass = self.class.const_get(klass_name) rescue nil
- klass ||= (klass_name.constantize rescue nil)
- klass === exception if klass
+ if handler = handler_for_rescue(exception, object: object)
+ handler.call exception
+ exception
+ elsif exception
+ if visited_exceptions.include?(exception.cause)
+ nil
+ else
+ rescue_with_handler(exception.cause, object: object, visited_exceptions: visited_exceptions)
+ end
+ end
end
- case rescuer
- when Symbol
- method(rescuer)
- when Proc
- if rescuer.arity == 0
- Proc.new { instance_exec(&rescuer) }
- else
- Proc.new { |_exception| instance_exec(_exception, &rescuer) }
+ def handler_for_rescue(exception, object: self) #:nodoc:
+ case rescuer = find_rescue_handler(exception)
+ when Symbol
+ method = object.method(rescuer)
+ if method.arity == 0
+ -> e { method.call }
+ else
+ method
+ end
+ when Proc
+ if rescuer.arity == 0
+ -> e { object.instance_exec(&rescuer) }
+ else
+ -> e { object.instance_exec(e, &rescuer) }
+ end
end
end
+
+ private
+ def find_rescue_handler(exception)
+ if exception
+ # Handlers are in order of declaration but the most recently declared
+ # is the highest priority match, so we search for matching handlers
+ # in reverse.
+ _, handler = rescue_handlers.reverse_each.detect do |class_or_name, _|
+ if klass = constantize_rescue_handler_class(class_or_name)
+ klass === exception
+ end
+ end
+
+ handler
+ end
+ end
+
+ def constantize_rescue_handler_class(class_or_name)
+ case class_or_name
+ when String, Symbol
+ begin
+ # Try a lexical lookup first since we support
+ #
+ # class Super
+ # rescue_from 'Error', with: …
+ # end
+ #
+ # class Sub
+ # class Error < StandardError; end
+ # end
+ #
+ # so an Error raised in Sub will hit the 'Error' handler.
+ const_get class_or_name
+ rescue NameError
+ class_or_name.safe_constantize
+ end
+ else
+ class_or_name
+ end
+ end
end
- def index_of_handler_for_rescue(exception)
- handlers = self.class.rescue_handlers.reverse_each.with_index
- _, index = handlers.detect do |(klass_name, _), _|
- klass = self.class.const_get(klass_name) rescue nil
- klass ||= (klass_name.constantize rescue nil)
- klass === exception if klass
- end
- index
+ # Delegates to the class method, but uses the instance as the subject for
+ # rescue_from handlers (method calls, instance_exec blocks).
+ def rescue_with_handler(exception)
+ self.class.rescue_with_handler exception, object: self
+ end
+
+ # Internal handler lookup. Delegates to class method. Some libraries call
+ # this directly, so keeping it around for compatibility.
+ def handler_for_rescue(exception) #:nodoc:
+ self.class.handler_for_rescue exception, object: self
end
end
end
diff --git a/activesupport/lib/active_support/security_utils.rb b/activesupport/lib/active_support/security_utils.rb
index 9be8613ada..20b6b9cd3f 100644
--- a/activesupport/lib/active_support/security_utils.rb
+++ b/activesupport/lib/active_support/security_utils.rb
@@ -1,15 +1,15 @@
-require 'digest'
+# frozen_string_literal: true
+
+require "digest/sha2"
module ActiveSupport
module SecurityUtils
- # Constant time string comparison.
+ # Constant time string comparison, for fixed length strings.
#
# The values compared should be of fixed length, such as strings
- # that have already been processed by HMAC. This should not be used
- # on variable length plaintext strings because it could leak length info
- # via timing attacks.
- def secure_compare(a, b)
- return false unless a.bytesize == b.bytesize
+ # that have already been processed by HMAC. Raises in case of length mismatch.
+ def fixed_length_secure_compare(a, b)
+ raise ArgumentError, "string length mismatch." unless a.bytesize == b.bytesize
l = a.unpack "C#{a.bytesize}"
@@ -17,11 +17,15 @@ module ActiveSupport
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
- module_function :secure_compare
+ module_function :fixed_length_secure_compare
- def variable_size_secure_compare(a, b) # :nodoc:
- secure_compare(::Digest::SHA256.hexdigest(a), ::Digest::SHA256.hexdigest(b))
+ # Constant time string comparison, for variable length strings.
+ #
+ # The values are first processed by SHA256, so that we don't leak length info
+ # via timing attacks.
+ def secure_compare(a, b)
+ fixed_length_secure_compare(::Digest::SHA256.hexdigest(a), ::Digest::SHA256.hexdigest(b)) && a == b
end
- module_function :variable_size_secure_compare
+ module_function :secure_compare
end
end
diff --git a/activesupport/lib/active_support/string_inquirer.rb b/activesupport/lib/active_support/string_inquirer.rb
index bc673150d0..a3af36720e 100644
--- a/activesupport/lib/active_support/string_inquirer.rb
+++ b/activesupport/lib/active_support/string_inquirer.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
# Wrapping a string in this class gives you a prettier way to test
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
@@ -8,15 +10,21 @@ module ActiveSupport
# you can call this:
#
# Rails.env.production?
+ #
+ # == Instantiating a new StringInquirer
+ #
+ # vehicle = ActiveSupport::StringInquirer.new('car')
+ # vehicle.car? # => true
+ # vehicle.bike? # => false
class StringInquirer < String
private
def respond_to_missing?(method_name, include_private = false)
- method_name[-1] == '?'
+ (method_name[-1] == "?") || super
end
def method_missing(method_name, *arguments)
- if method_name[-1] == '?'
+ if method_name[-1] == "?"
self == method_name[0..-2]
else
super
diff --git a/activesupport/lib/active_support/subscriber.rb b/activesupport/lib/active_support/subscriber.rb
index 1cd4b807ad..d6dd5474d0 100644
--- a/activesupport/lib/active_support/subscriber.rb
+++ b/activesupport/lib/active_support/subscriber.rb
@@ -1,4 +1,7 @@
-require 'active_support/per_thread_registry'
+# frozen_string_literal: true
+
+require "active_support/per_thread_registry"
+require "active_support/notifications"
module ActiveSupport
# ActiveSupport::Subscriber is an object set to consume
@@ -23,9 +26,8 @@ module ActiveSupport
# the +sql+ method.
class Subscriber
class << self
-
# Attach the subscriber to a namespace.
- def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
+ def attach_to(namespace, subscriber = new, notifier = ActiveSupport::Notifications)
@namespace = namespace
@subscriber = subscriber
@notifier = notifier
@@ -52,11 +54,15 @@ module ActiveSupport
@@subscribers ||= []
end
+ # TODO Change this to private once we've dropped Ruby 2.2 support.
+ # Workaround for Ruby 2.2 "private attribute?" warning.
protected
attr_reader :subscriber, :notifier, :namespace
- def add_event_subscriber(event)
+ private
+
+ def add_event_subscriber(event) # :doc:
return if %w{ start finish }.include?(event.to_s)
pattern = "#{event}.#{namespace}"
@@ -91,7 +97,7 @@ module ActiveSupport
event.end = finished
event.payload.merge!(payload)
- method = name.split('.'.freeze).first
+ method = name.split(".".freeze).first
send(method, event)
end
diff --git a/activesupport/lib/active_support/tagged_logging.rb b/activesupport/lib/active_support/tagged_logging.rb
index bcd7bf74c0..8561cba9f1 100644
--- a/activesupport/lib/active_support/tagged_logging.rb
+++ b/activesupport/lib/active_support/tagged_logging.rb
@@ -1,7 +1,9 @@
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/object/blank'
-require 'logger'
-require 'active_support/logger'
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/delegation"
+require "active_support/core_ext/object/blank"
+require "logger"
+require "active_support/logger"
module ActiveSupport
# Wraps any standard Logger object to provide tagging capabilities.
@@ -48,13 +50,12 @@ module ActiveSupport
Thread.current[thread_key] ||= []
end
- private
- def tags_text
- tags = current_tags
- if tags.any?
- tags.collect { |tag| "[#{tag}] " }.join
- end
+ def tags_text
+ tags = current_tags
+ if tags.any?
+ tags.collect { |tag| "[#{tag}] " }.join
end
+ end
end
def self.new(logger)
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index 1fc12d0bc1..d1f7e6ea09 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -1,15 +1,16 @@
-gem 'minitest' # make sure we get the gem, not stdlib
-require 'minitest'
-require 'active_support/testing/tagged_logging'
-require 'active_support/testing/setup_and_teardown'
-require 'active_support/testing/assertions'
-require 'active_support/testing/deprecation'
-require 'active_support/testing/declarative'
-require 'active_support/testing/isolation'
-require 'active_support/testing/constant_lookup'
-require 'active_support/testing/time_helpers'
-require 'active_support/testing/file_fixtures'
-require 'active_support/core_ext/kernel/reporting'
+# frozen_string_literal: true
+
+gem "minitest" # make sure we get the gem, not stdlib
+require "minitest"
+require "active_support/testing/tagged_logging"
+require "active_support/testing/setup_and_teardown"
+require "active_support/testing/assertions"
+require "active_support/testing/deprecation"
+require "active_support/testing/declarative"
+require "active_support/testing/isolation"
+require "active_support/testing/constant_lookup"
+require "active_support/testing/time_helpers"
+require "active_support/testing/file_fixtures"
module ActiveSupport
class TestCase < ::Minitest::Test
@@ -66,21 +67,6 @@ module ActiveSupport
alias :assert_not_respond_to :refute_respond_to
alias :assert_not_same :refute_same
-
- # Assertion that the block should not raise an exception.
- #
- # Passes if evaluated code in the yielded block raises no exception.
- #
- # assert_nothing_raised do
- # perform_service(param: 'no_exception')
- # end
- def assert_nothing_raised(*args)
- if args.present?
- ActiveSupport::Deprecation.warn(
- "Passing arguments to assert_nothing_raised " \
- "is deprecated and will be removed in Rails 5.1.")
- end
- yield
- end
+ ActiveSupport.run_load_hooks(:active_support_test_case, self)
end
end
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
index 29305e0082..6f69c48674 100644
--- a/activesupport/lib/active_support/testing/assertions.rb
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -1,8 +1,10 @@
-require 'active_support/core_ext/object/blank'
+# frozen_string_literal: true
module ActiveSupport
module Testing
module Assertions
+ UNTRACKED = Object.new # :nodoc:
+
# Asserts that an expression is not truthy. Passes if <tt>object</tt> is
# +nil+ or +false+. "Truthy" means "considered true in a conditional"
# like <tt>if foo</tt>.
@@ -19,6 +21,17 @@ module ActiveSupport
assert !object, message
end
+ # Assertion that the block should not raise an exception.
+ #
+ # Passes if evaluated code in the yielded block raises no exception.
+ #
+ # assert_nothing_raised do
+ # perform_service(param: 'no_exception')
+ # end
+ def assert_nothing_raised
+ yield
+ end
+
# Test numeric difference between the return value of an expression as a
# result of what is evaluated in the yielded block.
#
@@ -94,6 +107,94 @@ module ActiveSupport
def assert_no_difference(expression, message = nil, &block)
assert_difference expression, 0, message, &block
end
+
+ # Assertion that the result of evaluating an expression is changed before
+ # and after invoking the passed in block.
+ #
+ # assert_changes 'Status.all_good?' do
+ # post :create, params: { status: { ok: false } }
+ # end
+ #
+ # You can pass the block as a string to be evaluated in the context of
+ # the block. A lambda can be passed for the block as well.
+ #
+ # assert_changes -> { Status.all_good? } do
+ # post :create, params: { status: { ok: false } }
+ # end
+ #
+ # The assertion is useful to test side effects. The passed block can be
+ # anything that can be converted to string with #to_s.
+ #
+ # assert_changes :@object do
+ # @object = 42
+ # end
+ #
+ # The keyword arguments :from and :to can be given to specify the
+ # expected initial value and the expected value after the block was
+ # executed.
+ #
+ # assert_changes :@object, from: nil, to: :foo do
+ # @object = :foo
+ # end
+ #
+ # An error message can be specified.
+ #
+ # assert_changes -> { Status.all_good? }, 'Expected the status to be bad' do
+ # post :create, params: { status: { incident: true } }
+ # end
+ def assert_changes(expression, message = nil, from: UNTRACKED, to: UNTRACKED, &block)
+ exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) }
+
+ before = exp.call
+ retval = yield
+
+ unless from == UNTRACKED
+ error = "#{expression.inspect} isn't #{from.inspect}"
+ error = "#{message}.\n#{error}" if message
+ assert from === before, error
+ end
+
+ after = exp.call
+
+ error = "#{expression.inspect} didn't change"
+ error = "#{error}. It was already #{to}" if before == to
+ error = "#{message}.\n#{error}" if message
+ assert before != after, error
+
+ unless to == UNTRACKED
+ error = "#{expression.inspect} didn't change to #{to}"
+ error = "#{message}.\n#{error}" if message
+ assert to === after, error
+ end
+
+ retval
+ end
+
+ # Assertion that the result of evaluating an expression is not changed before
+ # and after invoking the passed in block.
+ #
+ # assert_no_changes 'Status.all_good?' do
+ # post :create, params: { status: { ok: true } }
+ # end
+ #
+ # An error message can be specified.
+ #
+ # assert_no_changes -> { Status.all_good? }, 'Expected the status to be good' do
+ # post :create, params: { status: { ok: false } }
+ # end
+ def assert_no_changes(expression, message = nil, &block)
+ exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) }
+
+ before = exp.call
+ retval = yield
+ after = exp.call
+
+ error = "#{expression.inspect} did change to #{after}"
+ error = "#{message}.\n#{error}" if message
+ assert before == after, error
+
+ retval
+ end
end
end
end
diff --git a/activesupport/lib/active_support/testing/autorun.rb b/activesupport/lib/active_support/testing/autorun.rb
index 84c6b89340..889b41659a 100644
--- a/activesupport/lib/active_support/testing/autorun.rb
+++ b/activesupport/lib/active_support/testing/autorun.rb
@@ -1,12 +1,7 @@
-gem 'minitest'
+# frozen_string_literal: true
-require 'minitest'
+gem "minitest"
-if Minitest.respond_to?(:run_with_rails_extension)
- unless Minitest.run_with_rails_extension
- Minitest.run_with_autorun = true
- Minitest.autorun
- end
-else
- Minitest.autorun
-end
+require "minitest"
+
+Minitest.autorun
diff --git a/activesupport/lib/active_support/testing/constant_lookup.rb b/activesupport/lib/active_support/testing/constant_lookup.rb
index 07d477c0db..51167e9237 100644
--- a/activesupport/lib/active_support/testing/constant_lookup.rb
+++ b/activesupport/lib/active_support/testing/constant_lookup.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
require "active_support/concern"
require "active_support/inflector"
@@ -44,7 +46,6 @@ module ActiveSupport
end
end
end
-
end
end
end
diff --git a/activesupport/lib/active_support/testing/declarative.rb b/activesupport/lib/active_support/testing/declarative.rb
index 0bf3643a56..7c3403684d 100644
--- a/activesupport/lib/active_support/testing/declarative.rb
+++ b/activesupport/lib/active_support/testing/declarative.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Testing
module Declarative
@@ -9,7 +11,7 @@ module ActiveSupport
# ...
# end
def test(name, &block)
- test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
+ test_name = "test_#{name.gsub(/\s+/, '_')}".to_sym
defined = method_defined? test_name
raise "#{test_name} is already defined in #{self}" if defined
if block_given?
diff --git a/activesupport/lib/active_support/testing/deprecation.rb b/activesupport/lib/active_support/testing/deprecation.rb
index 5dfa14eeba..f655435729 100644
--- a/activesupport/lib/active_support/testing/deprecation.rb
+++ b/activesupport/lib/active_support/testing/deprecation.rb
@@ -1,4 +1,7 @@
-require 'active_support/deprecation'
+# frozen_string_literal: true
+
+require "active_support/deprecation"
+require "active_support/core_ext/regexp"
module ActiveSupport
module Testing
@@ -8,7 +11,7 @@ module ActiveSupport
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
if match
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
- assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
+ assert warnings.any? { |w| match.match?(w) }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
end
result
end
diff --git a/activesupport/lib/active_support/testing/file_fixtures.rb b/activesupport/lib/active_support/testing/file_fixtures.rb
index affb84cda5..ad923d1aab 100644
--- a/activesupport/lib/active_support/testing/file_fixtures.rb
+++ b/activesupport/lib/active_support/testing/file_fixtures.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Testing
# Adds simple access to sample files called file fixtures.
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index edf8b30a0a..fa9bebb181 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Testing
module Isolation
- require 'thread'
+ require "thread"
def self.included(klass) #:nodoc:
klass.class_eval do
@@ -13,17 +15,6 @@ module ActiveSupport
!ENV["NO_FORK"] && Process.respond_to?(:fork)
end
- @@class_setup_mutex = Mutex.new
-
- def _run_class_setup # class setup method should only happen in parent
- @@class_setup_mutex.synchronize do
- unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST']
- self.class.setup if self.class.respond_to?(:setup)
- @@ran_class_setup = true
- end
- end
- end
-
def run
serialized = run_in_isolation do
super
@@ -54,7 +45,7 @@ module ActiveSupport
end
}
end
- result = Marshal.dump(self.dup)
+ result = Marshal.dump(dup)
end
write.puts [result].pack("m")
@@ -64,7 +55,7 @@ module ActiveSupport
write.close
result = read.read
Process.wait2(pid)
- return result.unpack("m")[0]
+ result.unpack("m")[0]
end
end
@@ -79,23 +70,25 @@ module ActiveSupport
if ENV["ISOLATION_TEST"]
yield
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
- file.puts [Marshal.dump(self.dup)].pack("m")
+ file.puts [Marshal.dump(dup)].pack("m")
end
exit!
else
Tempfile.open("isolation") do |tmpfile|
env = {
- 'ISOLATION_TEST' => self.class.name,
- 'ISOLATION_OUTPUT' => tmpfile.path
+ "ISOLATION_TEST" => self.class.name,
+ "ISOLATION_OUTPUT" => tmpfile.path
}
- load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
- orig_args = ORIG_ARGV.join(" ")
- test_opts = "-n#{self.class.name}##{self.name}"
- command = "#{Gem.ruby} #{load_paths} #{$0} '#{orig_args}' #{test_opts}"
+ test_opts = "-n#{self.class.name}##{name}"
+
+ load_path_args = []
+ $-I.each do |p|
+ load_path_args << "-I"
+ load_path_args << File.expand_path(p)
+ end
- # IO.popen lets us pass env in a cross-platform way
- child = IO.popen(env, command)
+ child = IO.popen([env, Gem.ruby, *load_path_args, $0, *ORIG_ARGV, test_opts])
begin
Process.wait(child.pid)
diff --git a/activesupport/lib/active_support/testing/method_call_assertions.rb b/activesupport/lib/active_support/testing/method_call_assertions.rb
index fccaa54f40..c6358002ea 100644
--- a/activesupport/lib/active_support/testing/method_call_assertions.rb
+++ b/activesupport/lib/active_support/testing/method_call_assertions.rb
@@ -1,4 +1,6 @@
-require 'minitest/mock'
+# frozen_string_literal: true
+
+require "minitest/mock"
module ActiveSupport
module Testing
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
index 33f2b8dc9b..1dbf3c5da0 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -1,5 +1,7 @@
-require 'active_support/concern'
-require 'active_support/callbacks'
+# frozen_string_literal: true
+
+require "active_support/concern"
+require "active_support/callbacks"
module ActiveSupport
module Testing
diff --git a/activesupport/lib/active_support/testing/stream.rb b/activesupport/lib/active_support/testing/stream.rb
index 895192ad05..d070a1793d 100644
--- a/activesupport/lib/active_support/testing/stream.rb
+++ b/activesupport/lib/active_support/testing/stream.rb
@@ -1,42 +1,44 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Testing
module Stream #:nodoc:
private
- def silence_stream(stream)
- old_stream = stream.dup
- stream.reopen(IO::NULL)
- stream.sync = true
- yield
- ensure
- stream.reopen(old_stream)
- old_stream.close
- end
+ def silence_stream(stream)
+ old_stream = stream.dup
+ stream.reopen(IO::NULL)
+ stream.sync = true
+ yield
+ ensure
+ stream.reopen(old_stream)
+ old_stream.close
+ end
- def quietly
- silence_stream(STDOUT) do
- silence_stream(STDERR) do
- yield
+ def quietly
+ silence_stream(STDOUT) do
+ silence_stream(STDERR) do
+ yield
+ end
end
end
- end
- def capture(stream)
- stream = stream.to_s
- captured_stream = Tempfile.new(stream)
- stream_io = eval("$#{stream}")
- origin_stream = stream_io.dup
- stream_io.reopen(captured_stream)
+ def capture(stream)
+ stream = stream.to_s
+ captured_stream = Tempfile.new(stream)
+ stream_io = eval("$#{stream}")
+ origin_stream = stream_io.dup
+ stream_io.reopen(captured_stream)
- yield
+ yield
- stream_io.rewind
- return captured_stream.read
- ensure
- captured_stream.close
- captured_stream.unlink
- stream_io.reopen(origin_stream)
- end
+ stream_io.rewind
+ return captured_stream.read
+ ensure
+ captured_stream.close
+ captured_stream.unlink
+ stream_io.reopen(origin_stream)
+ end
end
end
end
diff --git a/activesupport/lib/active_support/testing/tagged_logging.rb b/activesupport/lib/active_support/testing/tagged_logging.rb
index 843ce4a867..9ca50c7918 100644
--- a/activesupport/lib/active_support/testing/tagged_logging.rb
+++ b/activesupport/lib/active_support/testing/tagged_logging.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ActiveSupport
module Testing
# Logs a "PostsControllerTest: test name" heading before each test to
@@ -8,7 +10,7 @@ module ActiveSupport
def before_setup
if tagged_logger && tagged_logger.info?
heading = "#{self.class}: #{name}"
- divider = '-' * heading.size
+ divider = "-" * heading.size
tagged_logger.info divider
tagged_logger.info heading
tagged_logger.info divider
diff --git a/activesupport/lib/active_support/testing/time_helpers.rb b/activesupport/lib/active_support/testing/time_helpers.rb
index fca0947c5b..998a51a34c 100644
--- a/activesupport/lib/active_support/testing/time_helpers.rb
+++ b/activesupport/lib/active_support/testing/time_helpers.rb
@@ -1,39 +1,50 @@
+# frozen_string_literal: true
+
+require "active_support/core_ext/module/redefine_method"
+require "active_support/core_ext/string/strip" # for strip_heredoc
+require "active_support/core_ext/time/calculations"
+require "concurrent/map"
+
module ActiveSupport
module Testing
class SimpleStubs # :nodoc:
Stub = Struct.new(:object, :method_name, :original_method)
def initialize
- @stubs = {}
+ @stubs = Concurrent::Map.new { |h, k| h[k] = {} }
end
- def stub_object(object, method_name, return_value)
- key = [object.object_id, method_name]
-
- if stub = @stubs[key]
+ def stub_object(object, method_name, &block)
+ if stub = stubbing(object, method_name)
unstub_object(stub)
end
new_name = "__simple_stub__#{method_name}"
- @stubs[key] = Stub.new(object, method_name, new_name)
+ @stubs[object.object_id][method_name] = Stub.new(object, method_name, new_name)
object.singleton_class.send :alias_method, new_name, method_name
- object.define_singleton_method(method_name) { return_value }
+ object.define_singleton_method(method_name, &block)
end
def unstub_all!
- @stubs.each_value do |stub|
- unstub_object(stub)
+ @stubs.each_value do |object_stubs|
+ object_stubs.each_value do |stub|
+ unstub_object(stub)
+ end
end
- @stubs = {}
+ @stubs.clear
+ end
+
+ def stubbing(object, method_name)
+ @stubs[object.object_id][method_name]
end
private
def unstub_object(stub)
singleton_class = stub.object.singleton_class
- singleton_class.send :undef_method, stub.method_name
+ singleton_class.send :silence_redefinition_of_method, stub.method_name
singleton_class.send :alias_method, stub.method_name, stub.original_method
singleton_class.send :undef_method, stub.original_method
end
@@ -41,8 +52,14 @@ module ActiveSupport
# Contains helpers that help you test passage of time.
module TimeHelpers
+ def after_teardown
+ travel_back
+ super
+ end
+
# Changes current time to the time in the future or in the past by a given time difference by
- # stubbing +Time.now+, +Date.today+, and +DateTime.now+.
+ # stubbing +Time.now+, +Date.today+, and +DateTime.now+. The stubs are automatically removed
+ # at the end of the test.
#
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
# travel 1.day
@@ -64,9 +81,10 @@ module ActiveSupport
# Changes current time to the given time by stubbing +Time.now+,
# +Date.today+, and +DateTime.now+ to return the time or date passed into this method.
+ # The stubs are automatically removed at the end of the test.
#
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
- # travel_to Time.new(2004, 11, 24, 01, 04, 44)
+ # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44)
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
# Date.current # => Wed, 24 Nov 2004
# DateTime.current # => Wed, 24 Nov 2004 01:04:44 -0500
@@ -88,20 +106,48 @@ module ActiveSupport
# state at the end of the block:
#
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
- # travel_to Time.new(2004, 11, 24, 01, 04, 44) do
+ # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44) do
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
# end
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
def travel_to(date_or_time)
+ if block_given? && simple_stubs.stubbing(Time, :now)
+ travel_to_nested_block_call = <<-MSG.strip_heredoc
+
+ Calling `travel_to` with a block, when we have previously already made a call to `travel_to`, can lead to confusing time stubbing.
+
+ Instead of:
+
+ travel_to 2.days.from_now do
+ # 2 days from today
+ travel_to 3.days.from_now do
+ # 5 days from today
+ end
+ end
+
+ preferred way to achieve above is:
+
+ travel 2.days do
+ # 2 days from today
+ end
+
+ travel 5.days do
+ # 5 days from today
+ end
+
+ MSG
+ raise travel_to_nested_block_call
+ end
+
if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime)
now = date_or_time.midnight.to_time
else
now = date_or_time.to_time.change(usec: 0)
end
- simple_stubs.stub_object(Time, :now, now)
- simple_stubs.stub_object(Date, :today, now.to_date)
- simple_stubs.stub_object(DateTime, :now, now.to_datetime)
+ simple_stubs.stub_object(Time, :now) { at(now.to_i) }
+ simple_stubs.stub_object(Date, :today) { jd(now.to_date.jd) }
+ simple_stubs.stub_object(DateTime, :now) { jd(now.to_date.jd, now.hour, now.min, now.sec, Rational(now.utc_offset, 86400)) }
if block_given?
begin
@@ -113,10 +159,10 @@ module ActiveSupport
end
# Returns the current time back to its original state, by removing the stubs added by
- # `travel` and `travel_to`.
+ # +travel+ and +travel_to+.
#
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
- # travel_to Time.new(2004, 11, 24, 01, 04, 44)
+ # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44)
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
# travel_back
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
@@ -124,6 +170,26 @@ module ActiveSupport
simple_stubs.unstub_all!
end
+ # Calls +travel_to+ with +Time.now+.
+ #
+ # Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00
+ # freeze_time
+ # sleep(1)
+ # Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00
+ #
+ # This method also accepts a block, which will return the current time back to its original
+ # state at the end of the block:
+ #
+ # Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00
+ # freeze_time do
+ # sleep(1)
+ # User.create.created_at # => Sun, 09 Jul 2017 15:34:49 EST -05:00
+ # end
+ # Time.current # => Sun, 09 Jul 2017 15:34:50 EST -05:00
+ def freeze_time(&block)
+ travel_to Time.now, &block
+ end
+
private
def simple_stubs
diff --git a/activesupport/lib/active_support/time.rb b/activesupport/lib/active_support/time.rb
index ea2d3391bd..51854675bf 100644
--- a/activesupport/lib/active_support/time.rb
+++ b/activesupport/lib/active_support/time.rb
@@ -1,18 +1,20 @@
+# frozen_string_literal: true
+
module ActiveSupport
- autoload :Duration, 'active_support/duration'
- autoload :TimeWithZone, 'active_support/time_with_zone'
- autoload :TimeZone, 'active_support/values/time_zone'
+ autoload :Duration, "active_support/duration"
+ autoload :TimeWithZone, "active_support/time_with_zone"
+ autoload :TimeZone, "active_support/values/time_zone"
end
-require 'date'
-require 'time'
+require "date"
+require "time"
-require 'active_support/core_ext/time'
-require 'active_support/core_ext/date'
-require 'active_support/core_ext/date_time'
+require "active_support/core_ext/time"
+require "active_support/core_ext/date"
+require "active_support/core_ext/date_time"
-require 'active_support/core_ext/integer/time'
-require 'active_support/core_ext/numeric/time'
+require "active_support/core_ext/integer/time"
+require "active_support/core_ext/numeric/time"
-require 'active_support/core_ext/string/conversions'
-require 'active_support/core_ext/string/zones'
+require "active_support/core_ext/string/conversions"
+require "active_support/core_ext/string/zones"
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index b1cec43124..20650ce714 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -1,7 +1,9 @@
-require 'active_support/duration'
-require 'active_support/values/time_zone'
-require 'active_support/core_ext/object/acts_like'
-require 'active_support/core_ext/date_and_time/compatibility'
+# frozen_string_literal: true
+
+require "active_support/duration"
+require "active_support/values/time_zone"
+require "active_support/core_ext/object/acts_like"
+require "active_support/core_ext/date_and_time/compatibility"
module ActiveSupport
# A Time-like class that can represent a time in any time zone. Necessary
@@ -36,14 +38,13 @@ module ActiveSupport
# t.is_a?(Time) # => true
# t.is_a?(ActiveSupport::TimeWithZone) # => true
class TimeWithZone
-
# Report class name as 'Time' to thwart type checking.
def self.name
- 'Time'
+ "Time"
end
PRECISIONS = Hash.new { |h, n| h[n] = "%FT%T.%#{n}N".freeze }
- PRECISIONS[0] = '%FT%T'.freeze
+ PRECISIONS[0] = "%FT%T".freeze
include Comparable, DateAndTime::Compatibility
attr_reader :time_zone
@@ -134,7 +135,7 @@ module ActiveSupport
period.zone_identifier.to_s
end
- # Returns a string of the object's date, time, zone and offset from UTC.
+ # Returns a string of the object's date, time, zone, and offset from UTC.
#
# Time.zone.now.inspect # => "Thu, 04 Dec 2014 11:00:25 EST -05:00"
def inspect
@@ -149,6 +150,7 @@ module ActiveSupport
"#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z'.freeze)}"
end
alias_method :iso8601, :xmlschema
+ alias_method :rfc3339, :xmlschema
# Coerces time to a string for JSON encoding. The default format is ISO 8601.
# You can get %Y/%m/%d %H:%M:%S +offset style by setting
@@ -171,12 +173,12 @@ module ActiveSupport
end
def init_with(coder) #:nodoc:
- initialize(coder['utc'], coder['zone'], coder['time'])
+ initialize(coder["utc"], coder["zone"], coder["time"])
end
def encode_with(coder) #:nodoc:
- coder.tag = '!ruby/object:ActiveSupport::TimeWithZone'
- coder.map = { 'utc' => utc, 'zone' => time_zone, 'time' => time }
+ coder.tag = "!ruby/object:ActiveSupport::TimeWithZone"
+ coder.map = { "utc" => utc, "zone" => time_zone, "time" => time }
end
# Returns a string of the object's date and time in the format used by
@@ -280,6 +282,7 @@ module ActiveSupport
end
end
alias_method :since, :+
+ alias_method :in, :+
# Returns a new TimeWithZone object that represents the difference between
# the current object's time and the +other+ time.
@@ -329,6 +332,42 @@ module ActiveSupport
since(-other)
end
+ # Returns a new +ActiveSupport::TimeWithZone+ where one or more of the elements have
+ # been changed according to the +options+ parameter. The time options (<tt>:hour</tt>,
+ # <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>) reset cascadingly,
+ # so if only the hour is passed, then minute, sec, usec and nsec is set to 0. If the
+ # hour and minute is passed, then sec, usec and nsec is set to 0. The +options+
+ # parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>,
+ # <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>,
+ # <tt>:nsec</tt>, <tt>:offset</tt>, <tt>:zone</tt>. Pass either <tt>:usec</tt>
+ # or <tt>:nsec</tt>, not both. Similarly, pass either <tt>:zone</tt> or
+ # <tt>:offset</tt>, not both.
+ #
+ # t = Time.zone.now # => Fri, 14 Apr 2017 11:45:15 EST -05:00
+ # t.change(year: 2020) # => Tue, 14 Apr 2020 11:45:15 EST -05:00
+ # t.change(hour: 12) # => Fri, 14 Apr 2017 12:00:00 EST -05:00
+ # t.change(min: 30) # => Fri, 14 Apr 2017 11:30:00 EST -05:00
+ # t.change(offset: "-10:00") # => Fri, 14 Apr 2017 11:45:15 HST -10:00
+ # t.change(zone: "Hawaii") # => Fri, 14 Apr 2017 11:45:15 HST -10:00
+ def change(options)
+ if options[:zone] && options[:offset]
+ raise ArgumentError, "Can't change both :offset and :zone at the same time: #{options.inspect}"
+ end
+
+ new_time = time.change(options)
+
+ if options[:zone]
+ new_zone = ::Time.find_zone(options[:zone])
+ elsif options[:offset]
+ new_zone = ::Time.find_zone(new_time.utc_offset)
+ end
+
+ new_zone ||= time_zone
+ periods = new_zone.periods_for_local(new_time)
+
+ self.class.new(nil, new_zone, new_time, periods.include?(period) ? period : nil)
+ end
+
# Uses Date to provide precise Time calculations for years, months, and days
# according to the proleptic Gregorian calendar. The result is returned as a
# new TimeWithZone object.
@@ -407,7 +446,18 @@ module ActiveSupport
# Time.zone.now.to_datetime # => Tue, 18 Aug 2015 02:32:20 +0000
# Time.current.in_time_zone('Hawaii').to_datetime # => Mon, 17 Aug 2015 16:32:20 -1000
def to_datetime
- utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
+ @to_datetime ||= utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
+ end
+
+ # Returns an instance of +Time+, either with the same UTC offset
+ # as +self+ or in the local system timezone depending on the setting
+ # of +ActiveSupport.to_time_preserves_timezone+.
+ def to_time
+ if preserve_timezone
+ @to_time_with_instance_offset ||= getlocal(utc_offset)
+ else
+ @to_time_with_system_offset ||= getlocal
+ end
end
# So that +self+ <tt>acts_like?(:time)</tt>.
@@ -427,7 +477,8 @@ module ActiveSupport
end
def freeze
- period; utc; time # preload instance variables before freezing
+ # preload instance variables before freezing
+ period; utc; time; to_datetime; to_time
super
end
@@ -459,7 +510,7 @@ module ActiveSupport
def method_missing(sym, *args, &block)
wrap_with_time_zone time.__send__(sym, *args, &block)
rescue NoMethodError => e
- raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
+ raise e, e.message.sub(time.inspect, inspect), e.backtrace
end
private
@@ -477,11 +528,13 @@ module ActiveSupport
end
def transfer_time_values_to_utc_constructor(time)
+ # avoid creating another Time object if possible
+ return time if time.instance_of?(::Time) && time.utc?
::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec + time.subsec)
end
def duration_of_variable_length?(obj)
- ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
+ ActiveSupport::Duration === obj && obj.parts.any? { |p| [:years, :months, :weeks, :days].include?(p[0]) }
end
def wrap_with_time_zone(time)
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 19420cee5e..4d81ac939e 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -1,12 +1,14 @@
-require 'tzinfo'
-require 'concurrent/map'
-require 'active_support/core_ext/object/blank'
+# frozen_string_literal: true
+
+require "tzinfo"
+require "concurrent/map"
+require "active_support/core_ext/object/blank"
module ActiveSupport
# The TimeZone class serves as a wrapper around TZInfo::Timezone instances.
# It allows us to do the following:
#
- # * Limit the set of zones provided by TZInfo to a meaningful subset of 146
+ # * Limit the set of zones provided by TZInfo to a meaningful subset of 134
# zones.
# * Retrieve and display zones with a friendlier name
# (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
@@ -28,7 +30,7 @@ module ActiveSupport
class TimeZone
# Keys are Rails TimeZone names, values are TZInfo identifiers.
MAPPING = {
- "International Date Line West" => "Pacific/Midway",
+ "International Date Line West" => "Etc/GMT+12",
"Midway Island" => "Pacific/Midway",
"American Samoa" => "Pacific/Pago_Pago",
"Hawaii" => "Pacific/Honolulu",
@@ -59,6 +61,7 @@ module ActiveSupport
"Buenos Aires" => "America/Argentina/Buenos_Aires",
"Montevideo" => "America/Montevideo",
"Georgetown" => "America/Guyana",
+ "Puerto Rico" => "America/Puerto_Rico",
"Greenland" => "America/Godthab",
"Mid-Atlantic" => "Atlantic/South_Georgia",
"Azores" => "Atlantic/Azores",
@@ -180,8 +183,8 @@ module ActiveSupport
"Samoa" => "Pacific/Apia"
}
- UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
- UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.tr(':', '')
+ UTC_OFFSET_WITH_COLON = "%s%02d:%02d"
+ UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.tr(":", "")
@lazy_zones_map = Concurrent::Map.new
@country_zones = Concurrent::Map.new
@@ -193,7 +196,7 @@ module ActiveSupport
# ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
def seconds_to_utc_offset(seconds, colon = true)
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
- sign = (seconds < 0 ? '-' : '+')
+ sign = (seconds < 0 ? "-" : "+")
hours = seconds.abs / 3600
minutes = (seconds.abs % 3600) / 60
format % [sign, hours, minutes]
@@ -226,17 +229,17 @@ module ActiveSupport
# Returns +nil+ if no such time zone is known to the system.
def [](arg)
case arg
- when String
+ when String
begin
@lazy_zones_map[arg] ||= create(arg)
rescue TZInfo::InvalidTimezoneIdentifier
nil
end
- when Numeric, ActiveSupport::Duration
- arg *= 3600 if arg.abs <= 13
- all.find { |z| z.utc_offset == arg.to_i }
+ when Numeric, ActiveSupport::Duration
+ arg *= 3600 if arg.abs <= 13
+ all.find { |z| z.utc_offset == arg.to_i }
else
- raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
+ raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
end
end
@@ -250,18 +253,31 @@ module ActiveSupport
# for time zones in the country specified by its ISO 3166-1 Alpha2 code.
def country_zones(country_code)
code = country_code.to_s.upcase
- @country_zones[code] ||=
- TZInfo::Country.get(code).zone_identifiers.map do |tz_id|
- name = MAPPING.key(tz_id)
- name && self[name]
- end.compact.sort!
+ @country_zones[code] ||= load_country_zones(code)
+ end
+
+ def clear #:nodoc:
+ @lazy_zones_map = Concurrent::Map.new
+ @country_zones = Concurrent::Map.new
+ @zones = nil
+ @zones_map = nil
end
private
+ def load_country_zones(code)
+ country = TZInfo::Country.get(code)
+ country.zone_identifiers.map do |tz_id|
+ if MAPPING.value?(tz_id)
+ self[MAPPING.key(tz_id)]
+ else
+ create(tz_id, nil, TZInfo::Timezone.new(tz_id))
+ end
+ end.sort!
+ end
+
def zones_map
- @zones_map ||= begin
- MAPPING.each_key {|place| self[place]} # load all the zones
- @lazy_zones_map
+ @zones_map ||= MAPPING.each_with_object({}) do |(name, _), zones|
+ zones[name] = self[name]
end
end
end
@@ -295,7 +311,7 @@ module ActiveSupport
# zone = ActiveSupport::TimeZone['Central Time (US & Canada)']
# zone.formatted_offset # => "-06:00"
# zone.formatted_offset(false) # => "-0600"
- def formatted_offset(colon=true, alternate_utc_string = nil)
+ def formatted_offset(colon = true, alternate_utc_string = nil)
utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
end
@@ -340,6 +356,41 @@ module ActiveSupport
end
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
+ # of +self+ from an ISO 8601 string.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.iso8601('1999-12-31T14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # If the time components are missing then they will be set to zero.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.iso8601('1999-12-31') # => Fri, 31 Dec 1999 00:00:00 HST -10:00
+ #
+ # If the string is invalid then an +ArgumentError+ will be raised unlike +parse+
+ # which usually returns +nil+ when given an invalid date string.
+ def iso8601(str)
+ parts = Date._iso8601(str)
+
+ raise ArgumentError, "invalid date" if parts.empty?
+
+ time = Time.new(
+ parts.fetch(:year),
+ parts.fetch(:mon),
+ parts.fetch(:mday),
+ parts.fetch(:hour, 0),
+ parts.fetch(:min, 0),
+ parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset, 0)
+ )
+
+ if parts[:offset]
+ TimeWithZone.new(time.utc, self)
+ else
+ TimeWithZone.new(nil, self, time)
+ end
+ end
+
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone
# of +self+ from parsed string.
#
# Time.zone = 'Hawaii' # => "Hawaii"
@@ -355,10 +406,42 @@ module ActiveSupport
# components are supplied, then the day of the month defaults to 1:
#
# Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
- def parse(str, now=now())
+ #
+ # If the string is invalid then an +ArgumentError+ could be raised.
+ def parse(str, now = now())
parts_to_time(Date._parse(str, false), now)
end
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone
+ # of +self+ from an RFC 3339 string.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.rfc3339('2000-01-01T00:00:00Z') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # If the time or zone components are missing then an +ArgumentError+ will
+ # be raised. This is much stricter than either +parse+ or +iso8601+ which
+ # allow for missing components.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.rfc3339('1999-12-31') # => ArgumentError: invalid date
+ def rfc3339(str)
+ parts = Date._rfc3339(str)
+
+ raise ArgumentError, "invalid date" if parts.empty?
+
+ time = Time.new(
+ parts.fetch(:year),
+ parts.fetch(:mon),
+ parts.fetch(:mday),
+ parts.fetch(:hour),
+ parts.fetch(:min),
+ parts.fetch(:sec) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset)
+ )
+
+ TimeWithZone.new(time.utc, self)
+ end
+
# Parses +str+ according to +format+ and returns an ActiveSupport::TimeWithZone.
#
# Assumes that +str+ is a time in the time zone +self+,
@@ -379,7 +462,7 @@ module ActiveSupport
# components are supplied, then the day of the month defaults to 1:
#
# Time.zone.strptime('Mar 2000', '%b %Y') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
- def strptime(str, format, now=now())
+ def strptime(str, format, now = now())
parts_to_time(DateTime._strptime(str, format), now)
end
@@ -416,7 +499,7 @@ module ActiveSupport
# Adjust the given time to the simultaneous time in UTC. Returns a
# Time.utc() instance.
- def local_to_utc(time, dst=true)
+ def local_to_utc(time, dst = true)
tzinfo.local_to_utc(time, dst)
end
@@ -428,8 +511,8 @@ module ActiveSupport
# Available so that TimeZone instances respond like TZInfo::Timezone
# instances.
- def period_for_local(time, dst=true)
- tzinfo.period_for_local(time, dst)
+ def period_for_local(time, dst = true)
+ tzinfo.period_for_local(time, dst) { |periods| periods.last }
end
def periods_for_local(time) #:nodoc:
@@ -437,29 +520,34 @@ module ActiveSupport
end
def init_with(coder) #:nodoc:
- initialize(coder['name'])
+ initialize(coder["name"])
end
def encode_with(coder) #:nodoc:
- coder.tag ="!ruby/object:#{self.class}"
- coder.map = { 'name' => tzinfo.name }
+ coder.tag = "!ruby/object:#{self.class}"
+ coder.map = { "name" => tzinfo.name }
end
private
def parts_to_time(parts, now)
+ raise ArgumentError, "invalid date" if parts.nil?
return if parts.empty?
- time = Time.new(
- parts.fetch(:year, now.year),
- parts.fetch(:mon, now.month),
- parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
- parts.fetch(:hour, 0),
- parts.fetch(:min, 0),
- parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
- parts.fetch(:offset, 0)
- )
-
- if parts[:offset]
+ if parts[:seconds]
+ time = Time.at(parts[:seconds])
+ else
+ time = Time.new(
+ parts.fetch(:year, now.year),
+ parts.fetch(:mon, now.month),
+ parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
+ parts.fetch(:hour, 0),
+ parts.fetch(:min, 0),
+ parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset, 0)
+ )
+ end
+
+ if parts[:offset] || parts[:seconds]
TimeWithZone.new(time.utc, self)
else
TimeWithZone.new(nil, self, time)
diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat
index dd2c178fb6..f7d9c48bbe 100644
--- a/activesupport/lib/active_support/values/unicode_tables.dat
+++ b/activesupport/lib/active_support/values/unicode_tables.dat
Binary files differ
diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb
index fe03984546..928838c837 100644
--- a/activesupport/lib/active_support/version.rb
+++ b/activesupport/lib/active_support/version.rb
@@ -1,4 +1,6 @@
-require_relative 'gem_version'
+# frozen_string_literal: true
+
+require_relative "gem_version"
module ActiveSupport
# Returns the version of the currently loaded ActiveSupport as a <tt>Gem::Version</tt>
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
index df7b081993..ee2048cb54 100644
--- a/activesupport/lib/active_support/xml_mini.rb
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -1,9 +1,11 @@
-require 'time'
-require 'base64'
-require 'bigdecimal'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/core_ext/date_time/calculations'
+# frozen_string_literal: true
+
+require "time"
+require "base64"
+require "bigdecimal"
+require "active_support/core_ext/module/delegation"
+require "active_support/core_ext/string/inflections"
+require "active_support/core_ext/date_time/calculations"
module ActiveSupport
# = XmlMini
@@ -20,11 +22,11 @@ module ActiveSupport
attr_writer :original_filename, :content_type
def original_filename
- @original_filename || 'untitled'
+ @original_filename || "untitled"
end
def content_type
- @content_type || 'application/octet-stream'
+ @content_type || "application/octet-stream"
end
end
@@ -32,20 +34,25 @@ module ActiveSupport
"binary" => "base64"
} unless defined?(DEFAULT_ENCODINGS)
- TYPE_NAMES = {
- "Symbol" => "symbol",
- "Fixnum" => "integer",
- "Bignum" => "integer",
- "BigDecimal" => "decimal",
- "Float" => "float",
- "TrueClass" => "boolean",
- "FalseClass" => "boolean",
- "Date" => "date",
- "DateTime" => "dateTime",
- "Time" => "dateTime",
- "Array" => "array",
- "Hash" => "hash"
- } unless defined?(TYPE_NAMES)
+ unless defined?(TYPE_NAMES)
+ TYPE_NAMES = {
+ "Symbol" => "symbol",
+ "Integer" => "integer",
+ "BigDecimal" => "decimal",
+ "Float" => "float",
+ "TrueClass" => "boolean",
+ "FalseClass" => "boolean",
+ "Date" => "date",
+ "DateTime" => "dateTime",
+ "Time" => "dateTime",
+ "Array" => "array",
+ "Hash" => "hash"
+ }
+
+ # No need to map these on Ruby 2.4+
+ TYPE_NAMES["Fixnum"] = "integer" unless 0.class == Integer
+ TYPE_NAMES["Bignum"] = "integer" unless 0.class == Integer
+ end
FORMATTING = {
"symbol" => Proc.new { |symbol| symbol.to_s },
@@ -63,7 +70,17 @@ module ActiveSupport
"datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
"integer" => Proc.new { |integer| integer.to_i },
"float" => Proc.new { |float| float.to_f },
- "decimal" => Proc.new { |number| BigDecimal(number) },
+ "decimal" => Proc.new do |number|
+ if String === number
+ begin
+ BigDecimal(number)
+ rescue ArgumentError
+ BigDecimal("0")
+ end
+ else
+ BigDecimal(number)
+ end
+ end,
"boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) },
"string" => Proc.new { |string| string.to_s },
"yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
@@ -81,7 +98,7 @@ module ActiveSupport
attr_accessor :depth
self.depth = 100
- delegate :parse, :to => :backend
+ delegate :parse, to: :backend
def backend
current_thread_backend || @backend
@@ -103,7 +120,7 @@ module ActiveSupport
def to_tag(key, value, options)
type_name = options.delete(:type)
- merged_options = options.merge(:root => key, :skip_instruct => true)
+ merged_options = options.merge(root: key, skip_instruct: true)
if value.is_a?(::Method) || value.is_a?(::Proc)
if value.arity == 1
@@ -121,7 +138,7 @@ module ActiveSupport
key = rename_key(key.to_s, options)
- attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
+ attributes = options[:skip_types] || type_name.nil? ? {} : { type: type_name }
attributes[:nil] = true if value.nil?
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
@@ -144,33 +161,31 @@ module ActiveSupport
key
end
- protected
-
- def _dasherize(key)
- # $2 must be a non-greedy regex for this to work
- left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
- "#{left}#{middle.tr('_ ', '--')}#{right}"
- end
+ private
- # TODO: Add support for other encodings
- def _parse_binary(bin, entity) #:nodoc:
- case entity['encoding']
- when 'base64'
- ::Base64.decode64(bin)
- else
- bin
+ def _dasherize(key)
+ # $2 must be a non-greedy regex for this to work
+ left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1, 3]
+ "#{left}#{middle.tr('_ ', '--')}#{right}"
end
- end
- def _parse_file(file, entity)
- f = StringIO.new(::Base64.decode64(file))
- f.extend(FileLike)
- f.original_filename = entity['name']
- f.content_type = entity['content_type']
- f
- end
+ # TODO: Add support for other encodings
+ def _parse_binary(bin, entity)
+ case entity["encoding"]
+ when "base64"
+ ::Base64.decode64(bin)
+ else
+ bin
+ end
+ end
- private
+ def _parse_file(file, entity)
+ f = StringIO.new(::Base64.decode64(file))
+ f.extend(FileLike)
+ f.original_filename = entity["name"]
+ f.content_type = entity["content_type"]
+ f
+ end
def current_thread_backend
Thread.current[:xml_mini_backend]
@@ -190,5 +205,5 @@ module ActiveSupport
end
end
- XmlMini.backend = 'REXML'
+ XmlMini.backend = "REXML"
end
diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb
index 94751bbc04..7f94a64016 100644
--- a/activesupport/lib/active_support/xml_mini/jdom.rb
+++ b/activesupport/lib/active_support/xml_mini/jdom.rb
@@ -1,9 +1,11 @@
-raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM =~ /java/
+# frozen_string_literal: true
-require 'jruby'
+raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM.include?("java")
+
+require "jruby"
include Java
-require 'active_support/core_ext/object/blank'
+require "active_support/core_ext/object/blank"
java_import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder
java_import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory
@@ -16,7 +18,7 @@ module ActiveSupport
module XmlMini_JDOM #:nodoc:
extend self
- CONTENT_KEY = '__content__'.freeze
+ CONTENT_KEY = "__content__".freeze
NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE
DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE
@@ -38,7 +40,7 @@ module ActiveSupport
else
@dbf = DocumentBuilderFactory.new_instance
# secure processing of java xml
- # http://www.ibm.com/developerworks/xml/library/x-tipcfsx/index.html
+ # https://archive.is/9xcQQ
@dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
@dbf.setFeature("http://xml.org/sax/features/external-general-entities", false)
@dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false)
@@ -46,136 +48,136 @@ module ActiveSupport
xml_string_reader = StringReader.new(data)
xml_input_source = InputSource.new(xml_string_reader)
doc = @dbf.new_document_builder.parse(xml_input_source)
- merge_element!({CONTENT_KEY => ''}, doc.document_element, XmlMini.depth)
+ merge_element!({ CONTENT_KEY => "" }, doc.document_element, XmlMini.depth)
end
end
private
- # Convert an XML element and merge into the hash
- #
- # hash::
- # Hash to merge the converted element into.
- # element::
- # XML element to merge into hash
- def merge_element!(hash, element, depth)
- raise 'Document too deep!' if depth == 0
- delete_empty(hash)
- merge!(hash, element.tag_name, collapse(element, depth))
- end
-
- def delete_empty(hash)
- hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == ''
- end
+ # Convert an XML element and merge into the hash
+ #
+ # hash::
+ # Hash to merge the converted element into.
+ # element::
+ # XML element to merge into hash
+ def merge_element!(hash, element, depth)
+ raise "Document too deep!" if depth == 0
+ delete_empty(hash)
+ merge!(hash, element.tag_name, collapse(element, depth))
+ end
- # Actually converts an XML document element into a data structure.
- #
- # element::
- # The document element to be collapsed.
- def collapse(element, depth)
- hash = get_attributes(element)
+ def delete_empty(hash)
+ hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == ""
+ end
- child_nodes = element.child_nodes
- if child_nodes.length > 0
- (0...child_nodes.length).each do |i|
- child = child_nodes.item(i)
- merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE
+ # Actually converts an XML document element into a data structure.
+ #
+ # element::
+ # The document element to be collapsed.
+ def collapse(element, depth)
+ hash = get_attributes(element)
+
+ child_nodes = element.child_nodes
+ if child_nodes.length > 0
+ (0...child_nodes.length).each do |i|
+ child = child_nodes.item(i)
+ merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE
+ end
+ merge_texts!(hash, element) unless empty_content?(element)
+ hash
+ else
+ merge_texts!(hash, element)
end
- merge_texts!(hash, element) unless empty_content?(element)
- hash
- else
- merge_texts!(hash, element)
end
- end
- # Merge all the texts of an element into the hash
- #
- # hash::
- # Hash to add the converted element to.
- # element::
- # XML element whose texts are to me merged into the hash
- def merge_texts!(hash, element)
- delete_empty(hash)
- text_children = texts(element)
- if text_children.join.empty?
- hash
- else
- # must use value to prevent double-escaping
- merge!(hash, CONTENT_KEY, text_children.join)
+ # Merge all the texts of an element into the hash
+ #
+ # hash::
+ # Hash to add the converted element to.
+ # element::
+ # XML element whose texts are to me merged into the hash
+ def merge_texts!(hash, element)
+ delete_empty(hash)
+ text_children = texts(element)
+ if text_children.join.empty?
+ hash
+ else
+ # must use value to prevent double-escaping
+ merge!(hash, CONTENT_KEY, text_children.join)
+ end
end
- end
- # Adds a new key/value pair to an existing Hash. If the key to be added
- # already exists and the existing value associated with key is not
- # an Array, it will be wrapped in an Array. Then the new value is
- # appended to that Array.
- #
- # hash::
- # Hash to add key/value pair to.
- # key::
- # Key to be added.
- # value::
- # Value to be associated with key.
- def merge!(hash, key, value)
- if hash.has_key?(key)
- if hash[key].instance_of?(Array)
- hash[key] << value
+ # Adds a new key/value pair to an existing Hash. If the key to be added
+ # already exists and the existing value associated with key is not
+ # an Array, it will be wrapped in an Array. Then the new value is
+ # appended to that Array.
+ #
+ # hash::
+ # Hash to add key/value pair to.
+ # key::
+ # Key to be added.
+ # value::
+ # Value to be associated with key.
+ def merge!(hash, key, value)
+ if hash.has_key?(key)
+ if hash[key].instance_of?(Array)
+ hash[key] << value
+ else
+ hash[key] = [hash[key], value]
+ end
+ elsif value.instance_of?(Array)
+ hash[key] = [value]
else
- hash[key] = [hash[key], value]
+ hash[key] = value
end
- elsif value.instance_of?(Array)
- hash[key] = [value]
- else
- hash[key] = value
+ hash
end
- hash
- end
- # Converts the attributes array of an XML element into a hash.
- # Returns an empty Hash if node has no attributes.
- #
- # element::
- # XML element to extract attributes from.
- def get_attributes(element)
- attribute_hash = {}
- attributes = element.attributes
- (0...attributes.length).each do |i|
- attribute_hash[CONTENT_KEY] ||= ''
- attribute_hash[attributes.item(i).name] = attributes.item(i).value
+ # Converts the attributes array of an XML element into a hash.
+ # Returns an empty Hash if node has no attributes.
+ #
+ # element::
+ # XML element to extract attributes from.
+ def get_attributes(element)
+ attribute_hash = {}
+ attributes = element.attributes
+ (0...attributes.length).each do |i|
+ attribute_hash[CONTENT_KEY] ||= ""
+ attribute_hash[attributes.item(i).name] = attributes.item(i).value
+ end
+ attribute_hash
end
- attribute_hash
- end
- # Determines if a document element has text content
- #
- # element::
- # XML element to be checked.
- def texts(element)
- texts = []
- child_nodes = element.child_nodes
- (0...child_nodes.length).each do |i|
- item = child_nodes.item(i)
- if item.node_type == Node.TEXT_NODE
- texts << item.get_data
+ # Determines if a document element has text content
+ #
+ # element::
+ # XML element to be checked.
+ def texts(element)
+ texts = []
+ child_nodes = element.child_nodes
+ (0...child_nodes.length).each do |i|
+ item = child_nodes.item(i)
+ if item.node_type == Node.TEXT_NODE
+ texts << item.get_data
+ end
end
+ texts
end
- texts
- end
- # Determines if a document element has text content
- #
- # element::
- # XML element to be checked.
- def empty_content?(element)
- text = ''
- child_nodes = element.child_nodes
- (0...child_nodes.length).each do |i|
- item = child_nodes.item(i)
- if item.node_type == Node.TEXT_NODE
- text << item.get_data.strip
+ # Determines if a document element has text content
+ #
+ # element::
+ # XML element to be checked.
+ def empty_content?(element)
+ text = "".dup
+ child_nodes = element.child_nodes
+ (0...child_nodes.length).each do |i|
+ item = child_nodes.item(i)
+ if item.node_type == Node.TEXT_NODE
+ text << item.get_data.strip
+ end
end
+ text.strip.length == 0
end
- text.strip.length == 0
- end
end
end
diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb
index bb0ea9c582..0b000fea60 100644
--- a/activesupport/lib/active_support/xml_mini/libxml.rb
+++ b/activesupport/lib/active_support/xml_mini/libxml.rb
@@ -1,6 +1,8 @@
-require 'libxml'
-require 'active_support/core_ext/object/blank'
-require 'stringio'
+# frozen_string_literal: true
+
+require "libxml"
+require "active_support/core_ext/object/blank"
+require "stringio"
module ActiveSupport
module XmlMini_LibXML #:nodoc:
@@ -11,18 +13,15 @@ module ActiveSupport
# XML Document string or IO to parse
def parse(data)
if !data.respond_to?(:read)
- data = StringIO.new(data || '')
+ data = StringIO.new(data || "")
end
- char = data.getc
- if char.nil?
+ if data.eof?
{}
else
- data.ungetc(char)
LibXML::XML::Parser.io(data).parse.to_hash
end
end
-
end
end
@@ -35,20 +34,20 @@ module LibXML #:nodoc:
end
module Node #:nodoc:
- CONTENT_ROOT = '__content__'.freeze
+ CONTENT_ROOT = "__content__".freeze
# Convert XML document to hash.
#
# hash::
# Hash to merge the converted element into.
- def to_hash(hash={})
+ def to_hash(hash = {})
node_hash = {}
# Insert node hash into parent hash correctly.
case hash[name]
- when Array then hash[name] << node_hash
- when Hash then hash[name] = [hash[name], node_hash]
- when nil then hash[name] = node_hash
+ when Array then hash[name] << node_hash
+ when Hash then hash[name] = [hash[name], node_hash]
+ when nil then hash[name] = node_hash
end
# Handle child elements
@@ -56,7 +55,7 @@ module LibXML #:nodoc:
if c.element?
c.to_hash(node_hash)
elsif c.text? || c.cdata?
- node_hash[CONTENT_ROOT] ||= ''
+ node_hash[CONTENT_ROOT] ||= "".dup
node_hash[CONTENT_ROOT] << c.content
end
end
@@ -75,5 +74,7 @@ module LibXML #:nodoc:
end
end
+# :enddoc:
+
LibXML::XML::Document.include(LibXML::Conversions::Document)
LibXML::XML::Node.include(LibXML::Conversions::Node)
diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
index 70a95299ec..dcf16e6084 100644
--- a/activesupport/lib/active_support/xml_mini/libxmlsax.rb
+++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
@@ -1,6 +1,8 @@
-require 'libxml'
-require 'active_support/core_ext/object/blank'
-require 'stringio'
+# frozen_string_literal: true
+
+require "libxml"
+require "active_support/core_ext/object/blank"
+require "stringio"
module ActiveSupport
module XmlMini_LibXMLSAX #:nodoc:
@@ -9,11 +11,10 @@ module ActiveSupport
# Class that will build the hash while the XML document
# is being parsed using SAX events.
class HashBuilder
-
include LibXML::XML::SaxParser::Callbacks
- CONTENT_KEY = '__content__'.freeze
- HASH_SIZE_KEY = '__hash_size__'.freeze
+ CONTENT_KEY = "__content__".freeze
+ HASH_SIZE_KEY = "__hash_size__".freeze
attr_reader :hash
@@ -22,7 +23,7 @@ module ActiveSupport
end
def on_start_document
- @hash = { CONTENT_KEY => '' }
+ @hash = { CONTENT_KEY => "".dup }
@hash_stack = [@hash]
end
@@ -32,20 +33,20 @@ module ActiveSupport
end
def on_start_element(name, attrs = {})
- new_hash = { CONTENT_KEY => '' }.merge!(attrs)
+ new_hash = { CONTENT_KEY => "".dup }.merge!(attrs)
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
- when Array then current_hash[name] << new_hash
- when Hash then current_hash[name] = [current_hash[name], new_hash]
- when nil then current_hash[name] = new_hash
+ when Array then current_hash[name] << new_hash
+ when Hash then current_hash[name] = [current_hash[name], new_hash]
+ when nil then current_hash[name] = new_hash
end
@hash_stack.push(new_hash)
end
def on_end_element(name)
- if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
+ if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ""
current_hash.delete(CONTENT_KEY)
end
@hash_stack.pop
@@ -63,18 +64,15 @@ module ActiveSupport
def parse(data)
if !data.respond_to?(:read)
- data = StringIO.new(data || '')
+ data = StringIO.new(data || "")
end
- char = data.getc
- if char.nil?
+ if data.eof?
{}
else
- data.ungetc(char)
-
LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER)
parser = LibXML::XML::SaxParser.io(data)
- document = self.document_class.new
+ document = document_class.new
parser.callbacks = document
parser.parse
diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb
index 619cc7522d..5ee6fc8159 100644
--- a/activesupport/lib/active_support/xml_mini/nokogiri.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb
@@ -1,11 +1,13 @@
+# frozen_string_literal: true
+
begin
- require 'nokogiri'
+ require "nokogiri"
rescue LoadError => e
$stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
-require 'active_support/core_ext/object/blank'
-require 'stringio'
+require "active_support/core_ext/object/blank"
+require "stringio"
module ActiveSupport
module XmlMini_Nokogiri #:nodoc:
@@ -16,14 +18,12 @@ module ActiveSupport
# XML Document string or IO to parse
def parse(data)
if !data.respond_to?(:read)
- data = StringIO.new(data || '')
+ data = StringIO.new(data || "")
end
- char = data.getc
- if char.nil?
+ if data.eof?
{}
else
- data.ungetc(char)
doc = Nokogiri::XML(data)
raise doc.errors.first if doc.errors.length > 0
doc.to_hash
@@ -38,20 +38,20 @@ module ActiveSupport
end
module Node #:nodoc:
- CONTENT_ROOT = '__content__'.freeze
+ CONTENT_ROOT = "__content__".freeze
# Convert XML document to hash.
#
# hash::
# Hash to merge the converted element into.
- def to_hash(hash={})
+ def to_hash(hash = {})
node_hash = {}
# Insert node hash into parent hash correctly.
case hash[name]
- when Array then hash[name] << node_hash
- when Hash then hash[name] = [hash[name], node_hash]
- when nil then hash[name] = node_hash
+ when Array then hash[name] << node_hash
+ when Hash then hash[name] = [hash[name], node_hash]
+ when nil then hash[name] = node_hash
end
# Handle child elements
@@ -59,7 +59,7 @@ module ActiveSupport
if c.element?
c.to_hash(node_hash)
elsif c.text? || c.cdata?
- node_hash[CONTENT_ROOT] ||= ''
+ node_hash[CONTENT_ROOT] ||= "".dup
node_hash[CONTENT_ROOT] << c.content
end
end
diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
index be2d6a4cb1..b01ed00a14 100644
--- a/activesupport/lib/active_support/xml_mini/nokogirisax.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
@@ -1,11 +1,13 @@
+# frozen_string_literal: true
+
begin
- require 'nokogiri'
+ require "nokogiri"
rescue LoadError => e
$stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
-require 'active_support/core_ext/object/blank'
-require 'stringio'
+require "active_support/core_ext/object/blank"
+require "stringio"
module ActiveSupport
module XmlMini_NokogiriSAX #:nodoc:
@@ -14,9 +16,8 @@ module ActiveSupport
# Class that will build the hash while the XML document
# is being parsed using SAX events.
class HashBuilder < Nokogiri::XML::SAX::Document
-
- CONTENT_KEY = '__content__'.freeze
- HASH_SIZE_KEY = '__hash_size__'.freeze
+ CONTENT_KEY = "__content__".freeze
+ HASH_SIZE_KEY = "__hash_size__".freeze
attr_reader :hash
@@ -38,20 +39,20 @@ module ActiveSupport
end
def start_element(name, attrs = [])
- new_hash = { CONTENT_KEY => '' }.merge!(Hash[attrs])
+ new_hash = { CONTENT_KEY => "".dup }.merge!(Hash[attrs])
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
- when Array then current_hash[name] << new_hash
- when Hash then current_hash[name] = [current_hash[name], new_hash]
- when nil then current_hash[name] = new_hash
+ when Array then current_hash[name] << new_hash
+ when Hash then current_hash[name] = [current_hash[name], new_hash]
+ when nil then current_hash[name] = new_hash
end
@hash_stack.push(new_hash)
end
def end_element(name)
- if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
+ if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ""
current_hash.delete(CONTENT_KEY)
end
@hash_stack.pop
@@ -69,15 +70,13 @@ module ActiveSupport
def parse(data)
if !data.respond_to?(:read)
- data = StringIO.new(data || '')
+ data = StringIO.new(data || "")
end
- char = data.getc
- if char.nil?
+ if data.eof?
{}
else
- data.ungetc(char)
- document = self.document_class.new
+ document = document_class.new
parser = Nokogiri::XML::SAX::Parser.new(document)
parser.parse(data)
document.hash
diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb
index 924ed72345..32458d5b0d 100644
--- a/activesupport/lib/active_support/xml_mini/rexml.rb
+++ b/activesupport/lib/active_support/xml_mini/rexml.rb
@@ -1,12 +1,14 @@
-require 'active_support/core_ext/kernel/reporting'
-require 'active_support/core_ext/object/blank'
-require 'stringio'
+# frozen_string_literal: true
+
+require "active_support/core_ext/kernel/reporting"
+require "active_support/core_ext/object/blank"
+require "stringio"
module ActiveSupport
module XmlMini_REXML #:nodoc:
extend self
- CONTENT_KEY = '__content__'.freeze
+ CONTENT_KEY = "__content__".freeze
# Parse an XML Document string or IO into a simple hash.
#
@@ -17,15 +19,13 @@ module ActiveSupport
# XML Document string or IO to parse
def parse(data)
if !data.respond_to?(:read)
- data = StringIO.new(data || '')
+ data = StringIO.new(data || "")
end
- char = data.getc
- if char.nil?
+ if data.eof?
{}
else
- data.ungetc(char)
- silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
+ silence_warnings { require "rexml/document" } unless defined?(REXML::Document)
doc = REXML::Document.new(data)
if doc.root
@@ -57,7 +57,7 @@ module ActiveSupport
hash = get_attributes(element)
if element.has_elements?
- element.each_element {|child| merge_element!(hash, child, depth - 1) }
+ element.each_element { |child| merge_element!(hash, child, depth - 1) }
merge_texts!(hash, element) unless empty_content?(element)
hash
else
@@ -76,7 +76,7 @@ module ActiveSupport
hash
else
# must use value to prevent double-escaping
- texts = ''
+ texts = "".dup
element.texts.each { |t| texts << t.value }
merge!(hash, CONTENT_KEY, texts)
end
@@ -115,7 +115,7 @@ module ActiveSupport
# XML element to extract attributes from.
def get_attributes(element)
attributes = {}
- element.attributes.each { |n,v| attributes[n] = v }
+ element.attributes.each { |n, v| attributes[n] = v }
attributes
end
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index 7f0fcd6996..f214898145 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -1,36 +1,45 @@
+# frozen_string_literal: true
+
ORIG_ARGV = ARGV.dup
-require 'active_support/core_ext/kernel/reporting'
+require "active_support/core_ext/kernel/reporting"
silence_warnings do
- Encoding.default_internal = "UTF-8"
- Encoding.default_external = "UTF-8"
+ Encoding.default_internal = Encoding::UTF_8
+ Encoding.default_external = Encoding::UTF_8
end
-require 'active_support/testing/autorun'
-require 'active_support/testing/method_call_assertions'
+require "active_support/testing/autorun"
+require "active_support/testing/method_call_assertions"
-ENV['NO_RELOAD'] = '1'
-require 'active_support'
+ENV["NO_RELOAD"] = "1"
+require "active_support"
Thread.abort_on_exception = true
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
+# Default to old to_time behavior but allow running tests with new behavior
+ActiveSupport.to_time_preserves_timezone = ENV["PRESERVE_TIMEZONES"] == "1"
+
# Disable available locale checks to avoid warnings running the test suite.
I18n.enforce_available_locales = false
-# Skips the current run on Rubinius using Minitest::Assertions#skip
-def rubinius_skip(message = '')
- skip message if RUBY_ENGINE == 'rbx'
-end
-
-# Skips the current run on JRuby using Minitest::Assertions#skip
-def jruby_skip(message = '')
- skip message if defined?(JRUBY_VERSION)
-end
-
class ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions
+
+ # Skips the current run on Rubinius using Minitest::Assertions#skip
+ private def rubinius_skip(message = "")
+ skip message if RUBY_ENGINE == "rbx"
+ end
+
+ # Skips the current run on JRuby using Minitest::Assertions#skip
+ private def jruby_skip(message = "")
+ skip message if defined?(JRUBY_VERSION)
+ end
+
+ def frozen_error_class
+ Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError
+ end
end
diff --git a/activesupport/test/array_inquirer_test.rb b/activesupport/test/array_inquirer_test.rb
index 263ab3802b..d5419b862d 100644
--- a/activesupport/test/array_inquirer_test.rb
+++ b/activesupport/test/array_inquirer_test.rb
@@ -1,9 +1,11 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
class ArrayInquirerTest < ActiveSupport::TestCase
def setup
- @array_inquirer = ActiveSupport::ArrayInquirer.new([:mobile, :tablet, 'api'])
+ @array_inquirer = ActiveSupport::ArrayInquirer.new([:mobile, :tablet, "api"])
end
def test_individual
@@ -19,7 +21,7 @@ class ArrayInquirerTest < ActiveSupport::TestCase
end
def test_any_string_symbol_mismatch
- assert @array_inquirer.any?('mobile')
+ assert @array_inquirer.any?("mobile")
assert @array_inquirer.any?(:api)
end
@@ -33,9 +35,29 @@ class ArrayInquirerTest < ActiveSupport::TestCase
end
def test_inquiry
- result = [:mobile, :tablet, 'api'].inquiry
+ result = [:mobile, :tablet, "api"].inquiry
assert_instance_of ActiveSupport::ArrayInquirer, result
assert_equal @array_inquirer, result
end
+
+ def test_respond_to_fallback_to_array_respond_to
+ Array.class_eval do
+ def respond_to_missing?(name, include_private = false)
+ (name == :foo) || super
+ end
+ end
+ arr = ActiveSupport::ArrayInquirer.new([:x])
+
+ assert_respond_to arr, :can_you_hear_me?
+ assert_respond_to arr, :foo
+ assert_not_respond_to arr, :nope
+ ensure
+ Array.class_eval do
+ undef_method :respond_to_missing?
+ def respond_to_missing?(name, include_private = false)
+ super
+ end
+ end
+ end
end
diff --git a/activesupport/test/autoload_test.rb b/activesupport/test/autoload_test.rb
index c18b007612..216b069420 100644
--- a/activesupport/test/autoload_test.rb
+++ b/activesupport/test/autoload_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class TestAutoloadModule < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
@@ -31,7 +33,7 @@ class TestAutoloadModule < ActiveSupport::TestCase
end
end
- assert !$LOADED_FEATURES.include?(@some_class_path)
+ assert_not_includes $LOADED_FEATURES, @some_class_path
assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end
@@ -40,7 +42,7 @@ class TestAutoloadModule < ActiveSupport::TestCase
autoload :SomeClass
end
- assert !$LOADED_FEATURES.include?(@some_class_path)
+ assert_not_includes $LOADED_FEATURES, @some_class_path
assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end
@@ -51,9 +53,9 @@ class TestAutoloadModule < ActiveSupport::TestCase
end
end
- assert !$LOADED_FEATURES.include?(@some_class_path)
+ assert_not_includes $LOADED_FEATURES, @some_class_path
::Fixtures::Autoload.eager_load!
- assert $LOADED_FEATURES.include?(@some_class_path)
+ assert_includes $LOADED_FEATURES, @some_class_path
assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end
@@ -64,7 +66,7 @@ class TestAutoloadModule < ActiveSupport::TestCase
end
end
- assert !$LOADED_FEATURES.include?(@another_class_path)
+ assert_not_includes $LOADED_FEATURES, @another_class_path
assert_nothing_raised { ::Fixtures::AnotherClass }
end
@@ -75,7 +77,7 @@ class TestAutoloadModule < ActiveSupport::TestCase
end
end
- assert !$LOADED_FEATURES.include?(@another_class_path)
+ assert_not_includes $LOADED_FEATURES, @another_class_path
assert_nothing_raised { ::Fixtures::AnotherClass }
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/a/b.rb b/activesupport/test/autoloading_fixtures/a/b.rb
index 9c9e6454cf..27baaea08c 100644
--- a/activesupport/test/autoloading_fixtures/a/b.rb
+++ b/activesupport/test/autoloading_fixtures/a/b.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class A::B
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/a/c/d.rb b/activesupport/test/autoloading_fixtures/a/c/d.rb
index 0f40d6fbc4..f07128673f 100644
--- a/activesupport/test/autoloading_fixtures/a/c/d.rb
+++ b/activesupport/test/autoloading_fixtures/a/c/d.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class A::C::D
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/a/c/em/f.rb b/activesupport/test/autoloading_fixtures/a/c/em/f.rb
index 8b28e19148..78c96cf45f 100644
--- a/activesupport/test/autoloading_fixtures/a/c/em/f.rb
+++ b/activesupport/test/autoloading_fixtures/a/c/em/f.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class A::C::EM::F
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/application.rb b/activesupport/test/autoloading_fixtures/application.rb
index d7d3096dcb..971cbe1b17 100644
--- a/activesupport/test/autoloading_fixtures/application.rb
+++ b/activesupport/test/autoloading_fixtures/application.rb
@@ -1 +1,3 @@
+# frozen_string_literal: true
+
ApplicationController = 10
diff --git a/activesupport/test/autoloading_fixtures/circular1.rb b/activesupport/test/autoloading_fixtures/circular1.rb
index a45761f066..7f891b5eb1 100644
--- a/activesupport/test/autoloading_fixtures/circular1.rb
+++ b/activesupport/test/autoloading_fixtures/circular1.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
silence_warnings do
Circular2
end
diff --git a/activesupport/test/autoloading_fixtures/circular2.rb b/activesupport/test/autoloading_fixtures/circular2.rb
index c847fa5001..1fdb4c261f 100644
--- a/activesupport/test/autoloading_fixtures/circular2.rb
+++ b/activesupport/test/autoloading_fixtures/circular2.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
Circular1
class Circular2
diff --git a/activesupport/test/autoloading_fixtures/class_folder.rb b/activesupport/test/autoloading_fixtures/class_folder.rb
index ad2b27be61..ff0826c298 100644
--- a/activesupport/test/autoloading_fixtures/class_folder.rb
+++ b/activesupport/test/autoloading_fixtures/class_folder.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class ClassFolder
- ConstantInClassFolder = 'indeed'
+ ConstantInClassFolder = "indeed"
end
diff --git a/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb b/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb
index 402609c583..cd901e9d71 100644
--- a/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb
+++ b/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class ClassFolder::ClassFolderSubclass < ClassFolder
- ConstantInClassFolder = 'indeed'
+ ConstantInClassFolder = "indeed"
end
diff --git a/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb b/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb
index 8235e90724..960bfcbc70 100644
--- a/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb
+++ b/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class ClassFolder::InlineClass
end
diff --git a/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb b/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
index 57a13d89ea..98426b797d 100644
--- a/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
+++ b/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class ClassFolder
class NestedClass
end
diff --git a/activesupport/test/autoloading_fixtures/conflict.rb b/activesupport/test/autoloading_fixtures/conflict.rb
index 4ac6201902..c5d3f6bdc0 100644
--- a/activesupport/test/autoloading_fixtures/conflict.rb
+++ b/activesupport/test/autoloading_fixtures/conflict.rb
@@ -1 +1,3 @@
-Conflict = 2 \ No newline at end of file
+# frozen_string_literal: true
+
+Conflict = 2
diff --git a/activesupport/test/autoloading_fixtures/counting_loader.rb b/activesupport/test/autoloading_fixtures/counting_loader.rb
index 4225c4412c..6ac3a9828d 100644
--- a/activesupport/test/autoloading_fixtures/counting_loader.rb
+++ b/activesupport/test/autoloading_fixtures/counting_loader.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
$counting_loaded_times ||= 0
$counting_loaded_times += 1
diff --git a/activesupport/test/autoloading_fixtures/cross_site_dependency.rb b/activesupport/test/autoloading_fixtures/cross_site_dependency.rb
index 21ee554e92..8a18dcff10 100644
--- a/activesupport/test/autoloading_fixtures/cross_site_dependency.rb
+++ b/activesupport/test/autoloading_fixtures/cross_site_dependency.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class CrossSiteDependency
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/d.rb b/activesupport/test/autoloading_fixtures/d.rb
index 45c794d4ca..72752d878e 100644
--- a/activesupport/test/autoloading_fixtures/d.rb
+++ b/activesupport/test/autoloading_fixtures/d.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class D
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/em.rb b/activesupport/test/autoloading_fixtures/em.rb
index 16a1838667..2e0ac9a6f9 100644
--- a/activesupport/test/autoloading_fixtures/em.rb
+++ b/activesupport/test/autoloading_fixtures/em.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class EM
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/html/some_class.rb b/activesupport/test/autoloading_fixtures/html/some_class.rb
index b43d15d891..fbbfd4a214 100644
--- a/activesupport/test/autoloading_fixtures/html/some_class.rb
+++ b/activesupport/test/autoloading_fixtures/html/some_class.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module HTML
class SomeClass
end
diff --git a/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb b/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb
index e3d1218c96..8735ce87e1 100644
--- a/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb
+++ b/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: true
+
module LoadedConstant
end
-
diff --git a/activesupport/test/autoloading_fixtures/loads_constant.rb b/activesupport/test/autoloading_fixtures/loads_constant.rb
index 0b30dc8bca..0bb434a956 100644
--- a/activesupport/test/autoloading_fixtures/loads_constant.rb
+++ b/activesupport/test/autoloading_fixtures/loads_constant.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module LoadsConstant
end
diff --git a/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb b/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb
index ca83437046..c11246b528 100644
--- a/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb
+++ b/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class ModuleFolder::InlineClass
end
diff --git a/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb b/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb
index fc4076bd0a..69226b405c 100644
--- a/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb
+++ b/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module ModuleFolder
class NestedClass
end
diff --git a/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb b/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb
index 80244b8bab..30de83af11 100644
--- a/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb
+++ b/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class ModuleFolder::NestedSibling
-end \ No newline at end of file
+end
diff --git a/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb b/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb
index d12d02f3aa..f688c1ef35 100644
--- a/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb
+++ b/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb
@@ -1 +1,3 @@
-ModuleWithCustomConstMissing::A::B = "10" \ No newline at end of file
+# frozen_string_literal: true
+
+ModuleWithCustomConstMissing::A::B = "10"
diff --git a/activesupport/test/autoloading_fixtures/multiple_constant_file.rb b/activesupport/test/autoloading_fixtures/multiple_constant_file.rb
index a9ff4eb89c..1da26e6c2c 100644
--- a/activesupport/test/autoloading_fixtures/multiple_constant_file.rb
+++ b/activesupport/test/autoloading_fixtures/multiple_constant_file.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
MultipleConstantFile = 10
SiblingConstant = MultipleConstantFile * 2
diff --git a/activesupport/test/autoloading_fixtures/prepend.rb b/activesupport/test/autoloading_fixtures/prepend.rb
new file mode 100644
index 0000000000..bf9e36e12c
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/prepend.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+class SubClassConflict
+end
+
+class Prepend
+ module PrependedModule
+ end
+ prepend PrependedModule
+end
diff --git a/activesupport/test/autoloading_fixtures/prepend/sub_class_conflict.rb b/activesupport/test/autoloading_fixtures/prepend/sub_class_conflict.rb
new file mode 100644
index 0000000000..506c3c5920
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/prepend/sub_class_conflict.rb
@@ -0,0 +1,4 @@
+# frozen_string_literal: true
+
+class Prepend::SubClassConflict
+end
diff --git a/activesupport/test/autoloading_fixtures/raises_arbitrary_exception.rb b/activesupport/test/autoloading_fixtures/raises_arbitrary_exception.rb
index 3ca4213c71..118ee6bdd1 100644
--- a/activesupport/test/autoloading_fixtures/raises_arbitrary_exception.rb
+++ b/activesupport/test/autoloading_fixtures/raises_arbitrary_exception.rb
@@ -1,4 +1,6 @@
+# frozen_string_literal: true
+
RaisesArbitraryException = 1
_ = A::B # Autoloading recursion, also expected to be watched and discarded.
-raise Exception, 'arbitray exception message'
+raise Exception, "arbitrary exception message"
diff --git a/activesupport/test/autoloading_fixtures/raises_name_error.rb b/activesupport/test/autoloading_fixtures/raises_name_error.rb
index a49960abf0..c23afb7b12 100644
--- a/activesupport/test/autoloading_fixtures/raises_name_error.rb
+++ b/activesupport/test/autoloading_fixtures/raises_name_error.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class RaisesNameError
FooBarBaz
end
diff --git a/activesupport/test/autoloading_fixtures/raises_no_method_error.rb b/activesupport/test/autoloading_fixtures/raises_no_method_error.rb
index e1b8fce24a..1000ce1cf5 100644
--- a/activesupport/test/autoloading_fixtures/raises_no_method_error.rb
+++ b/activesupport/test/autoloading_fixtures/raises_no_method_error.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class RaisesNoMethodError
self.foobar_method_doesnt_exist
end
diff --git a/activesupport/test/autoloading_fixtures/requires_constant.rb b/activesupport/test/autoloading_fixtures/requires_constant.rb
index 14804a0de0..6e51998949 100644
--- a/activesupport/test/autoloading_fixtures/requires_constant.rb
+++ b/activesupport/test/autoloading_fixtures/requires_constant.rb
@@ -1,5 +1,6 @@
+# frozen_string_literal: true
+
require "loaded_constant"
module RequiresConstant
end
-
diff --git a/activesupport/test/autoloading_fixtures/should_not_be_required.rb b/activesupport/test/autoloading_fixtures/should_not_be_required.rb
index 1fcf170cc5..8deffa1816 100644
--- a/activesupport/test/autoloading_fixtures/should_not_be_required.rb
+++ b/activesupport/test/autoloading_fixtures/should_not_be_required.rb
@@ -1 +1,3 @@
+# frozen_string_literal: true
+
ShouldNotBeAutoloaded = 0
diff --git a/activesupport/test/autoloading_fixtures/throws.rb b/activesupport/test/autoloading_fixtures/throws.rb
index e1d96cc512..b6fb391032 100644
--- a/activesupport/test/autoloading_fixtures/throws.rb
+++ b/activesupport/test/autoloading_fixtures/throws.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
Throws = 1
_ = A::B # Autoloading recursion, expected to be discarded.
diff --git a/activesupport/test/autoloading_fixtures/typo.rb b/activesupport/test/autoloading_fixtures/typo.rb
index 8e047f5fd4..d45cddbcf5 100644
--- a/activesupport/test/autoloading_fixtures/typo.rb
+++ b/activesupport/test/autoloading_fixtures/typo.rb
@@ -1,2 +1,3 @@
-TypO = 1
+# frozen_string_literal: true
+TypO = 1
diff --git a/activesupport/test/benchmarkable_test.rb b/activesupport/test/benchmarkable_test.rb
index 5af041f458..424da0a52c 100644
--- a/activesupport/test/benchmarkable_test.rb
+++ b/activesupport/test/benchmarkable_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class BenchmarkableTest < ActiveSupport::TestCase
include ActiveSupport::Benchmarkable
@@ -36,20 +38,20 @@ class BenchmarkableTest < ActiveSupport::TestCase
def test_with_message
i_was_run = false
- benchmark('test_run') { i_was_run = true }
+ benchmark("test_run") { i_was_run = true }
assert i_was_run
- assert_last_logged 'test_run'
+ assert_last_logged "test_run"
end
def test_with_silence
- assert_difference 'buffer.count', +2 do
- benchmark('test_run') do
+ assert_difference "buffer.count", +2 do
+ benchmark("test_run") do
logger.info "SOMETHING"
end
end
- assert_difference 'buffer.count', +1 do
- benchmark('test_run', silence: true) do
+ assert_difference "buffer.count", +1 do
+ benchmark("test_run", silence: true) do
logger.info "NOTHING"
end
end
@@ -57,20 +59,20 @@ class BenchmarkableTest < ActiveSupport::TestCase
def test_within_level
logger.level = ActiveSupport::Logger::DEBUG
- benchmark('included_debug_run', :level => :debug) { }
- assert_last_logged 'included_debug_run'
+ benchmark("included_debug_run", level: :debug) {}
+ assert_last_logged "included_debug_run"
end
def test_outside_level
logger.level = ActiveSupport::Logger::ERROR
- benchmark('skipped_debug_run', :level => :debug) { }
+ benchmark("skipped_debug_run", level: :debug) {}
assert_no_match(/skipped_debug_run/, buffer.last)
ensure
logger.level = ActiveSupport::Logger::DEBUG
end
private
- def assert_last_logged(message = 'Benchmarking')
+ def assert_last_logged(message = "Benchmarking")
assert_match(/^#{message} \(.*\)$/, buffer.last)
end
end
diff --git a/activesupport/test/broadcast_logger_test.rb b/activesupport/test/broadcast_logger_test.rb
index 6d4e3b74f7..181113e70a 100644
--- a/activesupport/test/broadcast_logger_test.rb
+++ b/activesupport/test/broadcast_logger_test.rb
@@ -1,82 +1,172 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
module ActiveSupport
class BroadcastLoggerTest < TestCase
attr_reader :logger, :log1, :log2
- def setup
+
+ setup do
@log1 = FakeLogger.new
@log2 = FakeLogger.new
@log1.extend Logger.broadcast @log2
@logger = @log1
end
- def test_debug
- logger.debug "foo"
- assert_equal 'foo', log1.adds.first[2]
- assert_equal 'foo', log2.adds.first[2]
+ Logger::Severity.constants.each do |level_name|
+ method = level_name.downcase
+ level = Logger::Severity.const_get(level_name)
+
+ test "##{method} adds the message to all loggers" do
+ logger.send(method, "msg")
+
+ assert_equal [level, "msg", nil], log1.adds.first
+ assert_equal [level, "msg", nil], log2.adds.first
+ end
end
- def test_close
+ test "#close broadcasts to all loggers" do
logger.close
- assert log1.closed, 'should be closed'
- assert log2.closed, 'should be closed'
+
+ assert log1.closed, "should be closed"
+ assert log2.closed, "should be closed"
end
- def test_chevrons
+ test "#<< shovels the value into all loggers" do
logger << "foo"
+
assert_equal %w{ foo }, log1.chevrons
assert_equal %w{ foo }, log2.chevrons
end
- def test_level
- assert_nil logger.level
- logger.level = 10
- assert_equal 10, log1.level
- assert_equal 10, log2.level
+ test "#level= assigns the level to all loggers" do
+ assert_equal ::Logger::DEBUG, logger.level
+ logger.level = ::Logger::FATAL
+
+ assert_equal ::Logger::FATAL, log1.level
+ assert_equal ::Logger::FATAL, log2.level
end
- def test_progname
+ test "#progname= assigns to all the loggers" do
assert_nil logger.progname
- logger.progname = 10
- assert_equal 10, log1.progname
- assert_equal 10, log2.progname
+ logger.progname = ::Logger::FATAL
+
+ assert_equal ::Logger::FATAL, log1.progname
+ assert_equal ::Logger::FATAL, log2.progname
end
- def test_formatter
+ test "#formatter= assigns to all the loggers" do
assert_nil logger.formatter
- logger.formatter = 10
- assert_equal 10, log1.formatter
- assert_equal 10, log2.formatter
+ logger.formatter = ::Logger::FATAL
+
+ assert_equal ::Logger::FATAL, log1.formatter
+ assert_equal ::Logger::FATAL, log2.formatter
+ end
+
+ test "#local_level= assigns the local_level to all loggers" do
+ assert_equal ::Logger::DEBUG, logger.local_level
+ logger.local_level = ::Logger::FATAL
+
+ assert_equal ::Logger::FATAL, log1.local_level
+ assert_equal ::Logger::FATAL, log2.local_level
+ end
+
+ test "#silence does not break custom loggers" do
+ new_logger = FakeLogger.new
+ custom_logger = CustomLogger.new
+ custom_logger.extend(Logger.broadcast(new_logger))
+
+ custom_logger.silence do
+ custom_logger.error "from error"
+ custom_logger.unknown "from unknown"
+ end
+
+ assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], custom_logger.adds
+ assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], new_logger.adds
+ end
+
+ test "#silence silences all loggers below the default level of ERROR" do
+ logger.silence do
+ logger.debug "test"
+ end
+
+ assert_equal [], log1.adds
+ assert_equal [], log2.adds
+ end
+
+ test "#silence does not silence at or above ERROR" do
+ logger.silence do
+ logger.error "from error"
+ logger.unknown "from unknown"
+ end
+
+ assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], log1.adds
+ assert_equal [[::Logger::ERROR, "from error", nil], [::Logger::UNKNOWN, "from unknown", nil]], log2.adds
end
- class FakeLogger
+ test "#silence allows you to override the silence level" do
+ logger.silence(::Logger::FATAL) do
+ logger.error "unseen"
+ logger.fatal "seen"
+ end
+
+ assert_equal [[::Logger::FATAL, "seen", nil]], log1.adds
+ assert_equal [[::Logger::FATAL, "seen", nil]], log2.adds
+ end
+
+ class CustomLogger
attr_reader :adds, :closed, :chevrons
- attr_accessor :level, :progname, :formatter
+ attr_accessor :level, :progname, :formatter, :local_level
def initialize
- @adds = []
- @closed = false
- @chevrons = []
- @level = nil
- @progname = nil
- @formatter = nil
+ @adds = []
+ @closed = false
+ @chevrons = []
+ @level = ::Logger::DEBUG
+ @local_level = ::Logger::DEBUG
+ @progname = nil
+ @formatter = nil
+ end
+
+ def debug(message, &block)
+ add(::Logger::DEBUG, message, &block)
end
- def debug msg, &block
- add(:omg, nil, msg, &block)
+ def info(message, &block)
+ add(::Logger::INFO, message, &block)
end
- def << x
+ def warn(message, &block)
+ add(::Logger::WARN, message, &block)
+ end
+
+ def error(message, &block)
+ add(::Logger::ERROR, message, &block)
+ end
+
+ def fatal(message, &block)
+ add(::Logger::FATAL, message, &block)
+ end
+
+ def unknown(message, &block)
+ add(::Logger::UNKNOWN, message, &block)
+ end
+
+ def <<(x)
@chevrons << x
end
- def add(*args)
- @adds << args
+ def add(message_level, message = nil, progname = nil, &block)
+ @adds << [message_level, message, progname] if message_level >= local_level
end
def close
@closed = true
end
end
+
+ class FakeLogger < CustomLogger
+ include LoggerSilence
+ end
end
end
diff --git a/activesupport/test/cache/behaviors.rb b/activesupport/test/cache/behaviors.rb
new file mode 100644
index 0000000000..cb08a10bba
--- /dev/null
+++ b/activesupport/test/cache/behaviors.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+require_relative "behaviors/autoloading_cache_behavior"
+require_relative "behaviors/cache_delete_matched_behavior"
+require_relative "behaviors/cache_increment_decrement_behavior"
+require_relative "behaviors/cache_store_behavior"
+require_relative "behaviors/cache_store_version_behavior"
+require_relative "behaviors/encoded_key_cache_behavior"
+require_relative "behaviors/local_cache_behavior"
diff --git a/activesupport/test/cache/behaviors/autoloading_cache_behavior.rb b/activesupport/test/cache/behaviors/autoloading_cache_behavior.rb
new file mode 100644
index 0000000000..b340eb6c48
--- /dev/null
+++ b/activesupport/test/cache/behaviors/autoloading_cache_behavior.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+require "dependencies_test_helpers"
+
+module AutoloadingCacheBehavior
+ include DependenciesTestHelpers
+
+ def test_simple_autoloading
+ with_autoloading_fixtures do
+ @cache.write("foo", EM.new)
+ end
+
+ remove_constants(:EM)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ assert_kind_of EM, @cache.read("foo")
+ end
+
+ remove_constants(:EM)
+ ActiveSupport::Dependencies.clear
+ end
+
+ def test_two_classes_autoloading
+ with_autoloading_fixtures do
+ @cache.write("foo", [EM.new, ClassFolder.new])
+ end
+
+ remove_constants(:EM, :ClassFolder)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ loaded = @cache.read("foo")
+ assert_kind_of Array, loaded
+ assert_equal 2, loaded.size
+ assert_kind_of EM, loaded[0]
+ assert_kind_of ClassFolder, loaded[1]
+ end
+
+ remove_constants(:EM, :ClassFolder)
+ ActiveSupport::Dependencies.clear
+ end
+end
diff --git a/activesupport/test/cache/behaviors/cache_delete_matched_behavior.rb b/activesupport/test/cache/behaviors/cache_delete_matched_behavior.rb
new file mode 100644
index 0000000000..6f59ce48d2
--- /dev/null
+++ b/activesupport/test/cache/behaviors/cache_delete_matched_behavior.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module CacheDeleteMatchedBehavior
+ def test_delete_matched
+ @cache.write("foo", "bar")
+ @cache.write("fu", "baz")
+ @cache.write("foo/bar", "baz")
+ @cache.write("fu/baz", "bar")
+ @cache.delete_matched(/oo/)
+ assert !@cache.exist?("foo")
+ assert @cache.exist?("fu")
+ assert !@cache.exist?("foo/bar")
+ assert @cache.exist?("fu/baz")
+ end
+end
diff --git a/activesupport/test/cache/behaviors/cache_increment_decrement_behavior.rb b/activesupport/test/cache/behaviors/cache_increment_decrement_behavior.rb
new file mode 100644
index 0000000000..16b7abc679
--- /dev/null
+++ b/activesupport/test/cache/behaviors/cache_increment_decrement_behavior.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module CacheIncrementDecrementBehavior
+ def test_increment
+ @cache.write("foo", 1, raw: true)
+ assert_equal 1, @cache.read("foo").to_i
+ assert_equal 2, @cache.increment("foo")
+ assert_equal 2, @cache.read("foo").to_i
+ assert_equal 3, @cache.increment("foo")
+ assert_equal 3, @cache.read("foo").to_i
+
+ missing = @cache.increment("bar")
+ assert(missing.nil? || missing == 1)
+ end
+
+ def test_decrement
+ @cache.write("foo", 3, raw: true)
+ assert_equal 3, @cache.read("foo").to_i
+ assert_equal 2, @cache.decrement("foo")
+ assert_equal 2, @cache.read("foo").to_i
+ assert_equal 1, @cache.decrement("foo")
+ assert_equal 1, @cache.read("foo").to_i
+
+ missing = @cache.decrement("bar")
+ assert(missing.nil? || missing == -1)
+ end
+end
diff --git a/activesupport/test/cache/behaviors/cache_store_behavior.rb b/activesupport/test/cache/behaviors/cache_store_behavior.rb
new file mode 100644
index 0000000000..bdc689b8b4
--- /dev/null
+++ b/activesupport/test/cache/behaviors/cache_store_behavior.rb
@@ -0,0 +1,353 @@
+# frozen_string_literal: true
+
+# Tests the base functionality that should be identical across all cache stores.
+module CacheStoreBehavior
+ def test_should_read_and_write_strings
+ assert @cache.write("foo", "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_should_overwrite
+ @cache.write("foo", "bar")
+ @cache.write("foo", "baz")
+ assert_equal "baz", @cache.read("foo")
+ end
+
+ def test_fetch_without_cache_miss
+ @cache.write("foo", "bar")
+ assert_not_called(@cache, :write) do
+ assert_equal "bar", @cache.fetch("foo") { "baz" }
+ end
+ end
+
+ def test_fetch_with_cache_miss
+ assert_called_with(@cache, :write, ["foo", "baz", @cache.options]) do
+ assert_equal "baz", @cache.fetch("foo") { "baz" }
+ end
+ end
+
+ def test_fetch_with_cache_miss_passes_key_to_block
+ cache_miss = false
+ assert_equal 3, @cache.fetch("foo") { |key| cache_miss = true; key.length }
+ assert cache_miss
+
+ cache_miss = false
+ assert_equal 3, @cache.fetch("foo") { |key| cache_miss = true; key.length }
+ assert !cache_miss
+ end
+
+ def test_fetch_with_forced_cache_miss
+ @cache.write("foo", "bar")
+ assert_not_called(@cache, :read) do
+ assert_called_with(@cache, :write, ["foo", "bar", @cache.options.merge(force: true)]) do
+ @cache.fetch("foo", force: true) { "bar" }
+ end
+ end
+ end
+
+ def test_fetch_with_cached_nil
+ @cache.write("foo", nil)
+ assert_not_called(@cache, :write) do
+ assert_nil @cache.fetch("foo") { "baz" }
+ end
+ end
+
+ def test_fetch_with_forced_cache_miss_with_block
+ @cache.write("foo", "bar")
+ assert_equal "foo_bar", @cache.fetch("foo", force: true) { "foo_bar" }
+ end
+
+ def test_fetch_with_forced_cache_miss_without_block
+ @cache.write("foo", "bar")
+ assert_raises(ArgumentError) do
+ @cache.fetch("foo", force: true)
+ end
+
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_should_read_and_write_hash
+ assert @cache.write("foo", a: "b")
+ assert_equal({ a: "b" }, @cache.read("foo"))
+ end
+
+ def test_should_read_and_write_integer
+ assert @cache.write("foo", 1)
+ assert_equal 1, @cache.read("foo")
+ end
+
+ def test_should_read_and_write_nil
+ assert @cache.write("foo", nil)
+ assert_nil @cache.read("foo")
+ end
+
+ def test_should_read_and_write_false
+ assert @cache.write("foo", false)
+ assert_equal false, @cache.read("foo")
+ end
+
+ def test_read_multi
+ @cache.write("foo", "bar")
+ @cache.write("fu", "baz")
+ @cache.write("fud", "biz")
+ assert_equal({ "foo" => "bar", "fu" => "baz" }, @cache.read_multi("foo", "fu"))
+ end
+
+ def test_read_multi_with_expires
+ time = Time.now
+ @cache.write("foo", "bar", expires_in: 10)
+ @cache.write("fu", "baz")
+ @cache.write("fud", "biz")
+ Time.stub(:now, time + 11) do
+ assert_equal({ "fu" => "baz" }, @cache.read_multi("foo", "fu"))
+ end
+ end
+
+ def test_fetch_multi
+ @cache.write("foo", "bar")
+ @cache.write("fud", "biz")
+
+ values = @cache.fetch_multi("foo", "fu", "fud") { |value| value * 2 }
+
+ assert_equal({ "foo" => "bar", "fu" => "fufu", "fud" => "biz" }, values)
+ assert_equal("fufu", @cache.read("fu"))
+ end
+
+ def test_multi_with_objects
+ cache_struct = Struct.new(:cache_key, :title)
+ foo = cache_struct.new("foo", "FOO!")
+ bar = cache_struct.new("bar")
+
+ @cache.write("bar", "BAM!")
+
+ values = @cache.fetch_multi(foo, bar) { |object| object.title }
+
+ assert_equal({ foo => "FOO!", bar => "BAM!" }, values)
+ end
+
+ def test_fetch_multi_without_block
+ assert_raises(ArgumentError) do
+ @cache.fetch_multi("foo")
+ end
+ end
+
+ def test_read_and_write_compressed_small_data
+ @cache.write("foo", "bar", compress: true)
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_read_and_write_compressed_large_data
+ @cache.write("foo", "bar", compress: true, compress_threshold: 2)
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_read_and_write_compressed_nil
+ @cache.write("foo", nil, compress: true)
+ assert_nil @cache.read("foo")
+ end
+
+ def test_read_and_write_uncompressed_small_data
+ @cache.write("foo", "bar", compress: false)
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_read_and_write_uncompressed_nil
+ @cache.write("foo", nil, compress: false)
+ assert_nil @cache.read("foo")
+ end
+
+ def test_cache_key
+ obj = Object.new
+ def obj.cache_key
+ :foo
+ end
+ @cache.write(obj, "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_param_as_cache_key
+ obj = Object.new
+ def obj.to_param
+ "foo"
+ end
+ @cache.write(obj, "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_unversioned_cache_key
+ obj = Object.new
+ def obj.cache_key
+ "foo"
+ end
+ def obj.cache_key_with_version
+ "foo-v1"
+ end
+ @cache.write(obj, "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_array_as_cache_key
+ @cache.write([:fu, "foo"], "bar")
+ assert_equal "bar", @cache.read("fu/foo")
+ end
+
+ def test_hash_as_cache_key
+ @cache.write({ foo: 1, fu: 2 }, "bar")
+ assert_equal "bar", @cache.read("foo=1/fu=2")
+ end
+
+ def test_keys_are_case_sensitive
+ @cache.write("foo", "bar")
+ assert_nil @cache.read("FOO")
+ end
+
+ def test_exist
+ @cache.write("foo", "bar")
+ assert_equal true, @cache.exist?("foo")
+ assert_equal false, @cache.exist?("bar")
+ end
+
+ def test_nil_exist
+ @cache.write("foo", nil)
+ assert @cache.exist?("foo")
+ end
+
+ def test_delete
+ @cache.write("foo", "bar")
+ assert @cache.exist?("foo")
+ assert @cache.delete("foo")
+ assert !@cache.exist?("foo")
+ end
+
+ def test_original_store_objects_should_not_be_immutable
+ bar = "bar".dup
+ @cache.write("foo", bar)
+ assert_nothing_raised { bar.gsub!(/.*/, "baz") }
+ end
+
+ def test_expires_in
+ time = Time.local(2008, 4, 24)
+
+ Time.stub(:now, time) do
+ @cache.write("foo", "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ Time.stub(:now, time + 30) do
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ Time.stub(:now, time + 61) do
+ assert_nil @cache.read("foo")
+ end
+ end
+
+ def test_race_condition_protection_skipped_if_not_defined
+ @cache.write("foo", "bar")
+ time = @cache.send(:read_entry, @cache.send(:normalize_key, "foo", {}), {}).expires_at
+
+ Time.stub(:now, Time.at(time)) do
+ result = @cache.fetch("foo") do
+ assert_nil @cache.read("foo")
+ "baz"
+ end
+ assert_equal "baz", result
+ end
+ end
+
+ def test_race_condition_protection_is_limited
+ time = Time.now
+ @cache.write("foo", "bar", expires_in: 60)
+ Time.stub(:now, time + 71) do
+ result = @cache.fetch("foo", race_condition_ttl: 10) do
+ assert_nil @cache.read("foo")
+ "baz"
+ end
+ assert_equal "baz", result
+ end
+ end
+
+ def test_race_condition_protection_is_safe
+ time = Time.now
+ @cache.write("foo", "bar", expires_in: 60)
+ Time.stub(:now, time + 61) do
+ begin
+ @cache.fetch("foo", race_condition_ttl: 10) do
+ assert_equal "bar", @cache.read("foo")
+ raise ArgumentError.new
+ end
+ rescue ArgumentError
+ end
+ assert_equal "bar", @cache.read("foo")
+ end
+ Time.stub(:now, time + 91) do
+ assert_nil @cache.read("foo")
+ end
+ end
+
+ def test_race_condition_protection
+ time = Time.now
+ @cache.write("foo", "bar", expires_in: 60)
+ Time.stub(:now, time + 61) do
+ result = @cache.fetch("foo", race_condition_ttl: 10) do
+ assert_equal "bar", @cache.read("foo")
+ "baz"
+ end
+ assert_equal "baz", result
+ end
+ end
+
+ def test_crazy_key_characters
+ crazy_key = "#/:*(<+=> )&$%@?;'\"\'`~-"
+ assert @cache.write(crazy_key, "1", raw: true)
+ assert_equal "1", @cache.read(crazy_key)
+ assert_equal "1", @cache.fetch(crazy_key)
+ assert @cache.delete(crazy_key)
+ assert_equal "2", @cache.fetch(crazy_key, raw: true) { "2" }
+ assert_equal 3, @cache.increment(crazy_key)
+ assert_equal 2, @cache.decrement(crazy_key)
+ end
+
+ def test_really_long_keys
+ key = "".dup
+ 900.times { key << "x" }
+ assert @cache.write(key, "bar")
+ assert_equal "bar", @cache.read(key)
+ assert_equal "bar", @cache.fetch(key)
+ assert_nil @cache.read("#{key}x")
+ assert_equal({ key => "bar" }, @cache.read_multi(key))
+ assert @cache.delete(key)
+ end
+
+ def test_cache_hit_instrumentation
+ key = "test_key"
+ @events = []
+ ActiveSupport::Notifications.subscribe "cache_read.active_support" do |*args|
+ @events << ActiveSupport::Notifications::Event.new(*args)
+ end
+ assert @cache.write(key, "1", raw: true)
+ assert @cache.fetch(key) {}
+ assert_equal 1, @events.length
+ assert_equal "cache_read.active_support", @events[0].name
+ assert_equal :fetch, @events[0].payload[:super_operation]
+ assert @events[0].payload[:hit]
+ ensure
+ ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
+ end
+
+ def test_cache_miss_instrumentation
+ @events = []
+ ActiveSupport::Notifications.subscribe(/^cache_(.*)\.active_support$/) do |*args|
+ @events << ActiveSupport::Notifications::Event.new(*args)
+ end
+ assert_not @cache.fetch("bad_key") {}
+ assert_equal 3, @events.length
+ assert_equal "cache_read.active_support", @events[0].name
+ assert_equal "cache_generate.active_support", @events[1].name
+ assert_equal "cache_write.active_support", @events[2].name
+ assert_equal :fetch, @events[0].payload[:super_operation]
+ assert_not @events[0].payload[:hit]
+ ensure
+ ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
+ end
+end
diff --git a/activesupport/test/cache/behaviors/cache_store_version_behavior.rb b/activesupport/test/cache/behaviors/cache_store_version_behavior.rb
new file mode 100644
index 0000000000..c2e4d046af
--- /dev/null
+++ b/activesupport/test/cache/behaviors/cache_store_version_behavior.rb
@@ -0,0 +1,88 @@
+# frozen_string_literal: true
+
+module CacheStoreVersionBehavior
+ ModelWithKeyAndVersion = Struct.new(:cache_key, :cache_version)
+
+ def test_fetch_with_right_version_should_hit
+ @cache.fetch("foo", version: 1) { "bar" }
+ assert_equal "bar", @cache.read("foo", version: 1)
+ end
+
+ def test_fetch_with_wrong_version_should_miss
+ @cache.fetch("foo", version: 1) { "bar" }
+ assert_nil @cache.read("foo", version: 2)
+ end
+
+ def test_read_with_right_version_should_hit
+ @cache.write("foo", "bar", version: 1)
+ assert_equal "bar", @cache.read("foo", version: 1)
+ end
+
+ def test_read_with_wrong_version_should_miss
+ @cache.write("foo", "bar", version: 1)
+ assert_nil @cache.read("foo", version: 2)
+ end
+
+ def test_exist_with_right_version_should_be_true
+ @cache.write("foo", "bar", version: 1)
+ assert @cache.exist?("foo", version: 1)
+ end
+
+ def test_exist_with_wrong_version_should_be_false
+ @cache.write("foo", "bar", version: 1)
+ assert !@cache.exist?("foo", version: 2)
+ end
+
+ def test_reading_and_writing_with_model_supporting_cache_version
+ m1v1 = ModelWithKeyAndVersion.new("model/1", 1)
+ m1v2 = ModelWithKeyAndVersion.new("model/1", 2)
+
+ @cache.write(m1v1, "bar")
+ assert_equal "bar", @cache.read(m1v1)
+ assert_nil @cache.read(m1v2)
+ end
+
+ def test_reading_and_writing_with_model_supporting_cache_version_using_nested_key
+ m1v1 = ModelWithKeyAndVersion.new("model/1", 1)
+ m1v2 = ModelWithKeyAndVersion.new("model/1", 2)
+
+ @cache.write([ "something", m1v1 ], "bar")
+ assert_equal "bar", @cache.read([ "something", m1v1 ])
+ assert_nil @cache.read([ "something", m1v2 ])
+ end
+
+ def test_fetching_with_model_supporting_cache_version
+ m1v1 = ModelWithKeyAndVersion.new("model/1", 1)
+ m1v2 = ModelWithKeyAndVersion.new("model/1", 2)
+
+ @cache.fetch(m1v1) { "bar" }
+ assert_equal "bar", @cache.fetch(m1v1) { "bu" }
+ assert_equal "bu", @cache.fetch(m1v2) { "bu" }
+ end
+
+ def test_exist_with_model_supporting_cache_version
+ m1v1 = ModelWithKeyAndVersion.new("model/1", 1)
+ m1v2 = ModelWithKeyAndVersion.new("model/1", 2)
+
+ @cache.write(m1v1, "bar")
+ assert @cache.exist?(m1v1)
+ assert_not @cache.fetch(m1v2)
+ end
+
+ def test_fetch_multi_with_model_supporting_cache_version
+ m1v1 = ModelWithKeyAndVersion.new("model/1", 1)
+ m2v1 = ModelWithKeyAndVersion.new("model/2", 1)
+ m2v2 = ModelWithKeyAndVersion.new("model/2", 2)
+
+ first_fetch_values = @cache.fetch_multi(m1v1, m2v1) { |m| m.cache_key }
+ second_fetch_values = @cache.fetch_multi(m1v1, m2v2) { |m| m.cache_key + " 2nd" }
+
+ assert_equal({ m1v1 => "model/1", m2v1 => "model/2" }, first_fetch_values)
+ assert_equal({ m1v1 => "model/1", m2v2 => "model/2 2nd" }, second_fetch_values)
+ end
+
+ def test_version_is_normalized
+ @cache.write("foo", "bar", version: 1)
+ assert_equal "bar", @cache.read("foo", version: "1")
+ end
+end
diff --git a/activesupport/test/cache/behaviors/encoded_key_cache_behavior.rb b/activesupport/test/cache/behaviors/encoded_key_cache_behavior.rb
new file mode 100644
index 0000000000..da16142496
--- /dev/null
+++ b/activesupport/test/cache/behaviors/encoded_key_cache_behavior.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+# https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters
+# The error is caused by character encodings that can't be compared with ASCII-8BIT regular expressions and by special
+# characters like the umlaut in UTF-8.
+module EncodedKeyCacheBehavior
+ Encoding.list.each do |encoding|
+ define_method "test_#{encoding.name.underscore}_encoded_values" do
+ key = "foo".dup.force_encoding(encoding)
+ assert @cache.write(key, "1", raw: true)
+ assert_equal "1", @cache.read(key)
+ assert_equal "1", @cache.fetch(key)
+ assert @cache.delete(key)
+ assert_equal "2", @cache.fetch(key, raw: true) { "2" }
+ assert_equal 3, @cache.increment(key)
+ assert_equal 2, @cache.decrement(key)
+ end
+ end
+
+ def test_common_utf8_values
+ key = "\xC3\xBCmlaut".dup.force_encoding(Encoding::UTF_8)
+ assert @cache.write(key, "1", raw: true)
+ assert_equal "1", @cache.read(key)
+ assert_equal "1", @cache.fetch(key)
+ assert @cache.delete(key)
+ assert_equal "2", @cache.fetch(key, raw: true) { "2" }
+ assert_equal 3, @cache.increment(key)
+ assert_equal 2, @cache.decrement(key)
+ end
+
+ def test_retains_encoding
+ key = "\xC3\xBCmlaut".dup.force_encoding(Encoding::UTF_8)
+ assert @cache.write(key, "1", raw: true)
+ assert_equal Encoding::UTF_8, key.encoding
+ end
+end
diff --git a/activesupport/test/cache/behaviors/local_cache_behavior.rb b/activesupport/test/cache/behaviors/local_cache_behavior.rb
new file mode 100644
index 0000000000..f7302df4c8
--- /dev/null
+++ b/activesupport/test/cache/behaviors/local_cache_behavior.rb
@@ -0,0 +1,132 @@
+# frozen_string_literal: true
+
+module LocalCacheBehavior
+ def test_local_writes_are_persistent_on_the_remote_cache
+ retval = @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ end
+ assert retval
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_clear_also_clears_local_cache
+ @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ @cache.clear
+ assert_nil @cache.read("foo")
+ end
+
+ assert_nil @cache.read("foo")
+ end
+
+ def test_cleanup_clears_local_cache_but_not_remote_cache
+ begin
+ @cache.cleanup
+ rescue NotImplementedError
+ skip
+ end
+
+ @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ assert_equal "bar", @cache.read("foo")
+
+ @cache.send(:bypass_local_cache) { @cache.write("foo", "baz") }
+ assert_equal "bar", @cache.read("foo")
+
+ @cache.cleanup
+ assert_equal "baz", @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_write
+ @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ @peek.delete("foo")
+ assert_equal "bar", @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_read
+ @cache.write("foo", "bar")
+ @cache.with_local_cache do
+ assert_equal "bar", @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_read_nil
+ @cache.with_local_cache do
+ assert_nil @cache.read("foo")
+ @cache.send(:bypass_local_cache) { @cache.write "foo", "bar" }
+ assert_nil @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_fetch
+ @cache.with_local_cache do
+ @cache.send(:local_cache).write "foo", "bar"
+ assert_equal "bar", @cache.send(:local_cache).fetch("foo")
+ end
+ end
+
+ def test_local_cache_of_write_nil
+ @cache.with_local_cache do
+ assert @cache.write("foo", nil)
+ assert_nil @cache.read("foo")
+ @peek.write("foo", "bar")
+ assert_nil @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_write_with_unless_exist
+ @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ @cache.write("foo", "baz", unless_exist: true)
+ assert_equal @peek.read("foo"), @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_delete
+ @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ @cache.delete("foo")
+ assert_nil @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_exist
+ @cache.with_local_cache do
+ @cache.write("foo", "bar")
+ @peek.delete("foo")
+ assert @cache.exist?("foo")
+ end
+ end
+
+ def test_local_cache_of_increment
+ @cache.with_local_cache do
+ @cache.write("foo", 1, raw: true)
+ @peek.write("foo", 2, raw: true)
+ @cache.increment("foo")
+ assert_equal 3, @cache.read("foo")
+ end
+ end
+
+ def test_local_cache_of_decrement
+ @cache.with_local_cache do
+ @cache.write("foo", 1, raw: true)
+ @peek.write("foo", 3, raw: true)
+ @cache.decrement("foo")
+ assert_equal 2, @cache.read("foo")
+ end
+ end
+
+ def test_middleware
+ app = lambda { |env|
+ result = @cache.write("foo", "bar")
+ assert_equal "bar", @cache.read("foo") # make sure 'foo' was written
+ assert result
+ [200, {}, []]
+ }
+ app = @cache.middleware.new(app)
+ app.call({})
+ end
+end
diff --git a/activesupport/test/cache/cache_entry_test.rb b/activesupport/test/cache/cache_entry_test.rb
new file mode 100644
index 0000000000..80ff7ad564
--- /dev/null
+++ b/activesupport/test/cache/cache_entry_test.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+
+class CacheEntryTest < ActiveSupport::TestCase
+ def test_expired
+ entry = ActiveSupport::Cache::Entry.new("value")
+ assert !entry.expired?, "entry not expired"
+ entry = ActiveSupport::Cache::Entry.new("value", expires_in: 60)
+ assert !entry.expired?, "entry not expired"
+ Time.stub(:now, Time.now + 61) do
+ assert entry.expired?, "entry is expired"
+ end
+ end
+
+ def test_compressed_values
+ value = "value" * 100
+ entry = ActiveSupport::Cache::Entry.new(value, compress: true, compress_threshold: 1)
+ assert_equal value, entry.value
+ assert(value.bytesize > entry.size, "value is compressed")
+ end
+
+ def test_compressed_by_default
+ value = "value" * 100
+ entry = ActiveSupport::Cache::Entry.new(value, compress_threshold: 1)
+ assert_equal value, entry.value
+ assert(value.bytesize > entry.size, "value is compressed")
+ end
+
+ def test_uncompressed_values
+ value = "value" * 100
+ entry = ActiveSupport::Cache::Entry.new(value, compress: false)
+ assert_equal value, entry.value
+ assert_equal value.bytesize, entry.size
+ end
+end
diff --git a/activesupport/test/cache/cache_key_test.rb b/activesupport/test/cache/cache_key_test.rb
new file mode 100644
index 0000000000..84e656f504
--- /dev/null
+++ b/activesupport/test/cache/cache_key_test.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+
+class CacheKeyTest < ActiveSupport::TestCase
+ def test_entry_legacy_optional_ivars
+ legacy = Class.new(ActiveSupport::Cache::Entry) do
+ def initialize(value, options = {})
+ @value = value
+ @expires_in = nil
+ @created_at = nil
+ super
+ end
+ end
+
+ entry = legacy.new "foo"
+ assert_equal "foo", entry.value
+ end
+
+ def test_expand_cache_key
+ assert_equal "1/2/true", ActiveSupport::Cache.expand_cache_key([1, "2", true])
+ assert_equal "name/1/2/true", ActiveSupport::Cache.expand_cache_key([1, "2", true], :name)
+ end
+
+ def test_expand_cache_key_with_rails_cache_id
+ with_env("RAILS_CACHE_ID" => "c99") do
+ assert_equal "c99/foo", ActiveSupport::Cache.expand_cache_key(:foo)
+ assert_equal "c99/foo", ActiveSupport::Cache.expand_cache_key([:foo])
+ assert_equal "c99/foo/bar", ActiveSupport::Cache.expand_cache_key([:foo, :bar])
+ assert_equal "nm/c99/foo", ActiveSupport::Cache.expand_cache_key(:foo, :nm)
+ assert_equal "nm/c99/foo", ActiveSupport::Cache.expand_cache_key([:foo], :nm)
+ assert_equal "nm/c99/foo/bar", ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
+ end
+ end
+
+ def test_expand_cache_key_with_rails_app_version
+ with_env("RAILS_APP_VERSION" => "rails3") do
+ assert_equal "rails3/foo", ActiveSupport::Cache.expand_cache_key(:foo)
+ end
+ end
+
+ def test_expand_cache_key_rails_cache_id_should_win_over_rails_app_version
+ with_env("RAILS_CACHE_ID" => "c99", "RAILS_APP_VERSION" => "rails3") do
+ assert_equal "c99/foo", ActiveSupport::Cache.expand_cache_key(:foo)
+ end
+ end
+
+ def test_expand_cache_key_respond_to_cache_key
+ key = "foo".dup
+ def key.cache_key
+ :foo_key
+ end
+ assert_equal "foo_key", ActiveSupport::Cache.expand_cache_key(key)
+ end
+
+ def test_expand_cache_key_array_with_something_that_responds_to_cache_key
+ key = "foo".dup
+ def key.cache_key
+ :foo_key
+ end
+ assert_equal "foo_key", ActiveSupport::Cache.expand_cache_key([key])
+ end
+
+ def test_expand_cache_key_of_nil
+ assert_equal "", ActiveSupport::Cache.expand_cache_key(nil)
+ end
+
+ def test_expand_cache_key_of_false
+ assert_equal "false", ActiveSupport::Cache.expand_cache_key(false)
+ end
+
+ def test_expand_cache_key_of_true
+ assert_equal "true", ActiveSupport::Cache.expand_cache_key(true)
+ end
+
+ def test_expand_cache_key_of_array_like_object
+ assert_equal "foo/bar/baz", ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum)
+ end
+
+ private
+
+ def with_env(kv)
+ old_values = {}
+ kv.each { |key, value| old_values[key], ENV[key] = ENV[key], value }
+ yield
+ ensure
+ old_values.each { |key, value| ENV[key] = value }
+ end
+end
diff --git a/activesupport/test/cache/cache_store_logger_test.rb b/activesupport/test/cache/cache_store_logger_test.rb
new file mode 100644
index 0000000000..1af6893cc9
--- /dev/null
+++ b/activesupport/test/cache/cache_store_logger_test.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+
+class CacheStoreLoggerTest < ActiveSupport::TestCase
+ def setup
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store)
+
+ @buffer = StringIO.new
+ @cache.logger = ActiveSupport::Logger.new(@buffer)
+ end
+
+ def test_logging
+ @cache.fetch("foo") { "bar" }
+ assert @buffer.string.present?
+ end
+
+ def test_log_with_string_namespace
+ @cache.fetch("foo", namespace: "string_namespace") { "bar" }
+ assert_match %r{string_namespace:foo}, @buffer.string
+ end
+
+ def test_log_with_proc_namespace
+ proc = Proc.new do
+ "proc_namespace"
+ end
+ @cache.fetch("foo", namespace: proc) { "bar" }
+ assert_match %r{proc_namespace:foo}, @buffer.string
+ end
+
+ def test_mute_logging
+ @cache.mute { @cache.fetch("foo") { "bar" } }
+ assert @buffer.string.blank?
+ end
+end
diff --git a/activesupport/test/cache/cache_store_namespace_test.rb b/activesupport/test/cache/cache_store_namespace_test.rb
new file mode 100644
index 0000000000..b52a61c500
--- /dev/null
+++ b/activesupport/test/cache/cache_store_namespace_test.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+
+class CacheStoreNamespaceTest < ActiveSupport::TestCase
+ def test_static_namespace
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, namespace: "tester")
+ cache.write("foo", "bar")
+ assert_equal "bar", cache.read("foo")
+ assert_equal "bar", cache.instance_variable_get(:@data)["tester:foo"].value
+ end
+
+ def test_proc_namespace
+ test_val = "tester"
+ proc = lambda { test_val }
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, namespace: proc)
+ cache.write("foo", "bar")
+ assert_equal "bar", cache.read("foo")
+ assert_equal "bar", cache.instance_variable_get(:@data)["tester:foo"].value
+ end
+
+ def test_delete_matched_key_start
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, namespace: "tester")
+ cache.write("foo", "bar")
+ cache.write("fu", "baz")
+ cache.delete_matched(/^fo/)
+ assert !cache.exist?("foo")
+ assert cache.exist?("fu")
+ end
+
+ def test_delete_matched_key
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, namespace: "foo")
+ cache.write("foo", "bar")
+ cache.write("fu", "baz")
+ cache.delete_matched(/OO/i)
+ assert !cache.exist?("foo")
+ assert cache.exist?("fu")
+ end
+end
diff --git a/activesupport/test/cache/cache_store_setting_test.rb b/activesupport/test/cache/cache_store_setting_test.rb
new file mode 100644
index 0000000000..368cb39f97
--- /dev/null
+++ b/activesupport/test/cache/cache_store_setting_test.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+require "dalli"
+
+class CacheStoreSettingTest < ActiveSupport::TestCase
+ def test_memory_store_gets_created_if_no_arguments_passed_to_lookup_store_method
+ store = ActiveSupport::Cache.lookup_store
+ assert_kind_of(ActiveSupport::Cache::MemoryStore, store)
+ end
+
+ def test_memory_store
+ store = ActiveSupport::Cache.lookup_store :memory_store
+ assert_kind_of(ActiveSupport::Cache::MemoryStore, store)
+ end
+
+ def test_file_fragment_cache_store
+ store = ActiveSupport::Cache.lookup_store :file_store, "/path/to/cache/directory"
+ assert_kind_of(ActiveSupport::Cache::FileStore, store)
+ assert_equal "/path/to/cache/directory", store.cache_path
+ end
+
+ def test_mem_cache_fragment_cache_store
+ assert_called_with(Dalli::Client, :new, [%w[localhost], {}]) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost"
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+ end
+
+ def test_mem_cache_fragment_cache_store_with_given_mem_cache
+ mem_cache = Dalli::Client.new
+ assert_not_called(Dalli::Client, :new) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+ end
+
+ def test_mem_cache_fragment_cache_store_with_not_dalli_client
+ assert_not_called(Dalli::Client, :new) do
+ memcache = Object.new
+ assert_raises(ArgumentError) do
+ ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
+ end
+ end
+ end
+
+ def test_mem_cache_fragment_cache_store_with_multiple_servers
+ assert_called_with(Dalli::Client, :new, [%w[localhost 192.168.1.1], {}]) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", "192.168.1.1"
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+ end
+
+ def test_mem_cache_fragment_cache_store_with_options
+ assert_called_with(Dalli::Client, :new, [%w[localhost 192.168.1.1], { timeout: 10 }]) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", "192.168.1.1", namespace: "foo", timeout: 10
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ assert_equal "foo", store.options[:namespace]
+ end
+ end
+
+ def test_object_assigned_fragment_cache_store
+ store = ActiveSupport::Cache.lookup_store ActiveSupport::Cache::FileStore.new("/path/to/cache/directory")
+ assert_kind_of(ActiveSupport::Cache::FileStore, store)
+ assert_equal "/path/to/cache/directory", store.cache_path
+ end
+end
diff --git a/activesupport/test/cache/cache_store_write_multi_test.rb b/activesupport/test/cache/cache_store_write_multi_test.rb
new file mode 100644
index 0000000000..5b6fd678c5
--- /dev/null
+++ b/activesupport/test/cache/cache_store_write_multi_test.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+
+class CacheStoreWriteMultiEntriesStoreProviderInterfaceTest < ActiveSupport::TestCase
+ setup do
+ @cache = ActiveSupport::Cache.lookup_store(:null_store)
+ end
+
+ test "fetch_multi uses write_multi_entries store provider interface" do
+ assert_called_with(@cache, :write_multi_entries) do
+ @cache.fetch_multi "a", "b", "c" do |key|
+ key * 2
+ end
+ end
+ end
+end
+
+class CacheStoreWriteMultiInstrumentationTest < ActiveSupport::TestCase
+ setup do
+ @cache = ActiveSupport::Cache.lookup_store(:null_store)
+ end
+
+ test "instrumentation" do
+ writes = { "a" => "aa", "b" => "bb" }
+
+ events = with_instrumentation "write_multi" do
+ @cache.write_multi(writes)
+ end
+
+ assert_equal %w[ cache_write_multi.active_support ], events.map(&:name)
+ assert_nil events[0].payload[:super_operation]
+ assert_equal({ "a" => "aa", "b" => "bb" }, events[0].payload[:key])
+ end
+
+ test "instrumentation with fetch_multi as super operation" do
+ skip "fetch_multi isn't instrumented yet"
+
+ events = with_instrumentation "write_multi" do
+ @cache.fetch_multi("a", "b") { |key| key * 2 }
+ end
+
+ assert_equal %w[ cache_write_multi.active_support ], events.map(&:name)
+ assert_nil events[0].payload[:super_operation]
+ assert !events[0].payload[:hit]
+ end
+
+ private
+ def with_instrumentation(method)
+ event_name = "cache_#{method}.active_support"
+
+ [].tap do |events|
+ ActiveSupport::Notifications.subscribe event_name do |*args|
+ events << ActiveSupport::Notifications::Event.new(*args)
+ end
+ yield
+ end
+ ensure
+ ActiveSupport::Notifications.unsubscribe event_name
+ end
+end
diff --git a/activesupport/test/cache/local_cache_middleware_test.rb b/activesupport/test/cache/local_cache_middleware_test.rb
new file mode 100644
index 0000000000..e59fae0b4c
--- /dev/null
+++ b/activesupport/test/cache/local_cache_middleware_test.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+
+module ActiveSupport
+ module Cache
+ module Strategy
+ module LocalCache
+ class MiddlewareTest < ActiveSupport::TestCase
+ def test_local_cache_cleared_on_close
+ key = "super awesome key"
+ assert_nil LocalCacheRegistry.cache_for key
+ middleware = Middleware.new("<3", key).new(->(env) {
+ assert LocalCacheRegistry.cache_for(key), "should have a cache"
+ [200, {}, []]
+ })
+ _, _, body = middleware.call({})
+ assert LocalCacheRegistry.cache_for(key), "should still have a cache"
+ body.each {}
+ assert LocalCacheRegistry.cache_for(key), "should still have a cache"
+ body.close
+ assert_nil LocalCacheRegistry.cache_for(key)
+ end
+
+ def test_local_cache_cleared_and_response_should_be_present_on_invalid_parameters_error
+ key = "super awesome key"
+ assert_nil LocalCacheRegistry.cache_for key
+ middleware = Middleware.new("<3", key).new(->(env) {
+ assert LocalCacheRegistry.cache_for(key), "should have a cache"
+ raise Rack::Utils::InvalidParameterError
+ })
+ response = middleware.call({})
+ assert response, "response should exist"
+ assert_nil LocalCacheRegistry.cache_for(key)
+ end
+
+ def test_local_cache_cleared_on_exception
+ key = "super awesome key"
+ assert_nil LocalCacheRegistry.cache_for key
+ middleware = Middleware.new("<3", key).new(->(env) {
+ assert LocalCacheRegistry.cache_for(key), "should have a cache"
+ raise
+ })
+ assert_raises(RuntimeError) { middleware.call({}) }
+ assert_nil LocalCacheRegistry.cache_for(key)
+ end
+
+ def test_local_cache_cleared_on_throw
+ key = "super awesome key"
+ assert_nil LocalCacheRegistry.cache_for key
+ middleware = Middleware.new("<3", key).new(->(env) {
+ assert LocalCacheRegistry.cache_for(key), "should have a cache"
+ throw :warden
+ })
+ assert_throws(:warden) { middleware.call({}) }
+ assert_nil LocalCacheRegistry.cache_for(key)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/test/cache/stores/file_store_test.rb b/activesupport/test/cache/stores/file_store_test.rb
new file mode 100644
index 0000000000..66231b0a82
--- /dev/null
+++ b/activesupport/test/cache/stores/file_store_test.rb
@@ -0,0 +1,131 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+require_relative "../behaviors"
+require "pathname"
+
+class FileStoreTest < ActiveSupport::TestCase
+ def setup
+ Dir.mkdir(cache_dir) unless File.exist?(cache_dir)
+ @cache = ActiveSupport::Cache.lookup_store(:file_store, cache_dir, expires_in: 60)
+ @peek = ActiveSupport::Cache.lookup_store(:file_store, cache_dir, expires_in: 60)
+ @cache_with_pathname = ActiveSupport::Cache.lookup_store(:file_store, Pathname.new(cache_dir), expires_in: 60)
+
+ @buffer = StringIO.new
+ @cache.logger = ActiveSupport::Logger.new(@buffer)
+ end
+
+ def teardown
+ FileUtils.rm_r(cache_dir)
+ rescue Errno::ENOENT
+ end
+
+ def cache_dir
+ File.join(Dir.pwd, "tmp_cache")
+ end
+
+ include CacheStoreBehavior
+ include CacheStoreVersionBehavior
+ include LocalCacheBehavior
+ include CacheDeleteMatchedBehavior
+ include CacheIncrementDecrementBehavior
+ include AutoloadingCacheBehavior
+
+ def test_clear
+ gitkeep = File.join(cache_dir, ".gitkeep")
+ keep = File.join(cache_dir, ".keep")
+ FileUtils.touch([gitkeep, keep])
+ @cache.clear
+ assert File.exist?(gitkeep)
+ assert File.exist?(keep)
+ end
+
+ def test_clear_without_cache_dir
+ FileUtils.rm_r(cache_dir)
+ @cache.clear
+ end
+
+ def test_long_uri_encoded_keys
+ @cache.write("%" * 870, 1)
+ assert_equal 1, @cache.read("%" * 870)
+ end
+
+ def test_key_transformation
+ key = @cache.send(:normalize_key, "views/index?id=1", {})
+ assert_equal "views/index?id=1", @cache.send(:file_path_key, key)
+ end
+
+ def test_key_transformation_with_pathname
+ FileUtils.touch(File.join(cache_dir, "foo"))
+ key = @cache_with_pathname.send(:normalize_key, "views/index?id=1", {})
+ assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
+ end
+
+ # Test that generated cache keys are short enough to have Tempfile stuff added to them and
+ # remain valid
+ def test_filename_max_size
+ key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}"
+ path = @cache.send(:normalize_key, key, {})
+ Dir::Tmpname.create(path) do |tmpname, n, opts|
+ assert File.basename(tmpname + ".lock").length <= 255, "Temp filename too long: #{File.basename(tmpname + '.lock').length}"
+ end
+ end
+
+ # Because file systems have a maximum filename size, filenames > max size should be split in to directories
+ # If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B
+ def test_key_transformation_max_filename_size
+ key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B"
+ path = @cache.send(:normalize_key, key, {})
+ assert path.split("/").all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE }
+ assert_equal "B", File.basename(path)
+ end
+
+ # If nothing has been stored in the cache, there is a chance the cache directory does not yet exist
+ # Ensure delete_matched gracefully handles this case
+ def test_delete_matched_when_cache_directory_does_not_exist
+ assert_nothing_raised do
+ ActiveSupport::Cache::FileStore.new("/test/cache/directory").delete_matched(/does_not_exist/)
+ end
+ end
+
+ def test_delete_does_not_delete_empty_parent_dir
+ sub_cache_dir = File.join(cache_dir, "subdir/")
+ sub_cache_store = ActiveSupport::Cache::FileStore.new(sub_cache_dir)
+ assert_nothing_raised do
+ assert sub_cache_store.write("foo", "bar")
+ assert sub_cache_store.delete("foo")
+ end
+ assert File.exist?(cache_dir), "Parent of top level cache dir was deleted!"
+ assert File.exist?(sub_cache_dir), "Top level cache dir was deleted!"
+ assert Dir.entries(sub_cache_dir).reject { |f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f) }.empty?
+ end
+
+ def test_log_exception_when_cache_read_fails
+ File.stub(:exist?, -> { raise StandardError.new("failed") }) do
+ @cache.send(:read_entry, "winston", {})
+ assert @buffer.string.present?
+ end
+ end
+
+ def test_cleanup_removes_all_expired_entries
+ time = Time.now
+ @cache.write("foo", "bar", expires_in: 10)
+ @cache.write("baz", "qux")
+ @cache.write("quux", "corge", expires_in: 20)
+ Time.stub(:now, time + 15) do
+ @cache.cleanup
+ assert_not @cache.exist?("foo")
+ assert @cache.exist?("baz")
+ assert @cache.exist?("quux")
+ assert_equal 2, Dir.glob(File.join(cache_dir, "**")).size
+ end
+ end
+
+ def test_write_with_unless_exist
+ assert_equal true, @cache.write(1, "aaaaaaaaaa")
+ assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
+ @cache.write(1, nil)
+ assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
+ end
+end
diff --git a/activesupport/test/cache/stores/mem_cache_store_test.rb b/activesupport/test/cache/stores/mem_cache_store_test.rb
new file mode 100644
index 0000000000..99624caf8a
--- /dev/null
+++ b/activesupport/test/cache/stores/mem_cache_store_test.rb
@@ -0,0 +1,92 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+require_relative "../behaviors"
+require "dalli"
+
+class MemCacheStoreTest < ActiveSupport::TestCase
+ begin
+ ss = Dalli::Client.new("localhost:11211").stats
+ raise Dalli::DalliError unless ss["localhost:11211"]
+
+ MEMCACHE_UP = true
+ rescue Dalli::DalliError
+ $stderr.puts "Skipping memcached tests. Start memcached and try again."
+ MEMCACHE_UP = false
+ end
+
+ def setup
+ skip "memcache server is not up" unless MEMCACHE_UP
+
+ @cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, expires_in: 60)
+ @peek = ActiveSupport::Cache.lookup_store(:mem_cache_store)
+ @data = @cache.instance_variable_get(:@data)
+ @cache.clear
+ @cache.silence!
+ @cache.logger = ActiveSupport::Logger.new(File::NULL)
+ end
+
+ include CacheStoreBehavior
+ include CacheStoreVersionBehavior
+ include LocalCacheBehavior
+ include CacheIncrementDecrementBehavior
+ include EncodedKeyCacheBehavior
+ include AutoloadingCacheBehavior
+
+ def test_raw_values
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
+ cache.clear
+ cache.write("foo", 2)
+ assert_equal "2", cache.read("foo")
+ end
+
+ def test_raw_values_with_marshal
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
+ cache.clear
+ cache.write("foo", Marshal.dump([]))
+ assert_equal [], cache.read("foo")
+ end
+
+ def test_local_cache_raw_values
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
+ cache.clear
+ cache.with_local_cache do
+ cache.write("foo", 2)
+ assert_equal "2", cache.read("foo")
+ end
+ end
+
+ def test_increment_expires_in
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
+ cache.clear
+ assert_called_with cache.instance_variable_get(:@data), :incr, [ "foo", 1, 60 ] do
+ cache.increment("foo", 1, expires_in: 60)
+ end
+ end
+
+ def test_decrement_expires_in
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
+ cache.clear
+ assert_called_with cache.instance_variable_get(:@data), :decr, [ "foo", 1, 60 ] do
+ cache.decrement("foo", 1, expires_in: 60)
+ end
+ end
+
+ def test_local_cache_raw_values_with_marshal
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
+ cache.clear
+ cache.with_local_cache do
+ cache.write("foo", Marshal.dump([]))
+ assert_equal [], cache.read("foo")
+ end
+ end
+
+ def test_read_should_return_a_different_object_id_each_time_it_is_called
+ @cache.write("foo", "bar")
+ value = @cache.read("foo")
+ assert_not_equal value.object_id, @cache.read("foo").object_id
+ value << "bingo"
+ assert_not_equal value, @cache.read("foo")
+ end
+end
diff --git a/activesupport/test/cache/stores/memory_store_test.rb b/activesupport/test/cache/stores/memory_store_test.rb
new file mode 100644
index 0000000000..3981f05331
--- /dev/null
+++ b/activesupport/test/cache/stores/memory_store_test.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+require_relative "../behaviors"
+
+class MemoryStoreTest < ActiveSupport::TestCase
+ def setup
+ @record_size = ActiveSupport::Cache.lookup_store(:memory_store).send(:cached_size, 1, ActiveSupport::Cache::Entry.new("aaaaaaaaaa"))
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store, expires_in: 60, size: @record_size * 10 + 1)
+ end
+
+ include CacheStoreBehavior
+ include CacheStoreVersionBehavior
+ include CacheDeleteMatchedBehavior
+ include CacheIncrementDecrementBehavior
+
+ def test_prune_size
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.read(2) && sleep(0.001)
+ @cache.read(4)
+ @cache.prune(@record_size * 3)
+ assert @cache.exist?(5)
+ assert @cache.exist?(4)
+ assert !@cache.exist?(3), "no entry"
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1), "no entry"
+ end
+
+ def test_prune_size_on_write
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.write(6, "ffffffffff") && sleep(0.001)
+ @cache.write(7, "gggggggggg") && sleep(0.001)
+ @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
+ @cache.write(9, "iiiiiiiiii") && sleep(0.001)
+ @cache.write(10, "kkkkkkkkkk") && sleep(0.001)
+ @cache.read(2) && sleep(0.001)
+ @cache.read(4) && sleep(0.001)
+ @cache.write(11, "llllllllll")
+ assert @cache.exist?(11)
+ assert @cache.exist?(10)
+ assert @cache.exist?(9)
+ assert @cache.exist?(8)
+ assert @cache.exist?(7)
+ assert !@cache.exist?(6), "no entry"
+ assert !@cache.exist?(5), "no entry"
+ assert @cache.exist?(4)
+ assert !@cache.exist?(3), "no entry"
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1), "no entry"
+ end
+
+ def test_prune_size_on_write_based_on_key_length
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.write(6, "ffffffffff") && sleep(0.001)
+ @cache.write(7, "gggggggggg") && sleep(0.001)
+ @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
+ @cache.write(9, "iiiiiiiiii") && sleep(0.001)
+ long_key = "*" * 2 * @record_size
+ @cache.write(long_key, "llllllllll")
+ assert @cache.exist?(long_key)
+ assert @cache.exist?(9)
+ assert @cache.exist?(8)
+ assert @cache.exist?(7)
+ assert @cache.exist?(6)
+ assert !@cache.exist?(5), "no entry"
+ assert !@cache.exist?(4), "no entry"
+ assert !@cache.exist?(3), "no entry"
+ assert !@cache.exist?(2), "no entry"
+ assert !@cache.exist?(1), "no entry"
+ end
+
+ def test_pruning_is_capped_at_a_max_time
+ def @cache.delete_entry(*args)
+ sleep(0.01)
+ super
+ end
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.prune(30, 0.001)
+ assert @cache.exist?(5)
+ assert @cache.exist?(4)
+ assert @cache.exist?(3)
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1)
+ end
+
+ def test_write_with_unless_exist
+ assert_equal true, @cache.write(1, "aaaaaaaaaa")
+ assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
+ @cache.write(1, nil)
+ assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
+ end
+end
diff --git a/activesupport/test/cache/stores/null_store_test.rb b/activesupport/test/cache/stores/null_store_test.rb
new file mode 100644
index 0000000000..a891cbffc8
--- /dev/null
+++ b/activesupport/test/cache/stores/null_store_test.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+require_relative "../behaviors"
+
+class NullStoreTest < ActiveSupport::TestCase
+ def setup
+ @cache = ActiveSupport::Cache.lookup_store(:null_store)
+ end
+
+ def test_clear
+ @cache.clear
+ end
+
+ def test_cleanup
+ @cache.cleanup
+ end
+
+ def test_write
+ assert_equal true, @cache.write("name", "value")
+ end
+
+ def test_read
+ @cache.write("name", "value")
+ assert_nil @cache.read("name")
+ end
+
+ def test_delete
+ @cache.write("name", "value")
+ assert_equal false, @cache.delete("name")
+ end
+
+ def test_increment
+ @cache.write("name", 1, raw: true)
+ assert_nil @cache.increment("name")
+ end
+
+ def test_decrement
+ @cache.write("name", 1, raw: true)
+ assert_nil @cache.increment("name")
+ end
+
+ def test_delete_matched
+ @cache.write("name", "value")
+ @cache.delete_matched(/name/)
+ end
+
+ def test_local_store_strategy
+ @cache.with_local_cache do
+ @cache.write("name", "value")
+ assert_equal "value", @cache.read("name")
+ @cache.delete("name")
+ assert_nil @cache.read("name")
+ @cache.write("name", "value")
+ end
+ assert_nil @cache.read("name")
+ end
+end
diff --git a/activesupport/test/cache/stores/redis_cache_store_test.rb b/activesupport/test/cache/stores/redis_cache_store_test.rb
new file mode 100644
index 0000000000..7f684f7a0f
--- /dev/null
+++ b/activesupport/test/cache/stores/redis_cache_store_test.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/cache"
+require "active_support/cache/redis_cache_store"
+require_relative "../behaviors"
+
+module ActiveSupport::Cache::RedisCacheStoreTests
+ class LookupTest < ActiveSupport::TestCase
+ test "may be looked up as :redis_cache_store" do
+ assert_kind_of ActiveSupport::Cache::RedisCacheStore,
+ ActiveSupport::Cache.lookup_store(:redis_cache_store)
+ end
+ end
+
+ class InitializationTest < ActiveSupport::TestCase
+ test "omitted URL uses Redis client with default settings" do
+ assert_called_with Redis, :new, [
+ url: nil,
+ connect_timeout: 20, read_timeout: 1, write_timeout: 1,
+ reconnect_attempts: 0,
+ ] do
+ build
+ end
+ end
+
+ test "no URLs uses Redis client with default settings" do
+ assert_called_with Redis, :new, [
+ url: nil,
+ connect_timeout: 20, read_timeout: 1, write_timeout: 1,
+ reconnect_attempts: 0,
+ ] do
+ build url: []
+ end
+ end
+
+ test "singular URL uses Redis client" do
+ assert_called_with Redis, :new, [
+ url: "redis://localhost:6379/0",
+ connect_timeout: 20, read_timeout: 1, write_timeout: 1,
+ reconnect_attempts: 0,
+ ] do
+ build url: "redis://localhost:6379/0"
+ end
+ end
+
+ test "one URL uses Redis client" do
+ assert_called_with Redis, :new, [
+ url: "redis://localhost:6379/0",
+ connect_timeout: 20, read_timeout: 1, write_timeout: 1,
+ reconnect_attempts: 0,
+ ] do
+ build url: %w[ redis://localhost:6379/0 ]
+ end
+ end
+
+ test "multiple URLs uses Redis::Distributed client" do
+ assert_called_with Redis, :new, [
+ [ url: "redis://localhost:6379/0",
+ connect_timeout: 20, read_timeout: 1, write_timeout: 1,
+ reconnect_attempts: 0 ],
+ [ url: "redis://localhost:6379/1",
+ connect_timeout: 20, read_timeout: 1, write_timeout: 1,
+ reconnect_attempts: 0 ],
+ ], returns: Redis.new do
+ @cache = build url: %w[ redis://localhost:6379/0 redis://localhost:6379/1 ]
+ assert_kind_of ::Redis::Distributed, @cache.redis
+ end
+ end
+
+ test "block argument uses yielded client" do
+ block = -> { :custom_redis_client }
+ assert_called block, :call do
+ build redis: block
+ end
+ end
+
+ private
+ def build(**kwargs)
+ ActiveSupport::Cache::RedisCacheStore.new(**kwargs).tap do |cache|
+ cache.redis
+ end
+ end
+ end
+
+ class StoreTest < ActiveSupport::TestCase
+ setup do
+ @namespace = "namespace"
+
+ @cache = ActiveSupport::Cache::RedisCacheStore.new(timeout: 0.1, namespace: @namespace, expires_in: 60)
+ # @cache.logger = Logger.new($stdout) # For test debugging
+
+ # For LocalCacheBehavior tests
+ @peek = ActiveSupport::Cache::RedisCacheStore.new(timeout: 0.1, namespace: @namespace)
+ end
+
+ teardown do
+ @cache.clear
+ @cache.redis.disconnect!
+ end
+ end
+
+ class RedisCacheStoreCommonBehaviorTest < StoreTest
+ include CacheStoreBehavior
+ include CacheStoreVersionBehavior
+ include LocalCacheBehavior
+ include CacheIncrementDecrementBehavior
+ include AutoloadingCacheBehavior
+ end
+
+ # Separate test class so we can omit the namespace which causes expected,
+ # appropriate complaints about incompatible string encodings.
+ class KeyEncodingSafetyTest < StoreTest
+ include EncodedKeyCacheBehavior
+
+ setup do
+ @cache = ActiveSupport::Cache::RedisCacheStore.new(timeout: 0.1)
+ @cache.logger = nil
+ end
+ end
+
+ class StoreAPITest < StoreTest
+ end
+
+ class FailureSafetyTest < StoreTest
+ test "fetch read failure returns nil" do
+ end
+
+ test "fetch read failure does not attempt to write" do
+ end
+
+ test "write failure returns nil" do
+ end
+ end
+
+ class DeleteMatchedTest < StoreTest
+ test "deletes keys matching glob" do
+ @cache.write("foo", "bar")
+ @cache.write("fu", "baz")
+ @cache.delete_matched("foo*")
+ assert !@cache.exist?("foo")
+ assert @cache.exist?("fu")
+ end
+
+ test "fails with regexp matchers" do
+ assert_raise ArgumentError do
+ @cache.delete_matched(/OO/i)
+ end
+ end
+ end
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
deleted file mode 100644
index ec7d028d7e..0000000000
--- a/activesupport/test/caching_test.rb
+++ /dev/null
@@ -1,1194 +0,0 @@
-require 'logger'
-require 'abstract_unit'
-require 'active_support/cache'
-require 'dependencies_test_helpers'
-
-module ActiveSupport
- module Cache
- module Strategy
- module LocalCache
- class MiddlewareTest < ActiveSupport::TestCase
- def test_local_cache_cleared_on_close
- key = "super awesome key"
- assert_nil LocalCacheRegistry.cache_for key
- middleware = Middleware.new('<3', key).new(->(env) {
- assert LocalCacheRegistry.cache_for(key), 'should have a cache'
- [200, {}, []]
- })
- _, _, body = middleware.call({})
- assert LocalCacheRegistry.cache_for(key), 'should still have a cache'
- body.each { }
- assert LocalCacheRegistry.cache_for(key), 'should still have a cache'
- body.close
- assert_nil LocalCacheRegistry.cache_for(key)
- end
-
- def test_local_cache_cleared_on_exception
- key = "super awesome key"
- assert_nil LocalCacheRegistry.cache_for key
- middleware = Middleware.new('<3', key).new(->(env) {
- assert LocalCacheRegistry.cache_for(key), 'should have a cache'
- raise
- })
- assert_raises(RuntimeError) { middleware.call({}) }
- assert_nil LocalCacheRegistry.cache_for(key)
- end
- end
- end
- end
- end
-end
-
-class CacheKeyTest < ActiveSupport::TestCase
- def test_entry_legacy_optional_ivars
- legacy = Class.new(ActiveSupport::Cache::Entry) do
- def initialize(value, options = {})
- @value = value
- @expires_in = nil
- @created_at = nil
- super
- end
- end
-
- entry = legacy.new 'foo'
- assert_equal 'foo', entry.value
- end
-
- def test_expand_cache_key
- assert_equal '1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true])
- assert_equal 'name/1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true], :name)
- end
-
- def test_expand_cache_key_with_rails_cache_id
- with_env('RAILS_CACHE_ID' => 'c99') do
- assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
- assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key([:foo])
- assert_equal 'c99/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar])
- assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key(:foo, :nm)
- assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm)
- assert_equal 'nm/c99/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
- end
- end
-
- def test_expand_cache_key_with_rails_app_version
- with_env('RAILS_APP_VERSION' => 'rails3') do
- assert_equal 'rails3/foo', ActiveSupport::Cache.expand_cache_key(:foo)
- end
- end
-
- def test_expand_cache_key_rails_cache_id_should_win_over_rails_app_version
- with_env('RAILS_CACHE_ID' => 'c99', 'RAILS_APP_VERSION' => 'rails3') do
- assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
- end
- end
-
- def test_expand_cache_key_respond_to_cache_key
- key = 'foo'
- def key.cache_key
- :foo_key
- end
- assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key(key)
- end
-
- def test_expand_cache_key_array_with_something_that_responds_to_cache_key
- key = 'foo'
- def key.cache_key
- :foo_key
- end
- assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key([key])
- end
-
- def test_expand_cache_key_of_nil
- assert_equal '', ActiveSupport::Cache.expand_cache_key(nil)
- end
-
- def test_expand_cache_key_of_false
- assert_equal 'false', ActiveSupport::Cache.expand_cache_key(false)
- end
-
- def test_expand_cache_key_of_true
- assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true)
- end
-
- def test_expand_cache_key_of_array_like_object
- assert_equal 'foo/bar/baz', ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum)
- end
-
- private
-
- def with_env(kv)
- old_values = {}
- kv.each { |key, value| old_values[key], ENV[key] = ENV[key], value }
- yield
- ensure
- old_values.each { |key, value| ENV[key] = value}
- end
-end
-
-class CacheStoreSettingTest < ActiveSupport::TestCase
- def test_file_fragment_cache_store
- store = ActiveSupport::Cache.lookup_store :file_store, "/path/to/cache/directory"
- assert_kind_of(ActiveSupport::Cache::FileStore, store)
- assert_equal "/path/to/cache/directory", store.cache_path
- end
-
- def test_mem_cache_fragment_cache_store
- assert_called_with(Dalli::Client, :new, [%w[localhost], {}]) do
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost"
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
- end
- end
-
- def test_mem_cache_fragment_cache_store_with_given_mem_cache
- mem_cache = Dalli::Client.new
- assert_not_called(Dalli::Client, :new) do
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
- end
- end
-
- def test_mem_cache_fragment_cache_store_with_not_dalli_client
- assert_not_called(Dalli::Client, :new) do
- memcache = Object.new
- assert_raises(ArgumentError) do
- ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
- end
- end
- end
-
- def test_mem_cache_fragment_cache_store_with_multiple_servers
- assert_called_with(Dalli::Client, :new, [%w[localhost 192.168.1.1], {}]) do
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1'
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
- end
- end
-
- def test_mem_cache_fragment_cache_store_with_options
- assert_called_with(Dalli::Client, :new, [%w[localhost 192.168.1.1], { :timeout => 10 }]) do
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1', :namespace => 'foo', :timeout => 10
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
- assert_equal 'foo', store.options[:namespace]
- end
- end
-
- def test_object_assigned_fragment_cache_store
- store = ActiveSupport::Cache.lookup_store ActiveSupport::Cache::FileStore.new("/path/to/cache/directory")
- assert_kind_of(ActiveSupport::Cache::FileStore, store)
- assert_equal "/path/to/cache/directory", store.cache_path
- end
-end
-
-class CacheStoreNamespaceTest < ActiveSupport::TestCase
- def test_static_namespace
- cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => "tester")
- cache.write("foo", "bar")
- assert_equal "bar", cache.read("foo")
- assert_equal "bar", cache.instance_variable_get(:@data)["tester:foo"].value
- end
-
- def test_proc_namespace
- test_val = "tester"
- proc = lambda{test_val}
- cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => proc)
- cache.write("foo", "bar")
- assert_equal "bar", cache.read("foo")
- assert_equal "bar", cache.instance_variable_get(:@data)["tester:foo"].value
- end
-
- def test_delete_matched_key_start
- cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => "tester")
- cache.write("foo", "bar")
- cache.write("fu", "baz")
- cache.delete_matched(/^fo/)
- assert !cache.exist?("foo")
- assert cache.exist?("fu")
- end
-
- def test_delete_matched_key
- cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => "foo")
- cache.write("foo", "bar")
- cache.write("fu", "baz")
- cache.delete_matched(/OO/i)
- assert !cache.exist?("foo")
- assert cache.exist?("fu")
- end
-end
-
-# Tests the base functionality that should be identical across all cache stores.
-module CacheStoreBehavior
- def test_should_read_and_write_strings
- assert @cache.write('foo', 'bar')
- assert_equal 'bar', @cache.read('foo')
- end
-
- def test_should_overwrite
- @cache.write('foo', 'bar')
- @cache.write('foo', 'baz')
- assert_equal 'baz', @cache.read('foo')
- end
-
- def test_fetch_without_cache_miss
- @cache.write('foo', 'bar')
- assert_not_called(@cache, :write) do
- assert_equal 'bar', @cache.fetch('foo') { 'baz' }
- end
- end
-
- def test_fetch_with_cache_miss
- assert_called_with(@cache, :write, ['foo', 'baz', @cache.options]) do
- assert_equal 'baz', @cache.fetch('foo') { 'baz' }
- end
- end
-
- def test_fetch_with_cache_miss_passes_key_to_block
- cache_miss = false
- assert_equal 3, @cache.fetch('foo') { |key| cache_miss = true; key.length }
- assert cache_miss
-
- cache_miss = false
- assert_equal 3, @cache.fetch('foo') { |key| cache_miss = true; key.length }
- assert !cache_miss
- end
-
- def test_fetch_with_forced_cache_miss
- @cache.write('foo', 'bar')
- assert_not_called(@cache, :read) do
- assert_called_with(@cache, :write, ['foo', 'bar', @cache.options.merge(:force => true)]) do
- @cache.fetch('foo', :force => true) { 'bar' }
- end
- end
- end
-
- def test_fetch_with_cached_nil
- @cache.write('foo', nil)
- assert_not_called(@cache, :write) do
- assert_nil @cache.fetch('foo') { 'baz' }
- end
- end
-
- def test_fetch_with_forced_cache_miss_with_block
- @cache.write('foo', 'bar')
- assert_equal 'foo_bar', @cache.fetch('foo', force: true) { 'foo_bar' }
- end
-
- def test_fetch_with_forced_cache_miss_without_block
- @cache.write('foo', 'bar')
- assert_raises(ArgumentError) do
- @cache.fetch('foo', force: true)
- end
-
- assert_equal 'bar', @cache.read('foo')
- end
-
- def test_should_read_and_write_hash
- assert @cache.write('foo', {:a => "b"})
- assert_equal({:a => "b"}, @cache.read('foo'))
- end
-
- def test_should_read_and_write_integer
- assert @cache.write('foo', 1)
- assert_equal 1, @cache.read('foo')
- end
-
- def test_should_read_and_write_nil
- assert @cache.write('foo', nil)
- assert_equal nil, @cache.read('foo')
- end
-
- def test_should_read_and_write_false
- assert @cache.write('foo', false)
- assert_equal false, @cache.read('foo')
- end
-
- def test_read_multi
- @cache.write('foo', 'bar')
- @cache.write('fu', 'baz')
- @cache.write('fud', 'biz')
- assert_equal({"foo" => "bar", "fu" => "baz"}, @cache.read_multi('foo', 'fu'))
- end
-
- def test_read_multi_with_expires
- time = Time.now
- @cache.write('foo', 'bar', :expires_in => 10)
- @cache.write('fu', 'baz')
- @cache.write('fud', 'biz')
- Time.stub(:now, time + 11) do
- assert_equal({"fu" => "baz"}, @cache.read_multi('foo', 'fu'))
- end
- end
-
- def test_fetch_multi
- @cache.write('foo', 'bar')
- @cache.write('fud', 'biz')
-
- values = @cache.fetch_multi('foo', 'fu', 'fud') { |value| value * 2 }
-
- assert_equal({ 'foo' => 'bar', 'fu' => 'fufu', 'fud' => 'biz' }, values)
- assert_equal('fufu', @cache.read('fu'))
- end
-
- def test_multi_with_objects
- cache_struct = Struct.new(:cache_key, :title)
- foo = cache_struct.new('foo', 'FOO!')
- bar = cache_struct.new('bar')
-
- @cache.write('bar', 'BAM!')
-
- values = @cache.fetch_multi(foo, bar) { |object| object.title }
-
- assert_equal({ foo => 'FOO!', bar => 'BAM!' }, values)
- end
-
- def test_read_and_write_compressed_small_data
- @cache.write('foo', 'bar', :compress => true)
- assert_equal 'bar', @cache.read('foo')
- end
-
- def test_read_and_write_compressed_large_data
- @cache.write('foo', 'bar', :compress => true, :compress_threshold => 2)
- assert_equal 'bar', @cache.read('foo')
- end
-
- def test_read_and_write_compressed_nil
- @cache.write('foo', nil, :compress => true)
- assert_nil @cache.read('foo')
- end
-
- def test_cache_key
- obj = Object.new
- def obj.cache_key
- :foo
- end
- @cache.write(obj, "bar")
- assert_equal "bar", @cache.read("foo")
- end
-
- def test_param_as_cache_key
- obj = Object.new
- def obj.to_param
- "foo"
- end
- @cache.write(obj, "bar")
- assert_equal "bar", @cache.read("foo")
- end
-
- def test_array_as_cache_key
- @cache.write([:fu, "foo"], "bar")
- assert_equal "bar", @cache.read("fu/foo")
- end
-
- def test_hash_as_cache_key
- @cache.write({:foo => 1, :fu => 2}, "bar")
- assert_equal "bar", @cache.read("foo=1/fu=2")
- end
-
- def test_keys_are_case_sensitive
- @cache.write("foo", "bar")
- assert_nil @cache.read("FOO")
- end
-
- def test_exist
- @cache.write('foo', 'bar')
- assert_equal true, @cache.exist?('foo')
- assert_equal false, @cache.exist?('bar')
- end
-
- def test_nil_exist
- @cache.write('foo', nil)
- assert @cache.exist?('foo')
- end
-
- def test_delete
- @cache.write('foo', 'bar')
- assert @cache.exist?('foo')
- assert @cache.delete('foo')
- assert !@cache.exist?('foo')
- end
-
- def test_original_store_objects_should_not_be_immutable
- bar = 'bar'
- @cache.write('foo', bar)
- assert_nothing_raised { bar.gsub!(/.*/, 'baz') }
- end
-
- def test_expires_in
- time = Time.local(2008, 4, 24)
-
- Time.stub(:now, time) do
- @cache.write('foo', 'bar')
- assert_equal 'bar', @cache.read('foo')
- end
-
- Time.stub(:now, time + 30) do
- assert_equal 'bar', @cache.read('foo')
- end
-
- Time.stub(:now, time + 61) do
- assert_nil @cache.read('foo')
- end
- end
-
- def test_race_condition_protection_skipped_if_not_defined
- @cache.write('foo', 'bar')
- time = @cache.send(:read_entry, @cache.send(:normalize_key, 'foo', {}), {}).expires_at
-
- Time.stub(:now, Time.at(time)) do
- result = @cache.fetch('foo') do
- assert_equal nil, @cache.read('foo')
- 'baz'
- end
- assert_equal 'baz', result
- end
- end
-
- def test_race_condition_protection_is_limited
- time = Time.now
- @cache.write('foo', 'bar', :expires_in => 60)
- Time.stub(:now, time + 71) do
- result = @cache.fetch('foo', :race_condition_ttl => 10) do
- assert_equal nil, @cache.read('foo')
- "baz"
- end
- assert_equal "baz", result
- end
- end
-
- def test_race_condition_protection_is_safe
- time = Time.now
- @cache.write('foo', 'bar', :expires_in => 60)
- Time.stub(:now, time + 61) do
- begin
- @cache.fetch('foo', :race_condition_ttl => 10) do
- assert_equal 'bar', @cache.read('foo')
- raise ArgumentError.new
- end
- rescue ArgumentError
- end
- assert_equal "bar", @cache.read('foo')
- end
- Time.stub(:now, time + 91) do
- assert_nil @cache.read('foo')
- end
- end
-
- def test_race_condition_protection
- time = Time.now
- @cache.write('foo', 'bar', :expires_in => 60)
- Time.stub(:now, time + 61) do
- result = @cache.fetch('foo', :race_condition_ttl => 10) do
- assert_equal 'bar', @cache.read('foo')
- "baz"
- end
- assert_equal "baz", result
- end
- end
-
- def test_crazy_key_characters
- crazy_key = "#/:*(<+=> )&$%@?;'\"\'`~-"
- assert @cache.write(crazy_key, "1", :raw => true)
- assert_equal "1", @cache.read(crazy_key)
- assert_equal "1", @cache.fetch(crazy_key)
- assert @cache.delete(crazy_key)
- assert_equal "2", @cache.fetch(crazy_key, :raw => true) { "2" }
- assert_equal 3, @cache.increment(crazy_key)
- assert_equal 2, @cache.decrement(crazy_key)
- end
-
- def test_really_long_keys
- key = ""
- 900.times{key << "x"}
- assert @cache.write(key, "bar")
- assert_equal "bar", @cache.read(key)
- assert_equal "bar", @cache.fetch(key)
- assert_nil @cache.read("#{key}x")
- assert_equal({key => "bar"}, @cache.read_multi(key))
- assert @cache.delete(key)
- end
-
- def test_cache_hit_instrumentation
- key = "test_key"
- @events = []
- ActiveSupport::Notifications.subscribe "cache_read.active_support" do |*args|
- @events << ActiveSupport::Notifications::Event.new(*args)
- end
- assert @cache.write(key, "1", :raw => true)
- assert @cache.fetch(key) {}
- assert_equal 1, @events.length
- assert_equal 'cache_read.active_support', @events[0].name
- assert_equal :fetch, @events[0].payload[:super_operation]
- assert @events[0].payload[:hit]
- ensure
- ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
- end
-
- def test_cache_miss_instrumentation
- @events = []
- ActiveSupport::Notifications.subscribe(/^cache_(.*)\.active_support$/) do |*args|
- @events << ActiveSupport::Notifications::Event.new(*args)
- end
- assert_not @cache.fetch("bad_key") {}
- assert_equal 3, @events.length
- assert_equal 'cache_read.active_support', @events[0].name
- assert_equal 'cache_generate.active_support', @events[1].name
- assert_equal 'cache_write.active_support', @events[2].name
- assert_equal :fetch, @events[0].payload[:super_operation]
- assert_not @events[0].payload[:hit]
- ensure
- ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
- end
-
- def test_can_call_deprecated_namesaced_key
- assert_deprecated "`namespaced_key` is deprecated" do
- @cache.send(:namespaced_key, 111, {})
- end
- end
-end
-
-# https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters
-# The error is caused by character encodings that can't be compared with ASCII-8BIT regular expressions and by special
-# characters like the umlaut in UTF-8.
-module EncodedKeyCacheBehavior
- Encoding.list.each do |encoding|
- define_method "test_#{encoding.name.underscore}_encoded_values" do
- key = "foo".force_encoding(encoding)
- assert @cache.write(key, "1", :raw => true)
- assert_equal "1", @cache.read(key)
- assert_equal "1", @cache.fetch(key)
- assert @cache.delete(key)
- assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
- assert_equal 3, @cache.increment(key)
- assert_equal 2, @cache.decrement(key)
- end
- end
-
- def test_common_utf8_values
- key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
- assert @cache.write(key, "1", :raw => true)
- assert_equal "1", @cache.read(key)
- assert_equal "1", @cache.fetch(key)
- assert @cache.delete(key)
- assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
- assert_equal 3, @cache.increment(key)
- assert_equal 2, @cache.decrement(key)
- end
-
- def test_retains_encoding
- key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
- assert @cache.write(key, "1", :raw => true)
- assert_equal Encoding::UTF_8, key.encoding
- end
-end
-
-module CacheDeleteMatchedBehavior
- def test_delete_matched
- @cache.write("foo", "bar")
- @cache.write("fu", "baz")
- @cache.write("foo/bar", "baz")
- @cache.write("fu/baz", "bar")
- @cache.delete_matched(/oo/)
- assert !@cache.exist?("foo")
- assert @cache.exist?("fu")
- assert !@cache.exist?("foo/bar")
- assert @cache.exist?("fu/baz")
- end
-end
-
-module CacheIncrementDecrementBehavior
- def test_increment
- @cache.write('foo', 1, :raw => true)
- assert_equal 1, @cache.read('foo').to_i
- assert_equal 2, @cache.increment('foo')
- assert_equal 2, @cache.read('foo').to_i
- assert_equal 3, @cache.increment('foo')
- assert_equal 3, @cache.read('foo').to_i
- assert_nil @cache.increment('bar')
- end
-
- def test_decrement
- @cache.write('foo', 3, :raw => true)
- assert_equal 3, @cache.read('foo').to_i
- assert_equal 2, @cache.decrement('foo')
- assert_equal 2, @cache.read('foo').to_i
- assert_equal 1, @cache.decrement('foo')
- assert_equal 1, @cache.read('foo').to_i
- assert_nil @cache.decrement('bar')
- end
-end
-
-module LocalCacheBehavior
- def test_local_writes_are_persistent_on_the_remote_cache
- retval = @cache.with_local_cache do
- @cache.write('foo', 'bar')
- end
- assert retval
- assert_equal 'bar', @cache.read('foo')
- end
-
- def test_clear_also_clears_local_cache
- @cache.with_local_cache do
- @cache.write('foo', 'bar')
- @cache.clear
- assert_nil @cache.read('foo')
- end
-
- assert_nil @cache.read('foo')
- end
-
- def test_local_cache_of_write
- @cache.with_local_cache do
- @cache.write('foo', 'bar')
- @peek.delete('foo')
- assert_equal 'bar', @cache.read('foo')
- end
- end
-
- def test_local_cache_of_read
- @cache.write('foo', 'bar')
- @cache.with_local_cache do
- assert_equal 'bar', @cache.read('foo')
- end
- end
-
- def test_local_cache_of_read_nil
- @cache.with_local_cache do
- assert_equal nil, @cache.read('foo')
- @cache.send(:bypass_local_cache) { @cache.write 'foo', 'bar' }
- assert_equal nil, @cache.read('foo')
- end
- end
-
- def test_local_cache_fetch
- @cache.with_local_cache do
- @cache.send(:local_cache).write 'foo', 'bar'
- assert_equal 'bar', @cache.send(:local_cache).fetch('foo')
- end
- end
-
- def test_local_cache_of_write_nil
- @cache.with_local_cache do
- assert @cache.write('foo', nil)
- assert_nil @cache.read('foo')
- @peek.write('foo', 'bar')
- assert_nil @cache.read('foo')
- end
- end
-
- def test_local_cache_of_delete
- @cache.with_local_cache do
- @cache.write('foo', 'bar')
- @cache.delete('foo')
- assert_nil @cache.read('foo')
- end
- end
-
- def test_local_cache_of_exist
- @cache.with_local_cache do
- @cache.write('foo', 'bar')
- @peek.delete('foo')
- assert @cache.exist?('foo')
- end
- end
-
- def test_local_cache_of_increment
- @cache.with_local_cache do
- @cache.write('foo', 1, :raw => true)
- @peek.write('foo', 2, :raw => true)
- @cache.increment('foo')
- assert_equal 3, @cache.read('foo')
- end
- end
-
- def test_local_cache_of_decrement
- @cache.with_local_cache do
- @cache.write('foo', 1, :raw => true)
- @peek.write('foo', 3, :raw => true)
- @cache.decrement('foo')
- assert_equal 2, @cache.read('foo')
- end
- end
-
- def test_middleware
- app = lambda { |env|
- result = @cache.write('foo', 'bar')
- assert_equal 'bar', @cache.read('foo') # make sure 'foo' was written
- assert result
- [200, {}, []]
- }
- app = @cache.middleware.new(app)
- app.call({})
- end
-
- def test_can_call_deprecated_set_cache_value
- @cache.with_local_cache do
- assert_deprecated "`set_cache_value` is deprecated" do
- @cache.send(:set_cache_value, 1, 'foo', :ignored, {})
- end
- assert_equal 1, @cache.read('foo')
- end
- end
-end
-
-module AutoloadingCacheBehavior
- include DependenciesTestHelpers
- def test_simple_autoloading
- with_autoloading_fixtures do
- @cache.write('foo', EM.new)
- end
-
- remove_constants(:EM)
- ActiveSupport::Dependencies.clear
-
- with_autoloading_fixtures do
- assert_kind_of EM, @cache.read('foo')
- end
-
- remove_constants(:EM)
- ActiveSupport::Dependencies.clear
- end
-
- def test_two_classes_autoloading
- with_autoloading_fixtures do
- @cache.write('foo', [EM.new, ClassFolder.new])
- end
-
- remove_constants(:EM, :ClassFolder)
- ActiveSupport::Dependencies.clear
-
- with_autoloading_fixtures do
- loaded = @cache.read('foo')
- assert_kind_of Array, loaded
- assert_equal 2, loaded.size
- assert_kind_of EM, loaded[0]
- assert_kind_of ClassFolder, loaded[1]
- end
-
- remove_constants(:EM, :ClassFolder)
- ActiveSupport::Dependencies.clear
- end
-end
-
-class FileStoreTest < ActiveSupport::TestCase
- def setup
- Dir.mkdir(cache_dir) unless File.exist?(cache_dir)
- @cache = ActiveSupport::Cache.lookup_store(:file_store, cache_dir, :expires_in => 60)
- @peek = ActiveSupport::Cache.lookup_store(:file_store, cache_dir, :expires_in => 60)
- @cache_with_pathname = ActiveSupport::Cache.lookup_store(:file_store, Pathname.new(cache_dir), :expires_in => 60)
-
- @buffer = StringIO.new
- @cache.logger = ActiveSupport::Logger.new(@buffer)
- end
-
- def teardown
- FileUtils.rm_r(cache_dir)
- rescue Errno::ENOENT
- end
-
- def cache_dir
- File.join(Dir.pwd, 'tmp_cache')
- end
-
- include CacheStoreBehavior
- include LocalCacheBehavior
- include CacheDeleteMatchedBehavior
- include CacheIncrementDecrementBehavior
- include AutoloadingCacheBehavior
-
- def test_clear
- gitkeep = File.join(cache_dir, ".gitkeep")
- keep = File.join(cache_dir, ".keep")
- FileUtils.touch([gitkeep, keep])
- @cache.clear
- assert File.exist?(gitkeep)
- assert File.exist?(keep)
- end
-
- def test_clear_without_cache_dir
- FileUtils.rm_r(cache_dir)
- @cache.clear
- end
-
- def test_long_keys
- @cache.write("a"*10000, 1)
- assert_equal 1, @cache.read("a"*10000)
- end
-
- def test_long_uri_encoded_keys
- @cache.write("%"*870, 1)
- assert_equal 1, @cache.read("%"*870)
- end
-
- def test_key_transformation
- key = @cache.send(:normalize_key, "views/index?id=1", {})
- assert_equal "views/index?id=1", @cache.send(:file_path_key, key)
- end
-
- def test_key_transformation_with_pathname
- FileUtils.touch(File.join(cache_dir, "foo"))
- key = @cache_with_pathname.send(:normalize_key, "views/index?id=1", {})
- assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
- end
-
- # Test that generated cache keys are short enough to have Tempfile stuff added to them and
- # remain valid
- def test_filename_max_size
- key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}"
- path = @cache.send(:normalize_key, key, {})
- Dir::Tmpname.create(path) do |tmpname, n, opts|
- assert File.basename(tmpname+'.lock').length <= 255, "Temp filename too long: #{File.basename(tmpname+'.lock').length}"
- end
- end
-
- # Because file systems have a maximum filename size, filenames > max size should be split in to directories
- # If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B
- def test_key_transformation_max_filename_size
- key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B"
- path = @cache.send(:normalize_key, key, {})
- assert path.split('/').all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}
- assert_equal 'B', File.basename(path)
- end
-
- # If nothing has been stored in the cache, there is a chance the cache directory does not yet exist
- # Ensure delete_matched gracefully handles this case
- def test_delete_matched_when_cache_directory_does_not_exist
- assert_nothing_raised do
- ActiveSupport::Cache::FileStore.new('/test/cache/directory').delete_matched(/does_not_exist/)
- end
- end
-
- def test_delete_does_not_delete_empty_parent_dir
- sub_cache_dir = File.join(cache_dir, 'subdir/')
- sub_cache_store = ActiveSupport::Cache::FileStore.new(sub_cache_dir)
- assert_nothing_raised do
- assert sub_cache_store.write('foo', 'bar')
- assert sub_cache_store.delete('foo')
- end
- assert File.exist?(cache_dir), "Parent of top level cache dir was deleted!"
- assert File.exist?(sub_cache_dir), "Top level cache dir was deleted!"
- assert Dir.entries(sub_cache_dir).reject {|f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f)}.empty?
- end
-
- def test_log_exception_when_cache_read_fails
- File.stub(:exist?, -> { raise StandardError.new("failed") }) do
- @cache.send(:read_entry, "winston", {})
- assert @buffer.string.present?
- end
- end
-
- def test_cleanup_removes_all_expired_entries
- time = Time.now
- @cache.write('foo', 'bar', expires_in: 10)
- @cache.write('baz', 'qux')
- @cache.write('quux', 'corge', expires_in: 20)
- Time.stub(:now, time + 15) do
- @cache.cleanup
- assert_not @cache.exist?('foo')
- assert @cache.exist?('baz')
- assert @cache.exist?('quux')
- end
- end
-
- def test_write_with_unless_exist
- assert_equal true, @cache.write(1, "aaaaaaaaaa")
- assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
- @cache.write(1, nil)
- assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
- end
-
- def test_can_call_deprecated_key_file_path
- assert_deprecated "`key_file_path` is deprecated" do
- assert_equal 111, @cache.send(:key_file_path, 111)
- end
- end
-end
-
-class MemoryStoreTest < ActiveSupport::TestCase
- def setup
- @record_size = ActiveSupport::Cache.lookup_store(:memory_store).send(:cached_size, 1, ActiveSupport::Cache::Entry.new("aaaaaaaaaa"))
- @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10 + 1)
- end
-
- include CacheStoreBehavior
- include CacheDeleteMatchedBehavior
- include CacheIncrementDecrementBehavior
-
- def test_prune_size
- @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
- @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
- @cache.write(3, "cccccccccc") && sleep(0.001)
- @cache.write(4, "dddddddddd") && sleep(0.001)
- @cache.write(5, "eeeeeeeeee") && sleep(0.001)
- @cache.read(2) && sleep(0.001)
- @cache.read(4)
- @cache.prune(@record_size * 3)
- assert @cache.exist?(5)
- assert @cache.exist?(4)
- assert !@cache.exist?(3), "no entry"
- assert @cache.exist?(2)
- assert !@cache.exist?(1), "no entry"
- end
-
- def test_prune_size_on_write
- @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
- @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
- @cache.write(3, "cccccccccc") && sleep(0.001)
- @cache.write(4, "dddddddddd") && sleep(0.001)
- @cache.write(5, "eeeeeeeeee") && sleep(0.001)
- @cache.write(6, "ffffffffff") && sleep(0.001)
- @cache.write(7, "gggggggggg") && sleep(0.001)
- @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
- @cache.write(9, "iiiiiiiiii") && sleep(0.001)
- @cache.write(10, "kkkkkkkkkk") && sleep(0.001)
- @cache.read(2) && sleep(0.001)
- @cache.read(4) && sleep(0.001)
- @cache.write(11, "llllllllll")
- assert @cache.exist?(11)
- assert @cache.exist?(10)
- assert @cache.exist?(9)
- assert @cache.exist?(8)
- assert @cache.exist?(7)
- assert !@cache.exist?(6), "no entry"
- assert !@cache.exist?(5), "no entry"
- assert @cache.exist?(4)
- assert !@cache.exist?(3), "no entry"
- assert @cache.exist?(2)
- assert !@cache.exist?(1), "no entry"
- end
-
- def test_prune_size_on_write_based_on_key_length
- @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
- @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
- @cache.write(3, "cccccccccc") && sleep(0.001)
- @cache.write(4, "dddddddddd") && sleep(0.001)
- @cache.write(5, "eeeeeeeeee") && sleep(0.001)
- @cache.write(6, "ffffffffff") && sleep(0.001)
- @cache.write(7, "gggggggggg") && sleep(0.001)
- @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
- @cache.write(9, "iiiiiiiiii") && sleep(0.001)
- long_key = '*' * 2 * @record_size
- @cache.write(long_key, "llllllllll")
- assert @cache.exist?(long_key)
- assert @cache.exist?(9)
- assert @cache.exist?(8)
- assert @cache.exist?(7)
- assert @cache.exist?(6)
- assert !@cache.exist?(5), "no entry"
- assert !@cache.exist?(4), "no entry"
- assert !@cache.exist?(3), "no entry"
- assert !@cache.exist?(2), "no entry"
- assert !@cache.exist?(1), "no entry"
- end
-
- def test_pruning_is_capped_at_a_max_time
- def @cache.delete_entry (*args)
- sleep(0.01)
- super
- end
- @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
- @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
- @cache.write(3, "cccccccccc") && sleep(0.001)
- @cache.write(4, "dddddddddd") && sleep(0.001)
- @cache.write(5, "eeeeeeeeee") && sleep(0.001)
- @cache.prune(30, 0.001)
- assert @cache.exist?(5)
- assert @cache.exist?(4)
- assert @cache.exist?(3)
- assert @cache.exist?(2)
- assert !@cache.exist?(1)
- end
-
- def test_write_with_unless_exist
- assert_equal true, @cache.write(1, "aaaaaaaaaa")
- assert_equal false, @cache.write(1, "aaaaaaaaaa", :unless_exist => true)
- @cache.write(1, nil)
- assert_equal false, @cache.write(1, "aaaaaaaaaa", :unless_exist => true)
- end
-end
-
-class MemCacheStoreTest < ActiveSupport::TestCase
- require 'dalli'
-
- begin
- ss = Dalli::Client.new('localhost:11211').stats
- raise Dalli::DalliError unless ss['localhost:11211']
-
- MEMCACHE_UP = true
- rescue Dalli::DalliError
- $stderr.puts "Skipping memcached tests. Start memcached and try again."
- MEMCACHE_UP = false
- end
-
- def setup
- skip "memcache server is not up" unless MEMCACHE_UP
-
- @cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :expires_in => 60)
- @peek = ActiveSupport::Cache.lookup_store(:mem_cache_store)
- @data = @cache.instance_variable_get(:@data)
- @cache.clear
- @cache.silence!
- @cache.logger = ActiveSupport::Logger.new("/dev/null")
- end
-
- include CacheStoreBehavior
- include LocalCacheBehavior
- include CacheIncrementDecrementBehavior
- include EncodedKeyCacheBehavior
- include AutoloadingCacheBehavior
-
- def test_raw_values
- cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
- cache.clear
- cache.write("foo", 2)
- assert_equal "2", cache.read("foo")
- end
-
- def test_raw_values_with_marshal
- cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
- cache.clear
- cache.write("foo", Marshal.dump([]))
- assert_equal [], cache.read("foo")
- end
-
- def test_local_cache_raw_values
- cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
- cache.clear
- cache.with_local_cache do
- cache.write("foo", 2)
- assert_equal "2", cache.read("foo")
- end
- end
-
- def test_local_cache_raw_values_with_marshal
- cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
- cache.clear
- cache.with_local_cache do
- cache.write("foo", Marshal.dump([]))
- assert_equal [], cache.read("foo")
- end
- end
-
- def test_read_should_return_a_different_object_id_each_time_it_is_called
- @cache.write('foo', 'bar')
- value = @cache.read('foo')
- assert_not_equal value.object_id, @cache.read('foo').object_id
- value << 'bingo'
- assert_not_equal value, @cache.read('foo')
- end
-
- def test_can_call_deprecated_escape_key
- assert_deprecated "`escape_key` is deprecated" do
- assert_equal 111, @cache.send(:escape_key, 111)
- end
- end
-end
-
-class NullStoreTest < ActiveSupport::TestCase
- def setup
- @cache = ActiveSupport::Cache.lookup_store(:null_store)
- end
-
- def test_clear
- @cache.clear
- end
-
- def test_cleanup
- @cache.cleanup
- end
-
- def test_write
- assert_equal true, @cache.write("name", "value")
- end
-
- def test_read
- @cache.write("name", "value")
- assert_nil @cache.read("name")
- end
-
- def test_delete
- @cache.write("name", "value")
- assert_equal false, @cache.delete("name")
- end
-
- def test_increment
- @cache.write("name", 1, :raw => true)
- assert_nil @cache.increment("name")
- end
-
- def test_decrement
- @cache.write("name", 1, :raw => true)
- assert_nil @cache.increment("name")
- end
-
- def test_delete_matched
- @cache.write("name", "value")
- @cache.delete_matched(/name/)
- end
-
- def test_local_store_strategy
- @cache.with_local_cache do
- @cache.write("name", "value")
- assert_equal "value", @cache.read("name")
- @cache.delete("name")
- assert_nil @cache.read("name")
- @cache.write("name", "value")
- end
- assert_nil @cache.read("name")
- end
-end
-
-class CacheStoreLoggerTest < ActiveSupport::TestCase
- def setup
- @cache = ActiveSupport::Cache.lookup_store(:memory_store)
-
- @buffer = StringIO.new
- @cache.logger = ActiveSupport::Logger.new(@buffer)
- end
-
- def test_logging
- @cache.fetch('foo') { 'bar' }
- assert @buffer.string.present?
- end
-
- def test_log_with_string_namespace
- @cache.fetch('foo', {namespace: 'string_namespace'}) { 'bar' }
- assert_match %r{string_namespace:foo}, @buffer.string
- end
-
- def test_log_with_proc_namespace
- proc = Proc.new do
- "proc_namespace"
- end
- @cache.fetch('foo', {:namespace => proc}) { 'bar' }
- assert_match %r{proc_namespace:foo}, @buffer.string
- end
-
- def test_mute_logging
- @cache.mute { @cache.fetch('foo') { 'bar' } }
- assert @buffer.string.blank?
- end
-end
-
-class CacheEntryTest < ActiveSupport::TestCase
- def test_expired
- entry = ActiveSupport::Cache::Entry.new("value")
- assert !entry.expired?, 'entry not expired'
- entry = ActiveSupport::Cache::Entry.new("value", :expires_in => 60)
- assert !entry.expired?, 'entry not expired'
- Time.stub(:now, Time.now + 61) do
- assert entry.expired?, 'entry is expired'
- end
- end
-
- def test_compress_values
- value = "value" * 100
- entry = ActiveSupport::Cache::Entry.new(value, :compress => true, :compress_threshold => 1)
- assert_equal value, entry.value
- assert(value.bytesize > entry.size, "value is compressed")
- end
-
- def test_non_compress_values
- value = "value" * 100
- entry = ActiveSupport::Cache::Entry.new(value)
- assert_equal value, entry.value
- assert_equal value.bytesize, entry.size
- end
-end
diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb
index 1adfe4edf4..67813a749e 100644
--- a/activesupport/test/callback_inheritance_test.rb
+++ b/activesupport/test/callback_inheritance_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class GrandParent
include ActiveSupport::Callbacks
@@ -9,8 +11,8 @@ class GrandParent
end
define_callbacks :dispatch
- set_callback :dispatch, :before, :before1, :before2, :if => proc {|c| c.action_name == "index" || c.action_name == "update" }
- set_callback :dispatch, :after, :after1, :after2, :if => proc {|c| c.action_name == "update" || c.action_name == "delete" }
+ set_callback :dispatch, :before, :before1, :before2, if: proc { |c| c.action_name == "index" || c.action_name == "update" }
+ set_callback :dispatch, :after, :after1, :after2, if: proc { |c| c.action_name == "update" || c.action_name == "delete" }
def before1
@log << "before1"
@@ -37,12 +39,12 @@ class GrandParent
end
class Parent < GrandParent
- skip_callback :dispatch, :before, :before2, :unless => proc {|c| c.action_name == "update" }
- skip_callback :dispatch, :after, :after2, :unless => proc {|c| c.action_name == "delete" }
+ skip_callback :dispatch, :before, :before2, unless: proc { |c| c.action_name == "update" }
+ skip_callback :dispatch, :after, :after2, unless: proc { |c| c.action_name == "delete" }
end
class Child < GrandParent
- skip_callback :dispatch, :before, :before2, :unless => proc {|c| c.action_name == "update" }, :if => :state_open?
+ skip_callback :dispatch, :before, :before2, unless: proc { |c| c.action_name == "update" }, if: :state_open?
def state_open?
@state == :open
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
index a624473f46..30f1632460 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
module CallbacksTest
class Record
@@ -23,10 +25,6 @@ module CallbacksTest
method_name
end
- def callback_string(callback_method)
- "history << [#{callback_method.to_sym.inspect}, :string]"
- end
-
def callback_proc(callback_method)
Proc.new { |model| model.history << [callback_method, :proc] }
end
@@ -56,27 +54,30 @@ module CallbacksTest
end
class Person < Record
+ attr_accessor :save_fails
+
[:before_save, :after_save].each do |callback_method|
callback_method_sym = callback_method.to_sym
send(callback_method, callback_symbol(callback_method_sym))
- ActiveSupport::Deprecation.silence { send(callback_method, callback_string(callback_method_sym)) }
send(callback_method, callback_proc(callback_method_sym))
- send(callback_method, callback_object(callback_method_sym.to_s.gsub(/_save/, '')))
+ send(callback_method, callback_object(callback_method_sym.to_s.gsub(/_save/, "")))
send(callback_method, CallbackClass)
send(callback_method) { |model| model.history << [callback_method_sym, :block] }
end
def save
- run_callbacks :save
+ run_callbacks :save do
+ raise "inside save" if save_fails
+ end
end
end
class PersonSkipper < Person
- skip_callback :save, :before, :before_save_method, :if => :yes
- skip_callback :save, :after, :after_save_method, :unless => :yes
- skip_callback :save, :after, :after_save_method, :if => :no
- skip_callback :save, :before, :before_save_method, :unless => :no
- skip_callback :save, :before, CallbackClass , :if => :yes
+ skip_callback :save, :before, :before_save_method, if: :yes
+ skip_callback :save, :after, :after_save_method, unless: :yes
+ skip_callback :save, :after, :after_save_method, if: :no
+ skip_callback :save, :before, :before_save_method, unless: :no
+ skip_callback :save, :before, CallbackClass, if: :yes
def yes; true; end
def no; false; end
end
@@ -89,7 +90,7 @@ module CallbacksTest
define_callbacks :dispatch
- set_callback :dispatch, :before, :log, :unless => proc {|c| c.action_name == :index || c.action_name == :show }
+ set_callback :dispatch, :before, :log, unless: proc { |c| c.action_name == :index || c.action_name == :show }
set_callback :dispatch, :after, :log2
attr_reader :action_name, :logger
@@ -114,7 +115,7 @@ module CallbacksTest
end
class Child < ParentController
- skip_callback :dispatch, :before, :log, :if => proc {|c| c.action_name == :update}
+ skip_callback :dispatch, :before, :log, if: proc { |c| c.action_name == :update }
skip_callback :dispatch, :after, :log2
end
@@ -125,10 +126,10 @@ module CallbacksTest
super
end
- before_save Proc.new {|r| r.history << [:before_save, :starts_true, :if] }, :if => :starts_true
- before_save Proc.new {|r| r.history << [:before_save, :starts_false, :if] }, :if => :starts_false
- before_save Proc.new {|r| r.history << [:before_save, :starts_true, :unless] }, :unless => :starts_true
- before_save Proc.new {|r| r.history << [:before_save, :starts_false, :unless] }, :unless => :starts_false
+ before_save Proc.new { |r| r.history << [:before_save, :starts_true, :if] }, if: :starts_true
+ before_save Proc.new { |r| r.history << [:before_save, :starts_false, :if] }, if: :starts_false
+ before_save Proc.new { |r| r.history << [:before_save, :starts_true, :unless] }, unless: :starts_true
+ before_save Proc.new { |r| r.history << [:before_save, :starts_false, :unless] }, unless: :starts_false
def starts_true
if @@starts_true
@@ -181,27 +182,20 @@ module CallbacksTest
end
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 }
+ 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'
+ 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
# 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
+ 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
def yes; true; end
def other_yes; true; end
@@ -222,26 +216,64 @@ module CallbacksTest
define_callbacks :save
end
- class AroundPerson < MySuper
+ class MySlate < MySuper
attr_reader :history
+ attr_accessor :save_fails
- set_callback :save, :before, :nope, :if => :no
- set_callback :save, :before, :nope, :unless => :yes
- set_callback :save, :after, :tweedle
- ActiveSupport::Deprecation.silence { set_callback :save, :before, "tweedle_dee" }
- set_callback :save, :before, proc {|m| m.history << "yup" }
- set_callback :save, :before, :nope, :if => proc { false }
- set_callback :save, :before, :nope, :unless => proc { true }
- set_callback :save, :before, :yup, :if => proc { true }
- set_callback :save, :before, :yup, :unless => proc { false }
- set_callback :save, :around, :tweedle_dum
- set_callback :save, :around, :w0tyes, :if => :yes
- set_callback :save, :around, :w0tno, :if => :no
- set_callback :save, :around, :tweedle_deedle
+ def initialize
+ @history = []
+ end
+
+ def save
+ run_callbacks :save do
+ raise "inside save" if save_fails
+ @history << "running"
+ end
+ end
def no; false; end
def yes; true; end
+ def method_missing(sym, *)
+ case sym
+ when /^log_(.*)/
+ @history << $1
+ nil
+ when /^wrap_(.*)/
+ @history << "wrap_#$1"
+ yield
+ @history << "unwrap_#$1"
+ nil
+ when /^double_(.*)/
+ @history << "first_#$1"
+ yield
+ @history << "second_#$1"
+ yield
+ @history << "third_#$1"
+ else
+ super
+ end
+ end
+
+ def respond_to_missing?(sym)
+ sym =~ /^(log|wrap)_/ || super
+ end
+ end
+
+ class AroundPerson < MySlate
+ set_callback :save, :before, :nope, if: :no
+ set_callback :save, :before, :nope, unless: :yes
+ set_callback :save, :after, :tweedle
+ set_callback :save, :before, proc { |m| m.history << "yup" }
+ set_callback :save, :before, :nope, if: proc { false }
+ set_callback :save, :before, :nope, unless: proc { true }
+ set_callback :save, :before, :yup, if: proc { true }
+ set_callback :save, :before, :yup, unless: proc { false }
+ set_callback :save, :around, :tweedle_dum
+ set_callback :save, :around, :w0tyes, if: :yes
+ set_callback :save, :around, :w0tno, if: :no
+ set_callback :save, :around, :tweedle_deedle
+
def nope
@history << "boom"
end
@@ -261,10 +293,6 @@ module CallbacksTest
yield
end
- def tweedle_dee
- @history << "tweedle dee"
- end
-
def tweedle_dum
@history << "tweedle dum pre"
yield
@@ -280,16 +308,6 @@ module CallbacksTest
yield
@history << "tweedle deedle post"
end
-
- def initialize
- @history = []
- end
-
- def save
- run_callbacks :save do
- @history << "running"
- end
- end
end
class AroundPersonResult < MySuper
@@ -323,7 +341,7 @@ module CallbacksTest
define_callbacks :save
attr_reader :stuff
- set_callback :save, :before, :action, :if => :yes
+ set_callback :save, :before, :action, if: :yes
def yes() true end
@@ -361,7 +379,6 @@ module CallbacksTest
end
class ExtendCallbacks
-
include ActiveSupport::Callbacks
define_callbacks :save
@@ -391,7 +408,6 @@ module CallbacksTest
around = AroundPerson.new
around.save
assert_equal [
- "tweedle dee",
"yup", "yup",
"tweedle dum pre",
"w0tyes before",
@@ -405,6 +421,97 @@ module CallbacksTest
end
end
+ class DoubleYieldTest < ActiveSupport::TestCase
+ class DoubleYieldModel < MySlate
+ set_callback :save, :around, :wrap_outer
+ set_callback :save, :around, :double_trouble
+ set_callback :save, :around, :wrap_inner
+ end
+
+ def test_double_save
+ double = DoubleYieldModel.new
+ double.save
+ assert_equal [
+ "wrap_outer",
+ "first_trouble",
+ "wrap_inner",
+ "running",
+ "unwrap_inner",
+ "second_trouble",
+ "wrap_inner",
+ "running",
+ "unwrap_inner",
+ "third_trouble",
+ "unwrap_outer",
+ ], double.history
+ end
+ end
+
+ class CallStackTest < ActiveSupport::TestCase
+ def test_tidy_call_stack
+ around = AroundPerson.new
+ around.save_fails = true
+
+ exception = (around.save rescue $!)
+
+ # Make sure we have the exception we're expecting
+ assert_equal "inside save", exception.message
+
+ call_stack = exception.backtrace_locations
+ call_stack.pop caller_locations(0).size
+
+ # Yes, this looks like an implementation test, but it's the least
+ # obtuse way of asserting that there aren't a load of entries in
+ # the call stack for each callback.
+ #
+ # If you've renamed a method, or squeezed more lines out, go ahead
+ # and update this assertion. But if you're here because a
+ # refactoring added new lines, please reconsider.
+
+ # As shown here, our current budget is one line for run_callbacks
+ # itself, plus N+1 lines where N is the number of :around
+ # callbacks that have been invoked, if there are any (plus
+ # whatever the callbacks do themselves, of course).
+
+ assert_equal [
+ "block in save",
+ "block in run_callbacks",
+ "tweedle_deedle",
+ "block in run_callbacks",
+ "w0tyes",
+ "block in run_callbacks",
+ "tweedle_dum",
+ "block in run_callbacks",
+ ("call" if RUBY_VERSION < "2.3"),
+ "run_callbacks",
+ "save"
+ ].compact, call_stack.map(&:label)
+ end
+
+ def test_short_call_stack
+ person = Person.new
+ person.save_fails = true
+
+ exception = (person.save rescue $!)
+
+ # Make sure we have the exception we're expecting
+ assert_equal "inside save", exception.message
+
+ call_stack = exception.backtrace_locations
+ call_stack.pop caller_locations(0).size
+
+ # This budget much simpler: with no :around callbacks invoked,
+ # there should be just one line. run_callbacks yields directly
+ # back to its caller.
+
+ assert_equal [
+ "block in save",
+ "run_callbacks",
+ "save"
+ ], call_stack.map(&:label)
+ end
+ end
+
class AroundCallbackResultTest < ActiveSupport::TestCase
def test_save_around
around = AroundPersonResult.new
@@ -419,7 +526,6 @@ module CallbacksTest
assert_equal [], person.history
person.save
assert_equal [
- [:before_save, :string],
[:before_save, :proc],
[:before_save, :object],
[:before_save, :block],
@@ -427,7 +533,6 @@ module CallbacksTest
[:after_save, :class],
[:after_save, :object],
[:after_save, :proc],
- [:after_save, :string],
[:after_save, :symbol]
], person.history
end
@@ -446,21 +551,18 @@ module CallbacksTest
[:after_save, :class],
[:after_save, :object],
[:after_save, :proc],
- [:after_save, :string],
[:after_save, :symbol]
], person.history
end
end
class CallbacksTest < ActiveSupport::TestCase
-
def test_save_person
person = Person.new
assert_equal [], person.history
person.save
assert_equal [
[:before_save, :symbol],
- [:before_save, :string],
[:before_save, :proc],
[:before_save, :object],
[:before_save, :class],
@@ -469,7 +571,6 @@ module CallbacksTest
[:after_save, :class],
[:after_save, :object],
[:after_save, :proc],
- [:after_save, :string],
[:after_save, :symbol]
], person.history
end
@@ -484,15 +585,11 @@ module CallbacksTest
[:before_save, :proc],
[:before_save, :symbol],
[:before_save, :symbol],
- [:before_save, :string],
- [:before_save, :string],
[:before_save, :combined_symbol],
], person.history
end
end
-
-
class ResetCallbackTest < ActiveSupport::TestCase
def test_save_conditional_person
person = CleanPerson.new
@@ -637,7 +734,7 @@ module CallbacksTest
class CustomScopeObject
include ActiveSupport::Callbacks
- define_callbacks :save, :scope => [:kind, :name]
+ define_callbacks :save, scope: [:kind, :name]
set_callback :save, :before, CallbackObject.new
attr_accessor :record
@@ -765,37 +862,11 @@ module CallbacksTest
end
end
- class CallbackFalseTerminatorWithoutConfigTest < ActiveSupport::TestCase
- def test_returning_false_does_not_halt_callback_if_config_variable_is_not_set
+ class CallbackFalseTerminatorTest < ActiveSupport::TestCase
+ def test_returning_false_does_not_halt_callback
obj = CallbackFalseTerminator.new
obj.save
- assert_equal nil, obj.halted
- assert obj.saved
- end
- end
-
- class CallbackFalseTerminatorWithConfigTrueTest < ActiveSupport::TestCase
- def setup
- ActiveSupport::Callbacks.halt_and_display_warning_on_return_false = true
- end
-
- def test_returning_false_does_not_halt_callback_if_config_variable_is_true
- obj = CallbackFalseTerminator.new
- obj.save
- assert_equal nil, obj.halted
- assert obj.saved
- end
- end
-
- class CallbackFalseTerminatorWithConfigFalseTest < ActiveSupport::TestCase
- def setup
- ActiveSupport::Callbacks.halt_and_display_warning_on_return_false = false
- end
-
- def test_returning_false_does_not_halt_callback_if_config_variable_is_false
- obj = CallbackFalseTerminator.new
- obj.save
- assert_equal nil, obj.halted
+ assert_nil obj.halted
assert obj.saved
end
end
@@ -810,7 +881,7 @@ module CallbacksTest
class WriterSkipper < Person
attr_accessor :age
- skip_callback :save, :before, :before_save_method, :if => lambda {self.age > 21}
+ skip_callback :save, :before, :before_save_method, if: -> { age > 21 }
end
class WriterCallbacksTest < ActiveSupport::TestCase
@@ -821,7 +892,6 @@ module CallbacksTest
writer.save
assert_equal [
[:before_save, :symbol],
- [:before_save, :string],
[:before_save, :proc],
[:before_save, :object],
[:before_save, :class],
@@ -830,7 +900,6 @@ module CallbacksTest
[:after_save, :class],
[:after_save, :object],
[:after_save, :proc],
- [:after_save, :string],
[:after_save, :symbol]
], writer.history
end
@@ -885,7 +954,7 @@ module CallbacksTest
def test_proc_arity_2
assert_raises(ArgumentError) do
- klass = build_class(->(x,y) { })
+ klass = build_class(->(x, y) {})
klass.new.run
end
end
@@ -903,7 +972,7 @@ module CallbacksTest
Class.new {
include ActiveSupport::Callbacks
define_callbacks :foo
- set_callback :foo, :before, :foo, :if => callback
+ set_callback :foo, :before, :foo, if: callback
def foo; end
def run; run_callbacks :foo; end
}
@@ -918,11 +987,11 @@ module CallbacksTest
}
klass = Class.new {
include ActiveSupport::Callbacks
- define_callbacks :foo, :scope => [:name]
- set_callback :foo, :before, :foo, :if => callback
+ define_callbacks :foo, scope: [:name]
+ set_callback :foo, :before, :foo, if: callback
def run; run_callbacks :foo; end
private
- def foo; end
+ def foo; end
}
object = klass.new
object.run
@@ -964,7 +1033,7 @@ module CallbacksTest
def test_proc_arity2
assert_raises(ArgumentError) do
- object = build_class(->(a,b) { }).new
+ object = build_class(->(a, b) {}).new
object.run
end
end
@@ -1044,14 +1113,6 @@ module CallbacksTest
assert_equal 1, calls.length
end
- def test_add_eval
- calls = []
- klass = ActiveSupport::Deprecation.silence { build_class("bar") }
- klass.class_eval { define_method(:bar) { calls << klass } }
- klass.new.run
- assert_equal 1, calls.length
- end
-
def test_skip_class # removes one at a time
calls = []
callback = Class.new {
@@ -1086,7 +1147,7 @@ module CallbacksTest
def test_skip_string # raises error
calls = []
- klass = ActiveSupport::Deprecation.silence { build_class("bar") }
+ klass = build_class(:bar)
klass.class_eval { define_method(:bar) { calls << klass } }
assert_raises(ArgumentError) { klass.skip "bar" }
klass.new.run
@@ -1112,12 +1173,24 @@ module CallbacksTest
end
end
- class DeprecatedWarningTest < ActiveSupport::TestCase
- def test_deprecate_string_callback
+ class NotSupportedStringConditionalTest < ActiveSupport::TestCase
+ def test_string_conditional_options
klass = Class.new(Record)
- assert_deprecated do
- klass.send :before_save, "tweedle_dee"
+ assert_raises(ArgumentError) { klass.before_save :tweedle, if: ["true"] }
+ assert_raises(ArgumentError) { klass.before_save :tweedle, if: "true" }
+ assert_raises(ArgumentError) { klass.after_save :tweedle, unless: "false" }
+ assert_raises(ArgumentError) { klass.skip_callback :save, :before, :tweedle, if: "true" }
+ assert_raises(ArgumentError) { klass.skip_callback :save, :after, :tweedle, unless: "false" }
+ end
+ end
+
+ class NotPermittedStringCallbackTest < ActiveSupport::TestCase
+ def test_passing_string_callback_is_not_permitted
+ klass = Class.new(Record)
+
+ assert_raises(ArgumentError) do
+ klass.before_save "tweedle"
end
end
end
diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb
index b96f476ce6..7b97028e8c 100644
--- a/activesupport/test/class_cache_test.rb
+++ b/activesupport/test/class_cache_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/dependencies'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/dependencies"
module ActiveSupport
module Dependencies
@@ -61,7 +63,7 @@ module ActiveSupport
def test_safe_get_constantizes_doesnt_fail_on_invalid_names
assert @cache.empty?
- assert_equal nil, @cache.safe_get("OmgTotallyInvalidConstantName")
+ assert_nil @cache.safe_get("OmgTotallyInvalidConstantName")
end
def test_new_rejects_strings
diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb
index 05580352a9..1b44c7c9bf 100644
--- a/activesupport/test/clean_backtrace_test.rb
+++ b/activesupport/test/clean_backtrace_test.rb
@@ -1,15 +1,17 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class BacktraceCleanerFilterTest < ActiveSupport::TestCase
def setup
@bc = ActiveSupport::BacktraceCleaner.new
- @bc.add_filter { |line| line.gsub("/my/prefix", '') }
+ @bc.add_filter { |line| line.gsub("/my/prefix", "") }
end
test "backtrace should filter all lines in a backtrace, removing prefixes" do
assert_equal \
- ["/my/class.rb", "/my/module.rb"],
- @bc.clean(["/my/prefix/my/class.rb", "/my/prefix/my/module.rb"])
+ ["/my/class.rb", "/my/module.rb"],
+ @bc.clean(["/my/prefix/my/class.rb", "/my/prefix/my/module.rb"])
end
test "backtrace cleaner should allow removing filters" do
@@ -20,13 +22,12 @@ class BacktraceCleanerFilterTest < ActiveSupport::TestCase
test "backtrace should contain unaltered lines if they dont match a filter" do
assert_equal "/my/other_prefix/my/class.rb", @bc.clean([ "/my/other_prefix/my/class.rb" ]).first
end
-
end
class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
def setup
@bc = ActiveSupport::BacktraceCleaner.new
- @bc.add_silencer { |line| line =~ /mongrel/ }
+ @bc.add_silencer { |line| line.include?("mongrel") }
end
test "backtrace should not contain lines that match the silencer" do
@@ -44,8 +45,8 @@ end
class BacktraceCleanerMultipleSilencersTest < ActiveSupport::TestCase
def setup
@bc = ActiveSupport::BacktraceCleaner.new
- @bc.add_silencer { |line| line =~ /mongrel/ }
- @bc.add_silencer { |line| line =~ /yolo/ }
+ @bc.add_silencer { |line| line.include?("mongrel") }
+ @bc.add_silencer { |line| line.include?("yolo") }
end
test "backtrace should not contain lines that match the silencers" do
@@ -66,7 +67,7 @@ class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase
def setup
@bc = ActiveSupport::BacktraceCleaner.new
@bc.add_filter { |line| line.gsub("/mongrel", "") }
- @bc.add_silencer { |line| line =~ /mongrel/ }
+ @bc.add_silencer { |line| line.include?("mongrel") }
end
test "backtrace should not silence lines that has first had their silence hook filtered out" do
diff --git a/activesupport/test/clean_logger_test.rb b/activesupport/test/clean_logger_test.rb
index 02693a97dc..6d8f7064ce 100644
--- a/activesupport/test/clean_logger_test.rb
+++ b/activesupport/test/clean_logger_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'stringio'
-require 'active_support/logger'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "stringio"
+require "active_support/logger"
class CleanLoggerTest < ActiveSupport::TestCase
def setup
@@ -9,14 +11,14 @@ class CleanLoggerTest < ActiveSupport::TestCase
end
def test_format_message
- @logger.error 'error'
+ @logger.error "error"
assert_equal "error\n", @out.string
end
def test_datetime_format
@logger.formatter = Logger::Formatter.new
@logger.formatter.datetime_format = "%Y-%m-%d"
- @logger.debug 'debug'
+ @logger.debug "debug"
assert_equal "%Y-%m-%d", @logger.formatter.datetime_format
assert_match(/D, \[\d\d\d\d-\d\d-\d\d#\d+\] DEBUG -- : debug/, @out.string)
end
diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb
index 8ea701cfb7..ef75a320d1 100644
--- a/activesupport/test/concern_test.rb
+++ b/activesupport/test/concern_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/concern'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/concern"
class ConcernTest < ActiveSupport::TestCase
module Baz
@@ -66,17 +68,17 @@ class ConcernTest < ActiveSupport::TestCase
def test_module_is_included_normally
@klass.include(Baz)
assert_equal "baz", @klass.new.baz
- assert @klass.included_modules.include?(ConcernTest::Baz)
+ assert_includes @klass.included_modules, ConcernTest::Baz
end
def test_class_methods_are_extended
@klass.include(Baz)
assert_equal "baz", @klass.baz
- assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0]
+ assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; included_modules; end)[0]
end
def test_class_methods_are_extended_only_on_expected_objects
- ::Object.__send__(:include, Qux)
+ ::Object.include(Qux)
Object.extend(Qux::ClassMethods)
# module needs to be created after Qux is included in Object or bug won't
# be triggered
@@ -105,7 +107,7 @@ class ConcernTest < ActiveSupport::TestCase
assert_equal "bar", @klass.new.bar
assert_equal "bar+baz", @klass.new.baz
assert_equal "bar's baz + baz", @klass.baz
- assert @klass.included_modules.include?(ConcernTest::Bar)
+ assert_includes @klass.included_modules, ConcernTest::Bar
end
def test_dependencies_with_multiple_modules
diff --git a/activesupport/test/concurrency/load_interlock_aware_monitor_test.rb b/activesupport/test/concurrency/load_interlock_aware_monitor_test.rb
new file mode 100644
index 0000000000..2d0f45ec5f
--- /dev/null
+++ b/activesupport/test/concurrency/load_interlock_aware_monitor_test.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "concurrent/atomic/count_down_latch"
+require "active_support/concurrency/load_interlock_aware_monitor"
+
+module ActiveSupport
+ module Concurrency
+ class LoadInterlockAwareMonitorTest < ActiveSupport::TestCase
+ def setup
+ @monitor = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new
+ end
+
+ def test_entering_with_no_blocking
+ assert @monitor.mon_enter
+ end
+
+ def test_entering_with_blocking
+ load_interlock_latch = Concurrent::CountDownLatch.new
+ monitor_latch = Concurrent::CountDownLatch.new
+
+ able_to_use_monitor = false
+ able_to_load = false
+
+ thread_with_load_interlock = Thread.new do
+ ActiveSupport::Dependencies.interlock.running do
+ load_interlock_latch.count_down
+ monitor_latch.wait
+
+ @monitor.synchronize do
+ able_to_use_monitor = true
+ end
+ end
+ end
+
+ thread_with_monitor_lock = Thread.new do
+ @monitor.synchronize do
+ monitor_latch.count_down
+ load_interlock_latch.wait
+
+ ActiveSupport::Dependencies.interlock.loading do
+ able_to_load = true
+ end
+ end
+ end
+
+ thread_with_load_interlock.join
+ thread_with_monitor_lock.join
+
+ assert able_to_use_monitor
+ assert able_to_load
+ end
+ end
+ end
+end
diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb
index 5d22ded2de..10719596df 100644
--- a/activesupport/test/configurable_test.rb
+++ b/activesupport/test/configurable_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/configurable'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/configurable"
class ConfigurableActiveSupport < ActiveSupport::TestCase
class Parent
@@ -111,7 +113,7 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
end
end
- test 'the config_accessor method should not be publicly callable' do
+ test "the config_accessor method should not be publicly callable" do
assert_raises NoMethodError do
Class.new {
include ActiveSupport::Configurable
@@ -121,11 +123,11 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
def assert_method_defined(object, method)
methods = object.public_methods.map(&:to_s)
- assert methods.include?(method.to_s), "Expected #{methods.inspect} to include #{method.to_s.inspect}"
+ assert_includes methods, method.to_s, "Expected #{methods.inspect} to include #{method.to_s.inspect}"
end
def assert_method_not_defined(object, method)
methods = object.public_methods.map(&:to_s)
- assert !methods.include?(method.to_s), "Expected #{methods.inspect} to not include #{method.to_s.inspect}"
+ assert_not_includes methods, method.to_s, "Expected #{methods.inspect} to not include #{method.to_s.inspect}"
end
end
diff --git a/activesupport/test/constantize_test_cases.rb b/activesupport/test/constantize_test_cases.rb
index 1115bc0fd8..2c6145940b 100644
--- a/activesupport/test/constantize_test_cases.rb
+++ b/activesupport/test/constantize_test_cases.rb
@@ -1,4 +1,6 @@
-require 'dependencies_test_helpers'
+# frozen_string_literal: true
+
+require "dependencies_test_helpers"
module Ace
module Base
@@ -73,6 +75,11 @@ module ConstantizeTestCases
yield("RaisesNoMethodError")
end
end
+
+ with_autoloading_fixtures do
+ yield("Prepend::SubClassConflict")
+ assert_equal "constant", defined?(Prepend::SubClassConflict)
+ end
end
def run_safe_constantize_tests_on
@@ -100,10 +107,10 @@ module ConstantizeTestCases
assert_nil yield("Ace::Gas::ConstantizeTestCases")
assert_nil yield("#<Class:0x7b8b718b>::Nested_1")
assert_nil yield("Ace::gas")
- assert_nil yield('Object::ABC')
- assert_nil yield('Object::Object::Object::ABC')
- assert_nil yield('A::Object::B')
- assert_nil yield('A::Object::Object::Object::B')
+ assert_nil yield("Object::ABC")
+ assert_nil yield("Object::Object::Object::ABC")
+ assert_nil yield("A::Object::B")
+ assert_nil yield("A::Object::Object::Object::B")
assert_raises(NameError) do
with_autoloading_fixtures do
diff --git a/activesupport/test/core_ext/array/access_test.rb b/activesupport/test/core_ext/array/access_test.rb
index 1d834667f0..8c217023cf 100644
--- a/activesupport/test/core_ext/array/access_test.rb
+++ b/activesupport/test/core_ext/array/access_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
class AccessTest < ActiveSupport::TestCase
def test_from
diff --git a/activesupport/test/core_ext/array/conversions_test.rb b/activesupport/test/core_ext/array/conversions_test.rb
index 507e13f968..0a7c43d421 100644
--- a/activesupport/test/core_ext/array/conversions_test.rb
+++ b/activesupport/test/core_ext/array/conversions_test.rb
@@ -1,37 +1,39 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
-require 'active_support/core_ext/big_decimal'
-require 'active_support/core_ext/hash'
-require 'active_support/core_ext/string'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
+require "active_support/core_ext/big_decimal"
+require "active_support/core_ext/hash"
+require "active_support/core_ext/string"
class ToSentenceTest < ActiveSupport::TestCase
def test_plain_array_to_sentence
assert_equal "", [].to_sentence
- assert_equal "one", ['one'].to_sentence
- assert_equal "one and two", ['one', 'two'].to_sentence
- assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence
+ assert_equal "one", ["one"].to_sentence
+ assert_equal "one and two", ["one", "two"].to_sentence
+ assert_equal "one, two, and three", ["one", "two", "three"].to_sentence
end
def test_to_sentence_with_words_connector
- assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(words_connector: ' ')
- assert_equal "one & two, and three", ['one', 'two', 'three'].to_sentence(words_connector: ' & ')
- assert_equal "onetwo, and three", ['one', 'two', 'three'].to_sentence(words_connector: nil)
+ assert_equal "one two, and three", ["one", "two", "three"].to_sentence(words_connector: " ")
+ assert_equal "one & two, and three", ["one", "two", "three"].to_sentence(words_connector: " & ")
+ assert_equal "onetwo, and three", ["one", "two", "three"].to_sentence(words_connector: nil)
end
def test_to_sentence_with_last_word_connector
- assert_equal "one, two, and also three", ['one', 'two', 'three'].to_sentence(last_word_connector: ', and also ')
- assert_equal "one, twothree", ['one', 'two', 'three'].to_sentence(last_word_connector: nil)
- assert_equal "one, two three", ['one', 'two', 'three'].to_sentence(last_word_connector: ' ')
- assert_equal "one, two and three", ['one', 'two', 'three'].to_sentence(last_word_connector: ' and ')
+ assert_equal "one, two, and also three", ["one", "two", "three"].to_sentence(last_word_connector: ", and also ")
+ assert_equal "one, twothree", ["one", "two", "three"].to_sentence(last_word_connector: nil)
+ assert_equal "one, two three", ["one", "two", "three"].to_sentence(last_word_connector: " ")
+ assert_equal "one, two and three", ["one", "two", "three"].to_sentence(last_word_connector: " and ")
end
def test_two_elements
- assert_equal "one and two", ['one', 'two'].to_sentence
- assert_equal "one two", ['one', 'two'].to_sentence(two_words_connector: ' ')
+ assert_equal "one and two", ["one", "two"].to_sentence
+ assert_equal "one two", ["one", "two"].to_sentence(two_words_connector: " ")
end
def test_one_element
- assert_equal "one", ['one'].to_sentence
+ assert_equal "one", ["one"].to_sentence
end
def test_one_element_not_same_object
@@ -40,31 +42,31 @@ class ToSentenceTest < ActiveSupport::TestCase
end
def test_one_non_string_element
- assert_equal '1', [1].to_sentence
+ assert_equal "1", [1].to_sentence
end
def test_does_not_modify_given_hash
- options = { words_connector: ' ' }
- assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options)
- assert_equal({ words_connector: ' ' }, options)
+ options = { words_connector: " " }
+ assert_equal "one two, and three", ["one", "two", "three"].to_sentence(options)
+ assert_equal({ words_connector: " " }, options)
end
def test_with_blank_elements
- assert_equal ", one, , two, and three", [nil, 'one', '', 'two', 'three'].to_sentence
+ assert_equal ", one, , two, and three", [nil, "one", "", "two", "three"].to_sentence
end
def test_with_invalid_options
exception = assert_raise ArgumentError do
- ['one', 'two'].to_sentence(passing: 'invalid option')
+ ["one", "two"].to_sentence(passing: "invalid option")
end
- assert_equal exception.message, "Unknown key: :passing. Valid keys are: :words_connector, :two_words_connector, :last_word_connector, :locale"
+ assert_equal "Unknown key: :passing. Valid keys are: :words_connector, :two_words_connector, :last_word_connector, :locale", exception.message
end
def test_always_returns_string
- assert_instance_of String, [ActiveSupport::SafeBuffer.new('one')].to_sentence
- assert_instance_of String, [ActiveSupport::SafeBuffer.new('one'), 'two'].to_sentence
- assert_instance_of String, [ActiveSupport::SafeBuffer.new('one'), 'two', 'three'].to_sentence
+ assert_instance_of String, [ActiveSupport::SafeBuffer.new("one")].to_sentence
+ assert_instance_of String, [ActiveSupport::SafeBuffer.new("one"), "two"].to_sentence
+ assert_instance_of String, [ActiveSupport::SafeBuffer.new("one"), "two", "three"].to_sentence
end
end
@@ -88,32 +90,32 @@ class ToXmlTest < ActiveSupport::TestCase
def test_to_xml_with_hash_elements
xml = [
{ name: "David", age: 26, age_in_millis: 820497600000 },
- { name: "Jason", age: 31, age_in_millis: BigDecimal.new('1.0') }
+ { name: "Jason", age: 31, age_in_millis: BigDecimal("1.0") }
].to_xml(skip_instruct: true, indent: 0)
assert_equal '<objects type="array"><object>', xml.first(30)
- assert xml.include?(%(<age type="integer">26</age>)), xml
- assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>)), xml
- assert xml.include?(%(<name>David</name>)), xml
- assert xml.include?(%(<age type="integer">31</age>)), xml
- assert xml.include?(%(<age-in-millis type="decimal">1.0</age-in-millis>)), xml
- assert xml.include?(%(<name>Jason</name>)), xml
+ assert_includes xml, %(<age type="integer">26</age>), xml
+ assert_includes xml, %(<age-in-millis type="integer">820497600000</age-in-millis>), xml
+ assert_includes xml, %(<name>David</name>), xml
+ assert_includes xml, %(<age type="integer">31</age>), xml
+ assert_includes xml, %(<age-in-millis type="decimal">1.0</age-in-millis>), xml
+ assert_includes xml, %(<name>Jason</name>), xml
end
def test_to_xml_with_non_hash_elements
- xml = [1, 2, 3].to_xml(skip_instruct: true, indent: 0)
+ xml = %w[1 2 3].to_xml(skip_instruct: true, indent: 0)
- assert_equal '<fixnums type="array"><fixnum', xml.first(29)
- assert xml.include?(%(<fixnum type="integer">2</fixnum>)), xml
+ assert_equal '<strings type="array"><string', xml.first(29)
+ assert_includes xml, %(<string>2</string>), xml
end
def test_to_xml_with_non_hash_different_type_elements
- xml = [1, 2.0, '3'].to_xml(skip_instruct: true, indent: 0)
+ xml = [1, 2.0, "3"].to_xml(skip_instruct: true, indent: 0)
assert_equal '<objects type="array"><object', xml.first(29)
- assert xml.include?(%(<object type="integer">1</object>)), xml
- assert xml.include?(%(<object type="float">2.0</object>)), xml
- assert xml.include?(%(object>3</object>)), xml
+ assert_includes xml, %(<object type="integer">1</object>), xml
+ assert_includes xml, %(<object type="float">2.0</object>), xml
+ assert_includes xml, %(object>3</object>), xml
end
def test_to_xml_with_dedicated_name
@@ -130,10 +132,10 @@ class ToXmlTest < ActiveSupport::TestCase
].to_xml(skip_instruct: true, skip_types: true, indent: 0)
assert_equal "<objects><object>", xml.first(17)
- assert xml.include?(%(<street-address>Paulina</street-address>))
- assert xml.include?(%(<name>David</name>))
- assert xml.include?(%(<street-address>Evergreen</street-address>))
- assert xml.include?(%(<name>Jason</name>))
+ assert_includes xml, %(<street-address>Paulina</street-address>)
+ assert_includes xml, %(<name>David</name>)
+ assert_includes xml, %(<street-address>Evergreen</street-address>)
+ assert_includes xml, %(<name>Jason</name>)
end
def test_to_xml_with_indent_set
@@ -142,10 +144,10 @@ class ToXmlTest < ActiveSupport::TestCase
].to_xml(skip_instruct: true, skip_types: true, indent: 4)
assert_equal "<objects>\n <object>", xml.first(22)
- assert xml.include?(%(\n <street-address>Paulina</street-address>))
- assert xml.include?(%(\n <name>David</name>))
- assert xml.include?(%(\n <street-address>Evergreen</street-address>))
- assert xml.include?(%(\n <name>Jason</name>))
+ assert_includes xml, %(\n <street-address>Paulina</street-address>)
+ assert_includes xml, %(\n <name>David</name>)
+ assert_includes xml, %(\n <street-address>Evergreen</street-address>)
+ assert_includes xml, %(\n <name>Jason</name>)
end
def test_to_xml_with_dasherize_false
@@ -154,8 +156,8 @@ class ToXmlTest < ActiveSupport::TestCase
].to_xml(skip_instruct: true, skip_types: true, indent: 0, dasherize: false)
assert_equal "<objects><object>", xml.first(17)
- assert xml.include?(%(<street_address>Paulina</street_address>))
- assert xml.include?(%(<street_address>Evergreen</street_address>))
+ assert_includes xml, %(<street_address>Paulina</street_address>)
+ assert_includes xml, %(<street_address>Evergreen</street_address>)
end
def test_to_xml_with_dasherize_true
@@ -164,14 +166,14 @@ class ToXmlTest < ActiveSupport::TestCase
].to_xml(skip_instruct: true, skip_types: true, indent: 0, dasherize: true)
assert_equal "<objects><object>", xml.first(17)
- assert xml.include?(%(<street-address>Paulina</street-address>))
- assert xml.include?(%(<street-address>Evergreen</street-address>))
+ assert_includes xml, %(<street-address>Paulina</street-address>)
+ assert_includes xml, %(<street-address>Evergreen</street-address>)
end
def test_to_xml_with_instruct
xml = [
{ name: "David", age: 26, age_in_millis: 820497600000 },
- { name: "Jason", age: 31, age_in_millis: BigDecimal.new('1.0') }
+ { name: "Jason", age: 31, age_in_millis: BigDecimal("1.0") }
].to_xml(skip_instruct: false, indent: 0)
assert_match(/^<\?xml [^>]*/, xml)
@@ -181,12 +183,12 @@ class ToXmlTest < ActiveSupport::TestCase
def test_to_xml_with_block
xml = [
{ name: "David", age: 26, age_in_millis: 820497600000 },
- { name: "Jason", age: 31, age_in_millis: BigDecimal.new('1.0') }
+ { name: "Jason", age: 31, age_in_millis: BigDecimal("1.0") }
].to_xml(skip_instruct: true, indent: 0) do |builder|
builder.count 2
end
- assert xml.include?(%(<count>2</count>)), xml
+ assert_includes xml, %(<count>2</count>), xml
end
def test_to_xml_with_empty
diff --git a/activesupport/test/core_ext/array/extract_options_test.rb b/activesupport/test/core_ext/array/extract_options_test.rb
index 0481a507cf..7a4b15cd71 100644
--- a/activesupport/test/core_ext/array/extract_options_test.rb
+++ b/activesupport/test/core_ext/array/extract_options_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
-require 'active_support/core_ext/hash'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
+require "active_support/core_ext/hash"
class ExtractOptionsTest < ActiveSupport::TestCase
class HashSubclass < Hash
diff --git a/activesupport/test/core_ext/array/grouping_test.rb b/activesupport/test/core_ext/array/grouping_test.rb
index fb7367b0bf..c182b91826 100644
--- a/activesupport/test/core_ext/array/grouping_test.rb
+++ b/activesupport/test/core_ext/array/grouping_test.rb
@@ -1,38 +1,41 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
class GroupingTest < ActiveSupport::TestCase
def setup
- Fixnum.send :private, :/ # test we avoid Integer#/ (redefined by mathn)
+ # In Ruby < 2.4, test we avoid Integer#/ (redefined by mathn)
+ Fixnum.send :private, :/ unless 0.class == Integer
end
def teardown
- Fixnum.send :public, :/
+ Fixnum.send :public, :/ unless 0.class == Integer
end
def test_in_groups_of_with_perfect_fit
groups = []
- ('a'..'i').to_a.in_groups_of(3) do |group|
+ ("a".."i").to_a.in_groups_of(3) do |group|
groups << group
end
assert_equal [%w(a b c), %w(d e f), %w(g h i)], groups
- assert_equal [%w(a b c), %w(d e f), %w(g h i)], ('a'..'i').to_a.in_groups_of(3)
+ assert_equal [%w(a b c), %w(d e f), %w(g h i)], ("a".."i").to_a.in_groups_of(3)
end
def test_in_groups_of_with_padding
groups = []
- ('a'..'g').to_a.in_groups_of(3) do |group|
+ ("a".."g").to_a.in_groups_of(3) do |group|
groups << group
end
- assert_equal [%w(a b c), %w(d e f), ['g', nil, nil]], groups
+ assert_equal [%w(a b c), %w(d e f), ["g", nil, nil]], groups
end
def test_in_groups_of_pads_with_specified_values
groups = []
- ('a'..'g').to_a.in_groups_of(3, 'foo') do |group|
+ ("a".."g").to_a.in_groups_of(3, "foo") do |group|
groups << group
end
@@ -42,7 +45,7 @@ class GroupingTest < ActiveSupport::TestCase
def test_in_groups_of_without_padding
groups = []
- ('a'..'g').to_a.in_groups_of(3, false) do |group|
+ ("a".."g").to_a.in_groups_of(3, false) do |group|
groups << group
end
@@ -82,8 +85,8 @@ class GroupingTest < ActiveSupport::TestCase
assert_equal [[1, 2, 3], [4, 5, nil], [6, 7, nil]],
array.in_groups(3)
- assert_equal [[1, 2, 3], [4, 5, 'foo'], [6, 7, 'foo']],
- array.in_groups(3, 'foo')
+ assert_equal [[1, 2, 3], [4, 5, "foo"], [6, 7, "foo"]],
+ array.in_groups(3, "foo")
end
def test_in_groups_without_padding
@@ -113,7 +116,7 @@ class SplitTest < ActiveSupport::TestCase
def test_split_with_block
a = (1..10).to_a
assert_equal [[1, 2], [4, 5], [7, 8], [10]], a.split { |i| i % 3 == 0 }
- assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], a
+ assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], a
end
def test_split_with_edge_values
diff --git a/activesupport/test/core_ext/array/prepend_append_test.rb b/activesupport/test/core_ext/array/prepend_append_test.rb
index 762aa69b2b..c34acd66ad 100644
--- a/activesupport/test/core_ext/array/prepend_append_test.rb
+++ b/activesupport/test/core_ext/array/prepend_append_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
class PrependAppendTest < ActiveSupport::TestCase
def test_append
diff --git a/activesupport/test/core_ext/array/wrap_test.rb b/activesupport/test/core_ext/array/wrap_test.rb
index baf426506f..46564b4d73 100644
--- a/activesupport/test/core_ext/array/wrap_test.rb
+++ b/activesupport/test/core_ext/array/wrap_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
class WrapTest < ActiveSupport::TestCase
class FakeCollection
diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb
index 423a3f2e9d..62588be33b 100644
--- a/activesupport/test/core_ext/bigdecimal_test.rb
+++ b/activesupport/test/core_ext/bigdecimal_test.rb
@@ -1,9 +1,13 @@
-require 'abstract_unit'
-require 'active_support/core_ext/big_decimal'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/big_decimal"
class BigDecimalTest < ActiveSupport::TestCase
def test_to_s
- bd = BigDecimal.new '0.01'
- assert_equal '0.01', bd.to_s
+ bd = BigDecimal "0.01"
+ assert_equal "0.01", bd.to_s
+ assert_equal "+0.01", bd.to_s("+F")
+ assert_equal "+0.0 1", bd.to_s("+1F")
end
end
diff --git a/activesupport/test/core_ext/class/attribute_test.rb b/activesupport/test/core_ext/class/attribute_test.rb
index e7a1334db3..be6ad82367 100644
--- a/activesupport/test/core_ext/class/attribute_test.rb
+++ b/activesupport/test/core_ext/class/attribute_test.rb
@@ -1,23 +1,33 @@
-require 'abstract_unit'
-require 'active_support/core_ext/class/attribute'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/class/attribute"
class ClassAttributeTest < ActiveSupport::TestCase
def setup
- @klass = Class.new { class_attribute :setting }
+ @klass = Class.new do
+ class_attribute :setting
+ class_attribute :timeout, default: 5
+ end
+
@sub = Class.new(@klass)
end
- test 'defaults to nil' do
+ test "defaults to nil" do
assert_nil @klass.setting
assert_nil @sub.setting
end
- test 'inheritable' do
+ test "custom default" do
+ assert_equal 5, @klass.timeout
+ end
+
+ test "inheritable" do
@klass.setting = 1
assert_equal 1, @sub.setting
end
- test 'overridable' do
+ test "overridable" do
@sub.setting = 1
assert_nil @klass.setting
@@ -27,20 +37,20 @@ class ClassAttributeTest < ActiveSupport::TestCase
assert_equal 1, Class.new(@sub).setting
end
- test 'predicate method' do
+ test "predicate method" do
assert_equal false, @klass.setting?
@klass.setting = 1
assert_equal true, @klass.setting?
end
- test 'instance reader delegates to class' do
+ test "instance reader delegates to class" do
assert_nil @klass.new.setting
@klass.setting = 1
assert_equal 1, @klass.new.setting
end
- test 'instance override' do
+ test "instance override" do
object = @klass.new
object.setting = 1
assert_nil @klass.setting
@@ -48,43 +58,43 @@ class ClassAttributeTest < ActiveSupport::TestCase
assert_equal 1, object.setting
end
- test 'instance predicate' do
+ test "instance predicate" do
object = @klass.new
assert_equal false, object.setting?
object.setting = 1
assert_equal true, object.setting?
end
- test 'disabling instance writer' do
- object = Class.new { class_attribute :setting, :instance_writer => false }.new
- assert_raise(NoMethodError) { object.setting = 'boom' }
+ test "disabling instance writer" do
+ object = Class.new { class_attribute :setting, instance_writer: false }.new
+ assert_raise(NoMethodError) { object.setting = "boom" }
end
- test 'disabling instance reader' do
- object = Class.new { class_attribute :setting, :instance_reader => false }.new
+ test "disabling instance reader" do
+ object = Class.new { class_attribute :setting, instance_reader: false }.new
assert_raise(NoMethodError) { object.setting }
assert_raise(NoMethodError) { object.setting? }
end
- test 'disabling both instance writer and reader' do
- object = Class.new { class_attribute :setting, :instance_accessor => false }.new
+ test "disabling both instance writer and reader" do
+ object = Class.new { class_attribute :setting, instance_accessor: false }.new
assert_raise(NoMethodError) { object.setting }
assert_raise(NoMethodError) { object.setting? }
- assert_raise(NoMethodError) { object.setting = 'boom' }
+ assert_raise(NoMethodError) { object.setting = "boom" }
end
- test 'disabling instance predicate' do
+ test "disabling instance predicate" do
object = Class.new { class_attribute :setting, instance_predicate: false }.new
assert_raise(NoMethodError) { object.setting? }
end
- test 'works well with singleton classes' do
+ test "works well with singleton classes" do
object = @klass.new
- object.singleton_class.setting = 'foo'
- assert_equal 'foo', object.setting
+ object.singleton_class.setting = "foo"
+ assert_equal "foo", object.setting
end
- test 'setter returns set value' do
+ test "setter returns set value" do
val = @klass.send(:setting=, 1)
assert_equal 1, val
end
diff --git a/activesupport/test/core_ext/class_test.rb b/activesupport/test/core_ext/class_test.rb
index 9c6c579ef7..9cc006fc63 100644
--- a/activesupport/test/core_ext/class_test.rb
+++ b/activesupport/test/core_ext/class_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/core_ext/class'
-require 'set'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/class"
+require "set"
class ClassTest < ActiveSupport::TestCase
class Parent; end
@@ -25,4 +27,14 @@ class ClassTest < ActiveSupport::TestCase
assert_equal [Baz], Bar.subclasses
assert_equal [], Baz.subclasses
end
+
+ def test_descendants_excludes_singleton_classes
+ klass = Parent.new.singleton_class
+ refute Parent.descendants.include?(klass), "descendants should not include singleton classes"
+ end
+
+ def test_subclasses_excludes_singleton_classes
+ klass = Parent.new.singleton_class
+ refute Parent.subclasses.include?(klass), "subclasses should not include singleton classes"
+ end
end
diff --git a/activesupport/test/core_ext/date_and_time_behavior.rb b/activesupport/test/core_ext/date_and_time_behavior.rb
index 54df87def8..1176ed647a 100644
--- a/activesupport/test/core_ext/date_and_time_behavior.rb
+++ b/activesupport/test/core_ext/date_and_time_behavior.rb
@@ -1,107 +1,119 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
module DateAndTimeBehavior
def test_yesterday
- assert_equal date_time_init(2005,2,21,10,10,10), date_time_init(2005,2,22,10,10,10).yesterday
- assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,3,2,10,10,10).yesterday.yesterday
+ assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).yesterday
+ assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 3, 2, 10, 10, 10).yesterday.yesterday
end
def test_prev_day
- assert_equal date_time_init(2005,2,21,10,10,10), date_time_init(2005,2,22,10,10,10).prev_day
- assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,3,2,10,10,10).prev_day.prev_day
+ assert_equal date_time_init(2005, 2, 24, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(-2)
+ assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(-1)
+ assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(0)
+ assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(1)
+ assert_equal date_time_init(2005, 2, 20, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(2)
+ assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day
+ assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 3, 2, 10, 10, 10).prev_day.prev_day
end
def test_tomorrow
- assert_equal date_time_init(2005,2,23,10,10,10), date_time_init(2005,2,22,10,10,10).tomorrow
- assert_equal date_time_init(2005,3,2,10,10,10), date_time_init(2005,2,28,10,10,10).tomorrow.tomorrow
+ assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).tomorrow
+ assert_equal date_time_init(2005, 3, 2, 10, 10, 10), date_time_init(2005, 2, 28, 10, 10, 10).tomorrow.tomorrow
end
def test_next_day
- assert_equal date_time_init(2005,2,23,10,10,10), date_time_init(2005,2,22,10,10,10).next_day
- assert_equal date_time_init(2005,3,2,10,10,10), date_time_init(2005,2,28,10,10,10).next_day.next_day
+ assert_equal date_time_init(2005, 2, 20, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(-2)
+ assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(-1)
+ assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(0)
+ assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(1)
+ assert_equal date_time_init(2005, 2, 24, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(2)
+ assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day
+ assert_equal date_time_init(2005, 3, 2, 10, 10, 10), date_time_init(2005, 2, 28, 10, 10, 10).next_day.next_day
end
def test_days_ago
- assert_equal date_time_init(2005,6,4,10,10,10), date_time_init(2005,6,5,10,10,10).days_ago(1)
- assert_equal date_time_init(2005,5,31,10,10,10), date_time_init(2005,6,5,10,10,10).days_ago(5)
+ assert_equal date_time_init(2005, 6, 4, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).days_ago(1)
+ assert_equal date_time_init(2005, 5, 31, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).days_ago(5)
end
def test_days_since
- assert_equal date_time_init(2005,6,6,10,10,10), date_time_init(2005,6,5,10,10,10).days_since(1)
- assert_equal date_time_init(2005,1,1,10,10,10), date_time_init(2004,12,31,10,10,10).days_since(1)
+ assert_equal date_time_init(2005, 6, 6, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).days_since(1)
+ assert_equal date_time_init(2005, 1, 1, 10, 10, 10), date_time_init(2004, 12, 31, 10, 10, 10).days_since(1)
end
def test_weeks_ago
- assert_equal date_time_init(2005,5,29,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(1)
- assert_equal date_time_init(2005,5,1,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(5)
- assert_equal date_time_init(2005,4,24,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(6)
- assert_equal date_time_init(2005,2,27,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(14)
- assert_equal date_time_init(2004,12,25,10,10,10), date_time_init(2005,1,1,10,10,10).weeks_ago(1)
+ assert_equal date_time_init(2005, 5, 29, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).weeks_ago(1)
+ assert_equal date_time_init(2005, 5, 1, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).weeks_ago(5)
+ assert_equal date_time_init(2005, 4, 24, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).weeks_ago(6)
+ assert_equal date_time_init(2005, 2, 27, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).weeks_ago(14)
+ assert_equal date_time_init(2004, 12, 25, 10, 10, 10), date_time_init(2005, 1, 1, 10, 10, 10).weeks_ago(1)
end
def test_weeks_since
- assert_equal date_time_init(2005,7,14,10,10,10), date_time_init(2005,7,7,10,10,10).weeks_since(1)
- assert_equal date_time_init(2005,7,14,10,10,10), date_time_init(2005,7,7,10,10,10).weeks_since(1)
- assert_equal date_time_init(2005,7,4,10,10,10), date_time_init(2005,6,27,10,10,10).weeks_since(1)
- assert_equal date_time_init(2005,1,4,10,10,10), date_time_init(2004,12,28,10,10,10).weeks_since(1)
+ assert_equal date_time_init(2005, 7, 14, 10, 10, 10), date_time_init(2005, 7, 7, 10, 10, 10).weeks_since(1)
+ assert_equal date_time_init(2005, 7, 14, 10, 10, 10), date_time_init(2005, 7, 7, 10, 10, 10).weeks_since(1)
+ assert_equal date_time_init(2005, 7, 4, 10, 10, 10), date_time_init(2005, 6, 27, 10, 10, 10).weeks_since(1)
+ assert_equal date_time_init(2005, 1, 4, 10, 10, 10), date_time_init(2004, 12, 28, 10, 10, 10).weeks_since(1)
end
def test_months_ago
- assert_equal date_time_init(2005,5,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(1)
- assert_equal date_time_init(2004,11,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(7)
- assert_equal date_time_init(2004,12,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(6)
- assert_equal date_time_init(2004,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(12)
- assert_equal date_time_init(2003,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(24)
+ assert_equal date_time_init(2005, 5, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_ago(1)
+ assert_equal date_time_init(2004, 11, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_ago(7)
+ assert_equal date_time_init(2004, 12, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_ago(6)
+ assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_ago(12)
+ assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_ago(24)
end
def test_months_since
- assert_equal date_time_init(2005,7,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(1)
- assert_equal date_time_init(2006,1,5,10,10,10), date_time_init(2005,12,5,10,10,10).months_since(1)
- assert_equal date_time_init(2005,12,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(6)
- assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,12,5,10,10,10).months_since(6)
- assert_equal date_time_init(2006,1,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(7)
- assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(12)
- assert_equal date_time_init(2007,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(24)
- assert_equal date_time_init(2005,4,30,10,10,10), date_time_init(2005,3,31,10,10,10).months_since(1)
- assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,1,29,10,10,10).months_since(1)
- assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,1,30,10,10,10).months_since(1)
- assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,1,31,10,10,10).months_since(1)
+ assert_equal date_time_init(2005, 7, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_since(1)
+ assert_equal date_time_init(2006, 1, 5, 10, 10, 10), date_time_init(2005, 12, 5, 10, 10, 10).months_since(1)
+ assert_equal date_time_init(2005, 12, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_since(6)
+ assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 12, 5, 10, 10, 10).months_since(6)
+ assert_equal date_time_init(2006, 1, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_since(7)
+ assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_since(12)
+ assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).months_since(24)
+ assert_equal date_time_init(2005, 4, 30, 10, 10, 10), date_time_init(2005, 3, 31, 10, 10, 10).months_since(1)
+ assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 1, 29, 10, 10, 10).months_since(1)
+ assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 1, 30, 10, 10, 10).months_since(1)
+ assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 1, 31, 10, 10, 10).months_since(1)
end
def test_years_ago
- assert_equal date_time_init(2004,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_ago(1)
- assert_equal date_time_init(1998,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_ago(7)
- assert_equal date_time_init(2003,2,28,10,10,10), date_time_init(2004,2,29,10,10,10).years_ago(1) # 1 year ago from leap day
+ assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).years_ago(1)
+ assert_equal date_time_init(1998, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).years_ago(7)
+ assert_equal date_time_init(2003, 2, 28, 10, 10, 10), date_time_init(2004, 2, 29, 10, 10, 10).years_ago(1) # 1 year ago from leap day
end
def test_years_since
- assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_since(1)
- assert_equal date_time_init(2012,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_since(7)
- assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2004,2,29,10,10,10).years_since(1) # 1 year since leap day
- assert_equal date_time_init(2182,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_since(177)
+ assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).years_since(1)
+ assert_equal date_time_init(2012, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).years_since(7)
+ assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2004, 2, 29, 10, 10, 10).years_since(1) # 1 year since leap day
+ assert_equal date_time_init(2182, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).years_since(177)
end
def test_beginning_of_month
- assert_equal date_time_init(2005,2,1,0,0,0), date_time_init(2005,2,22,10,10,10).beginning_of_month
+ assert_equal date_time_init(2005, 2, 1, 0, 0, 0), date_time_init(2005, 2, 22, 10, 10, 10).beginning_of_month
end
def test_beginning_of_quarter
- assert_equal date_time_init(2005,1,1,0,0,0), date_time_init(2005,2,15,10,10,10).beginning_of_quarter
- assert_equal date_time_init(2005,1,1,0,0,0), date_time_init(2005,1,1,0,0,0).beginning_of_quarter
- assert_equal date_time_init(2005,10,1,0,0,0), date_time_init(2005,12,31,10,10,10).beginning_of_quarter
- assert_equal date_time_init(2005,4,1,0,0,0), date_time_init(2005,6,30,23,59,59).beginning_of_quarter
+ assert_equal date_time_init(2005, 1, 1, 0, 0, 0), date_time_init(2005, 2, 15, 10, 10, 10).beginning_of_quarter
+ assert_equal date_time_init(2005, 1, 1, 0, 0, 0), date_time_init(2005, 1, 1, 0, 0, 0).beginning_of_quarter
+ assert_equal date_time_init(2005, 10, 1, 0, 0, 0), date_time_init(2005, 12, 31, 10, 10, 10).beginning_of_quarter
+ assert_equal date_time_init(2005, 4, 1, 0, 0, 0), date_time_init(2005, 6, 30, 23, 59, 59).beginning_of_quarter
end
def test_end_of_quarter
- assert_equal date_time_init(2007,3,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,2,15,10,10,10).end_of_quarter
- assert_equal date_time_init(2007,3,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,3,31,0,0,0).end_of_quarter
- assert_equal date_time_init(2007,12,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,12,21,10,10,10).end_of_quarter
- assert_equal date_time_init(2007,6,30,23,59,59,Rational(999999999, 1000)), date_time_init(2007,4,1,0,0,0).end_of_quarter
- assert_equal date_time_init(2008,6,30,23,59,59,Rational(999999999, 1000)), date_time_init(2008,5,31,0,0,0).end_of_quarter
+ assert_equal date_time_init(2007, 3, 31, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 2, 15, 10, 10, 10).end_of_quarter
+ assert_equal date_time_init(2007, 3, 31, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 3, 31, 0, 0, 0).end_of_quarter
+ assert_equal date_time_init(2007, 12, 31, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 12, 21, 10, 10, 10).end_of_quarter
+ assert_equal date_time_init(2007, 6, 30, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 4, 1, 0, 0, 0).end_of_quarter
+ assert_equal date_time_init(2008, 6, 30, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2008, 5, 31, 0, 0, 0).end_of_quarter
end
def test_beginning_of_year
- assert_equal date_time_init(2005,1,1,0,0,0), date_time_init(2005,2,22,10,10,10).beginning_of_year
+ assert_equal date_time_init(2005, 1, 1, 0, 0, 0), date_time_init(2005, 2, 22, 10, 10, 10).beginning_of_year
end
def test_next_week
@@ -110,10 +122,10 @@ module DateAndTimeBehavior
# | 22/2 | | | | | # | | | | 4/3 | | # friday in next week `next_week(:friday)`
# 23/10 | | | | | | # 30/10 | | | | | | # monday in next week `next_week`
# 23/10 | | | | | | # | | 1/11 | | | | # wednesday in next week `next_week(:wednesday)`
- assert_equal date_time_init(2005,2,28,0,0,0), date_time_init(2005,2,22,15,15,10).next_week
- assert_equal date_time_init(2005,3,4,0,0,0), date_time_init(2005,2,22,15,15,10).next_week(:friday)
- assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,10,23,0,0,0).next_week
- assert_equal date_time_init(2006,11,1,0,0,0), date_time_init(2006,10,23,0,0,0).next_week(:wednesday)
+ assert_equal date_time_init(2005, 2, 28, 0, 0, 0), date_time_init(2005, 2, 22, 15, 15, 10).next_week
+ assert_equal date_time_init(2005, 3, 4, 0, 0, 0), date_time_init(2005, 2, 22, 15, 15, 10).next_week(:friday)
+ assert_equal date_time_init(2006, 10, 30, 0, 0, 0), date_time_init(2006, 10, 23, 0, 0, 0).next_week
+ assert_equal date_time_init(2006, 11, 1, 0, 0, 0), date_time_init(2006, 10, 23, 0, 0, 0).next_week(:wednesday)
end
def test_next_week_with_default_beginning_of_week_set
@@ -126,45 +138,63 @@ module DateAndTimeBehavior
end
def test_next_week_at_same_time
- assert_equal date_time_init(2005,2,28,15,15,10), date_time_init(2005,2,22,15,15,10).next_week(:monday, same_time: true)
- assert_equal date_time_init(2005,3,4,15,15,10), date_time_init(2005,2,22,15,15,10).next_week(:friday, same_time: true)
- assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,10,23,0,0,0).next_week(:monday, same_time: true)
- assert_equal date_time_init(2006,11,1,0,0,0), date_time_init(2006,10,23,0,0,0).next_week(:wednesday, same_time: true)
+ assert_equal date_time_init(2005, 2, 28, 15, 15, 10), date_time_init(2005, 2, 22, 15, 15, 10).next_week(:monday, same_time: true)
+ assert_equal date_time_init(2005, 2, 28, 15, 15, 10, 999999), date_time_init(2005, 2, 22, 15, 15, 10, 999999).next_week(:monday, same_time: true)
+ assert_equal date_time_init(2005, 2, 28, 15, 15, 10, Rational(999999999, 1000)), date_time_init(2005, 2, 22, 15, 15, 10, Rational(999999999, 1000)).next_week(:monday, same_time: true)
+ assert_equal date_time_init(2005, 3, 4, 15, 15, 10), date_time_init(2005, 2, 22, 15, 15, 10).next_week(:friday, same_time: true)
+ assert_equal date_time_init(2006, 10, 30, 0, 0, 0), date_time_init(2006, 10, 23, 0, 0, 0).next_week(:monday, same_time: true)
+ assert_equal date_time_init(2006, 11, 1, 0, 0, 0), date_time_init(2006, 10, 23, 0, 0, 0).next_week(:wednesday, same_time: true)
end
def test_next_weekday_on_wednesday
- assert_equal date_time_init(2015,1,8,0,0,0), date_time_init(2015,1,7,0,0,0).next_weekday
- assert_equal date_time_init(2015,1,8,15,15,10), date_time_init(2015,1,7,15,15,10).next_weekday
+ assert_equal date_time_init(2015, 1, 8, 0, 0, 0), date_time_init(2015, 1, 7, 0, 0, 0).next_weekday
+ assert_equal date_time_init(2015, 1, 8, 15, 15, 10), date_time_init(2015, 1, 7, 15, 15, 10).next_weekday
end
def test_next_weekday_on_friday
- assert_equal date_time_init(2015,1,5,0,0,0), date_time_init(2015,1,2,0,0,0).next_weekday
- assert_equal date_time_init(2015,1,5,15,15,10), date_time_init(2015,1,2,15,15,10).next_weekday
+ assert_equal date_time_init(2015, 1, 5, 0, 0, 0), date_time_init(2015, 1, 2, 0, 0, 0).next_weekday
+ assert_equal date_time_init(2015, 1, 5, 15, 15, 10), date_time_init(2015, 1, 2, 15, 15, 10).next_weekday
end
def test_next_weekday_on_saturday
- assert_equal date_time_init(2015,1,5,0,0,0), date_time_init(2015,1,3,0,0,0).next_weekday
- assert_equal date_time_init(2015,1,5,15,15,10), date_time_init(2015,1,3,15,15,10).next_weekday
+ assert_equal date_time_init(2015, 1, 5, 0, 0, 0), date_time_init(2015, 1, 3, 0, 0, 0).next_weekday
+ assert_equal date_time_init(2015, 1, 5, 15, 15, 10), date_time_init(2015, 1, 3, 15, 15, 10).next_weekday
+ end
+
+ def test_next_month
+ assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(-2)
+ assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(-1)
+ assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(0)
+ assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(1)
+ assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(2)
+ assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month
+ assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month.next_month
end
def test_next_month_on_31st
- assert_equal date_time_init(2005,9,30,15,15,10), date_time_init(2005,8,31,15,15,10).next_month
+ assert_equal date_time_init(2005, 9, 30, 15, 15, 10), date_time_init(2005, 8, 31, 15, 15, 10).next_month
end
def test_next_quarter_on_31st
- assert_equal date_time_init(2005,11,30,15,15,10), date_time_init(2005,8,31,15,15,10).next_quarter
+ assert_equal date_time_init(2005, 11, 30, 15, 15, 10), date_time_init(2005, 8, 31, 15, 15, 10).next_quarter
end
def test_next_year
- assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).next_year
+ assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(-2)
+ assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(-1)
+ assert_equal date_time_init(2005, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(0)
+ assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(1)
+ assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(2)
+ assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year
+ assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year.next_year
end
def test_prev_week
- assert_equal date_time_init(2005,2,21,0,0,0), date_time_init(2005,3,1,15,15,10).prev_week
- assert_equal date_time_init(2005,2,22,0,0,0), date_time_init(2005,3,1,15,15,10).prev_week(:tuesday)
- assert_equal date_time_init(2005,2,25,0,0,0), date_time_init(2005,3,1,15,15,10).prev_week(:friday)
- assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,11,6,0,0,0).prev_week
- assert_equal date_time_init(2006,11,15,0,0,0), date_time_init(2006,11,23,0,0,0).prev_week(:wednesday)
+ assert_equal date_time_init(2005, 2, 21, 0, 0, 0), date_time_init(2005, 3, 1, 15, 15, 10).prev_week
+ assert_equal date_time_init(2005, 2, 22, 0, 0, 0), date_time_init(2005, 3, 1, 15, 15, 10).prev_week(:tuesday)
+ assert_equal date_time_init(2005, 2, 25, 0, 0, 0), date_time_init(2005, 3, 1, 15, 15, 10).prev_week(:friday)
+ assert_equal date_time_init(2006, 10, 30, 0, 0, 0), date_time_init(2006, 11, 6, 0, 0, 0).prev_week
+ assert_equal date_time_init(2006, 11, 15, 0, 0, 0), date_time_init(2006, 11, 23, 0, 0, 0).prev_week(:wednesday)
end
def test_prev_week_with_default_beginning_of_week
@@ -177,138 +207,182 @@ module DateAndTimeBehavior
end
def test_prev_week_at_same_time
- assert_equal date_time_init(2005,2,21,15,15,10), date_time_init(2005,3,1,15,15,10).prev_week(:monday, same_time: true)
- assert_equal date_time_init(2005,2,22,15,15,10), date_time_init(2005,3,1,15,15,10).prev_week(:tuesday, same_time: true)
- assert_equal date_time_init(2005,2,25,15,15,10), date_time_init(2005,3,1,15,15,10).prev_week(:friday, same_time: true)
- assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,11,6,0,0,0).prev_week(:monday, same_time: true)
- assert_equal date_time_init(2006,11,15,0,0,0), date_time_init(2006,11,23,0,0,0).prev_week(:wednesday, same_time: true)
+ assert_equal date_time_init(2005, 2, 21, 15, 15, 10), date_time_init(2005, 3, 1, 15, 15, 10).prev_week(:monday, same_time: true)
+ assert_equal date_time_init(2005, 2, 22, 15, 15, 10), date_time_init(2005, 3, 1, 15, 15, 10).prev_week(:tuesday, same_time: true)
+ assert_equal date_time_init(2005, 2, 25, 15, 15, 10), date_time_init(2005, 3, 1, 15, 15, 10).prev_week(:friday, same_time: true)
+ assert_equal date_time_init(2006, 10, 30, 0, 0, 0), date_time_init(2006, 11, 6, 0, 0, 0).prev_week(:monday, same_time: true)
+ assert_equal date_time_init(2006, 11, 15, 0, 0, 0), date_time_init(2006, 11, 23, 0, 0, 0).prev_week(:wednesday, same_time: true)
end
def test_prev_weekday_on_wednesday
- assert_equal date_time_init(2015,1,6,0,0,0), date_time_init(2015,1,7,0,0,0).prev_weekday
- assert_equal date_time_init(2015,1,6,15,15,10), date_time_init(2015,1,7,15,15,10).prev_weekday
+ assert_equal date_time_init(2015, 1, 6, 0, 0, 0), date_time_init(2015, 1, 7, 0, 0, 0).prev_weekday
+ assert_equal date_time_init(2015, 1, 6, 15, 15, 10), date_time_init(2015, 1, 7, 15, 15, 10).prev_weekday
end
def test_prev_weekday_on_monday
- assert_equal date_time_init(2015,1,2,0,0,0), date_time_init(2015,1,5,0,0,0).prev_weekday
- assert_equal date_time_init(2015,1,2,15,15,10), date_time_init(2015,1,5,15,15,10).prev_weekday
+ assert_equal date_time_init(2015, 1, 2, 0, 0, 0), date_time_init(2015, 1, 5, 0, 0, 0).prev_weekday
+ assert_equal date_time_init(2015, 1, 2, 15, 15, 10), date_time_init(2015, 1, 5, 15, 15, 10).prev_weekday
end
def test_prev_weekday_on_sunday
- assert_equal date_time_init(2015,1,2,0,0,0), date_time_init(2015,1,4,0,0,0).prev_weekday
- assert_equal date_time_init(2015,1,2,15,15,10), date_time_init(2015,1,4,15,15,10).prev_weekday
+ assert_equal date_time_init(2015, 1, 2, 0, 0, 0), date_time_init(2015, 1, 4, 0, 0, 0).prev_weekday
+ assert_equal date_time_init(2015, 1, 2, 15, 15, 10), date_time_init(2015, 1, 4, 15, 15, 10).prev_weekday
+ end
+
+ def test_prev_month
+ assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(-2)
+ assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(-1)
+ assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(0)
+ assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(1)
+ assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(2)
+ assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month
+ assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month.prev_month
end
def test_prev_month_on_31st
- assert_equal date_time_init(2004,2,29,10,10,10), date_time_init(2004,3,31,10,10,10).prev_month
+ assert_equal date_time_init(2004, 2, 29, 10, 10, 10), date_time_init(2004, 3, 31, 10, 10, 10).prev_month
end
def test_prev_quarter_on_31st
- assert_equal date_time_init(2004,2,29,10,10,10), date_time_init(2004,5,31,10,10,10).prev_quarter
+ assert_equal date_time_init(2004, 2, 29, 10, 10, 10), date_time_init(2004, 5, 31, 10, 10, 10).prev_quarter
end
def test_prev_year
- assert_equal date_time_init(2004,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).prev_year
+ assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(-2)
+ assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(-1)
+ assert_equal date_time_init(2005, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(0)
+ assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(1)
+ assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(2)
+ assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year
+ assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year.prev_year
+ end
+
+ def test_last_month_on_31st
+ assert_equal date_time_init(2004, 2, 29, 0, 0, 0), date_time_init(2004, 3, 31, 0, 0, 0).last_month
+ end
+
+ def test_last_year
+ assert_equal date_time_init(2004, 6, 5, 10, 0, 0), date_time_init(2005, 6, 5, 10, 0, 0).last_year
end
def test_days_to_week_start
- assert_equal 0, date_time_init(2011,11,01,0,0,0).days_to_week_start(:tuesday)
- assert_equal 1, date_time_init(2011,11,02,0,0,0).days_to_week_start(:tuesday)
- assert_equal 2, date_time_init(2011,11,03,0,0,0).days_to_week_start(:tuesday)
- assert_equal 3, date_time_init(2011,11,04,0,0,0).days_to_week_start(:tuesday)
- assert_equal 4, date_time_init(2011,11,05,0,0,0).days_to_week_start(:tuesday)
- assert_equal 5, date_time_init(2011,11,06,0,0,0).days_to_week_start(:tuesday)
- assert_equal 6, date_time_init(2011,11,07,0,0,0).days_to_week_start(:tuesday)
-
- assert_equal 3, date_time_init(2011,11,03,0,0,0).days_to_week_start(:monday)
- assert_equal 3, date_time_init(2011,11,04,0,0,0).days_to_week_start(:tuesday)
- assert_equal 3, date_time_init(2011,11,05,0,0,0).days_to_week_start(:wednesday)
- assert_equal 3, date_time_init(2011,11,06,0,0,0).days_to_week_start(:thursday)
- assert_equal 3, date_time_init(2011,11,07,0,0,0).days_to_week_start(:friday)
- assert_equal 3, date_time_init(2011,11,8,0,0,0).days_to_week_start(:saturday)
- assert_equal 3, date_time_init(2011,11,9,0,0,0).days_to_week_start(:sunday)
+ assert_equal 0, date_time_init(2011, 11, 01, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 1, date_time_init(2011, 11, 02, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 2, date_time_init(2011, 11, 03, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 3, date_time_init(2011, 11, 04, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 4, date_time_init(2011, 11, 05, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 5, date_time_init(2011, 11, 06, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 6, date_time_init(2011, 11, 07, 0, 0, 0).days_to_week_start(:tuesday)
+
+ assert_equal 3, date_time_init(2011, 11, 03, 0, 0, 0).days_to_week_start(:monday)
+ assert_equal 3, date_time_init(2011, 11, 04, 0, 0, 0).days_to_week_start(:tuesday)
+ assert_equal 3, date_time_init(2011, 11, 05, 0, 0, 0).days_to_week_start(:wednesday)
+ assert_equal 3, date_time_init(2011, 11, 06, 0, 0, 0).days_to_week_start(:thursday)
+ assert_equal 3, date_time_init(2011, 11, 07, 0, 0, 0).days_to_week_start(:friday)
+ assert_equal 3, date_time_init(2011, 11, 8, 0, 0, 0).days_to_week_start(:saturday)
+ assert_equal 3, date_time_init(2011, 11, 9, 0, 0, 0).days_to_week_start(:sunday)
end
def test_days_to_week_start_with_default_set
with_bw_default(:friday) do
- assert_equal 6, Time.local(2012,03,8,0,0,0).days_to_week_start
- assert_equal 5, Time.local(2012,03,7,0,0,0).days_to_week_start
- assert_equal 4, Time.local(2012,03,6,0,0,0).days_to_week_start
- assert_equal 3, Time.local(2012,03,5,0,0,0).days_to_week_start
- assert_equal 2, Time.local(2012,03,4,0,0,0).days_to_week_start
- assert_equal 1, Time.local(2012,03,3,0,0,0).days_to_week_start
- assert_equal 0, Time.local(2012,03,2,0,0,0).days_to_week_start
+ assert_equal 6, Time.local(2012, 03, 8, 0, 0, 0).days_to_week_start
+ assert_equal 5, Time.local(2012, 03, 7, 0, 0, 0).days_to_week_start
+ assert_equal 4, Time.local(2012, 03, 6, 0, 0, 0).days_to_week_start
+ assert_equal 3, Time.local(2012, 03, 5, 0, 0, 0).days_to_week_start
+ assert_equal 2, Time.local(2012, 03, 4, 0, 0, 0).days_to_week_start
+ assert_equal 1, Time.local(2012, 03, 3, 0, 0, 0).days_to_week_start
+ assert_equal 0, Time.local(2012, 03, 2, 0, 0, 0).days_to_week_start
end
end
def test_beginning_of_week
- assert_equal date_time_init(2005,1,31,0,0,0), date_time_init(2005,2,4,10,10,10).beginning_of_week
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,11,28,0,0,0).beginning_of_week #monday
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,11,29,0,0,0).beginning_of_week #tuesday
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,11,30,0,0,0).beginning_of_week #wednesday
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,01,0,0,0).beginning_of_week #thursday
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,02,0,0,0).beginning_of_week #friday
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,03,0,0,0).beginning_of_week #saturday
- assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,04,0,0,0).beginning_of_week #sunday
+ assert_equal date_time_init(2005, 1, 31, 0, 0, 0), date_time_init(2005, 2, 4, 10, 10, 10).beginning_of_week
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 11, 28, 0, 0, 0).beginning_of_week # monday
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 11, 29, 0, 0, 0).beginning_of_week # tuesday
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 11, 30, 0, 0, 0).beginning_of_week # wednesday
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 12, 01, 0, 0, 0).beginning_of_week # thursday
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 12, 02, 0, 0, 0).beginning_of_week # friday
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 12, 03, 0, 0, 0).beginning_of_week # saturday
+ assert_equal date_time_init(2005, 11, 28, 0, 0, 0), date_time_init(2005, 12, 04, 0, 0, 0).beginning_of_week # sunday
end
def test_end_of_week
- assert_equal date_time_init(2008,1,6,23,59,59,Rational(999999999, 1000)), date_time_init(2007,12,31,10,10,10).end_of_week
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,27,0,0,0).end_of_week #monday
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,28,0,0,0).end_of_week #tuesday
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,29,0,0,0).end_of_week #wednesday
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,30,0,0,0).end_of_week #thursday
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,31,0,0,0).end_of_week #friday
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,9,01,0,0,0).end_of_week #saturday
- assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,9,02,0,0,0).end_of_week #sunday
+ assert_equal date_time_init(2008, 1, 6, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 12, 31, 10, 10, 10).end_of_week
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 8, 27, 0, 0, 0).end_of_week # monday
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 8, 28, 0, 0, 0).end_of_week # tuesday
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 8, 29, 0, 0, 0).end_of_week # wednesday
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 8, 30, 0, 0, 0).end_of_week # thursday
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 8, 31, 0, 0, 0).end_of_week # friday
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 9, 01, 0, 0, 0).end_of_week # saturday
+ assert_equal date_time_init(2007, 9, 2, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 9, 02, 0, 0, 0).end_of_week # sunday
end
def test_end_of_month
- assert_equal date_time_init(2005,3,31,23,59,59,Rational(999999999, 1000)), date_time_init(2005,3,20,10,10,10).end_of_month
- assert_equal date_time_init(2005,2,28,23,59,59,Rational(999999999, 1000)), date_time_init(2005,2,20,10,10,10).end_of_month
- assert_equal date_time_init(2005,4,30,23,59,59,Rational(999999999, 1000)), date_time_init(2005,4,20,10,10,10).end_of_month
+ assert_equal date_time_init(2005, 3, 31, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2005, 3, 20, 10, 10, 10).end_of_month
+ assert_equal date_time_init(2005, 2, 28, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2005, 2, 20, 10, 10, 10).end_of_month
+ assert_equal date_time_init(2005, 4, 30, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2005, 4, 20, 10, 10, 10).end_of_month
end
def test_end_of_year
- assert_equal date_time_init(2007,12,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,2,22,10,10,10).end_of_year
- assert_equal date_time_init(2007,12,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,12,31,10,10,10).end_of_year
+ assert_equal date_time_init(2007, 12, 31, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 2, 22, 10, 10, 10).end_of_year
+ assert_equal date_time_init(2007, 12, 31, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2007, 12, 31, 10, 10, 10).end_of_year
+ end
+
+ def test_next_occurring
+ assert_equal date_time_init(2017, 12, 18, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:monday)
+ assert_equal date_time_init(2017, 12, 19, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:tuesday)
+ assert_equal date_time_init(2017, 12, 20, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:wednesday)
+ assert_equal date_time_init(2017, 12, 21, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:thursday)
+ assert_equal date_time_init(2017, 12, 15, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:friday)
+ assert_equal date_time_init(2017, 12, 16, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:saturday)
+ assert_equal date_time_init(2017, 12, 17, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).next_occurring(:sunday)
+ end
+
+ def test_prev_occurring
+ assert_equal date_time_init(2017, 12, 11, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:monday)
+ assert_equal date_time_init(2017, 12, 12, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:tuesday)
+ assert_equal date_time_init(2017, 12, 13, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:wednesday)
+ assert_equal date_time_init(2017, 12, 7, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:thursday)
+ assert_equal date_time_init(2017, 12, 8, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:friday)
+ assert_equal date_time_init(2017, 12, 9, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:saturday)
+ assert_equal date_time_init(2017, 12, 10, 3, 14, 15), date_time_init(2017, 12, 14, 3, 14, 15).prev_occurring(:sunday)
end
def test_monday_with_default_beginning_of_week_set
with_bw_default(:saturday) do
- assert_equal date_time_init(2012,9,17,0,0,0), date_time_init(2012,9,18,0,0,0).monday
+ assert_equal date_time_init(2012, 9, 17, 0, 0, 0), date_time_init(2012, 9, 18, 0, 0, 0).monday
end
end
def test_sunday_with_default_beginning_of_week_set
with_bw_default(:wednesday) do
- assert_equal date_time_init(2012,9,23,23,59,59, Rational(999999999, 1000)), date_time_init(2012,9,19,0,0,0).sunday
+ assert_equal date_time_init(2012, 9, 23, 23, 59, 59, Rational(999999999, 1000)), date_time_init(2012, 9, 19, 0, 0, 0).sunday
end
end
def test_on_weekend_on_saturday
- assert date_time_init(2015,1,3,0,0,0).on_weekend?
- assert date_time_init(2015,1,3,15,15,10).on_weekend?
+ assert date_time_init(2015, 1, 3, 0, 0, 0).on_weekend?
+ assert date_time_init(2015, 1, 3, 15, 15, 10).on_weekend?
end
def test_on_weekend_on_sunday
- assert date_time_init(2015,1,4,0,0,0).on_weekend?
- assert date_time_init(2015,1,4,15,15,10).on_weekend?
+ assert date_time_init(2015, 1, 4, 0, 0, 0).on_weekend?
+ assert date_time_init(2015, 1, 4, 15, 15, 10).on_weekend?
end
def test_on_weekend_on_monday
- assert_not date_time_init(2015,1,5,0,0,0).on_weekend?
- assert_not date_time_init(2015,1,5,15,15,10).on_weekend?
+ assert_not date_time_init(2015, 1, 5, 0, 0, 0).on_weekend?
+ assert_not date_time_init(2015, 1, 5, 15, 15, 10).on_weekend?
end
def test_on_weekday_on_sunday
- assert_not date_time_init(2015,1,4,0,0,0).on_weekday?
- assert_not date_time_init(2015,1,4,15,15,10).on_weekday?
+ assert_not date_time_init(2015, 1, 4, 0, 0, 0).on_weekday?
+ assert_not date_time_init(2015, 1, 4, 15, 15, 10).on_weekday?
end
def test_on_weekday_on_monday
- assert date_time_init(2015,1,5,0,0,0).on_weekday?
- assert date_time_init(2015,1,5,15,15,10).on_weekday?
+ assert date_time_init(2015, 1, 5, 0, 0, 0).on_weekday?
+ assert date_time_init(2015, 1, 5, 15, 15, 10).on_weekday?
end
def with_bw_default(bw = :monday)
diff --git a/activesupport/test/core_ext/date_and_time_compatibility_test.rb b/activesupport/test/core_ext/date_and_time_compatibility_test.rb
index 11cb1469da..266829a452 100644
--- a/activesupport/test/core_ext/date_and_time_compatibility_test.rb
+++ b/activesupport/test/core_ext/date_and_time_compatibility_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'time_zone_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "time_zone_test_helpers"
class DateAndTimeCompatibilityTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
@@ -10,37 +12,72 @@ class DateAndTimeCompatibilityTest < ActiveSupport::TestCase
@date_time = DateTime.new(2016, 4, 23, 14, 11, 12, 0)
@utc_offset = 3600
@system_offset = -14400
- @zone = ActiveSupport::TimeZone['London']
+ @zone = ActiveSupport::TimeZone["London"]
end
def test_time_to_time_preserves_timezone
with_preserve_timezone(true) do
- with_env_tz 'US/Eastern' do
- time = Time.new(2016, 4, 23, 15, 11, 12, 3600).to_time
+ with_env_tz "US/Eastern" do
+ source = Time.new(2016, 4, 23, 15, 11, 12, 3600)
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
assert_equal @utc_offset, time.utc_offset
+ assert_equal source.object_id, time.object_id
end
end
end
def test_time_to_time_does_not_preserve_time_zone
with_preserve_timezone(false) do
- with_env_tz 'US/Eastern' do
- time = Time.new(2016, 4, 23, 15, 11, 12, 3600).to_time
+ with_env_tz "US/Eastern" do
+ source = Time.new(2016, 4, 23, 15, 11, 12, 3600)
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_equal @system_offset, time.utc_offset
+ assert_not_equal source.object_id, time.object_id
+ end
+ end
+ end
+
+ def test_time_to_time_frozen_preserves_timezone
+ with_preserve_timezone(true) do
+ with_env_tz "US/Eastern" do
+ source = Time.new(2016, 4, 23, 15, 11, 12, 3600).freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_equal @utc_offset, time.utc_offset
+ assert_equal source.object_id, time.object_id
+ assert_predicate time, :frozen?
+ end
+ end
+ end
+
+ def test_time_to_time_frozen_does_not_preserve_time_zone
+ with_preserve_timezone(false) do
+ with_env_tz "US/Eastern" do
+ source = Time.new(2016, 4, 23, 15, 11, 12, 3600).freeze
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
assert_equal @system_offset, time.utc_offset
+ assert_not_equal source.object_id, time.object_id
+ assert_not_predicate time, :frozen?
end
end
end
def test_datetime_to_time_preserves_timezone
with_preserve_timezone(true) do
- with_env_tz 'US/Eastern' do
- time = DateTime.new(2016, 4, 23, 15, 11, 12, Rational(1,24)).to_time
+ with_env_tz "US/Eastern" do
+ source = DateTime.new(2016, 4, 23, 15, 11, 12, Rational(1, 24))
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
@@ -51,27 +88,58 @@ class DateAndTimeCompatibilityTest < ActiveSupport::TestCase
def test_datetime_to_time_does_not_preserve_time_zone
with_preserve_timezone(false) do
- with_env_tz 'US/Eastern' do
- time = DateTime.new(2016, 4, 23, 15, 11, 12, Rational(1,24)).to_time
+ with_env_tz "US/Eastern" do
+ source = DateTime.new(2016, 4, 23, 15, 11, 12, Rational(1, 24))
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_equal @system_offset, time.utc_offset
+ end
+ end
+ end
+
+ def test_datetime_to_time_frozen_preserves_timezone
+ with_preserve_timezone(true) do
+ with_env_tz "US/Eastern" do
+ source = DateTime.new(2016, 4, 23, 15, 11, 12, Rational(1, 24)).freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_equal @utc_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
+ end
+ end
+ end
+
+ def test_datetime_to_time_frozen_does_not_preserve_time_zone
+ with_preserve_timezone(false) do
+ with_env_tz "US/Eastern" do
+ source = DateTime.new(2016, 4, 23, 15, 11, 12, Rational(1, 24)).freeze
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
assert_equal @system_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
end
end
end
def test_twz_to_time_preserves_timezone
with_preserve_timezone(true) do
- with_env_tz 'US/Eastern' do
- time = ActiveSupport::TimeWithZone.new(@utc_time, @zone).to_time
+ with_env_tz "US/Eastern" do
+ source = ActiveSupport::TimeWithZone.new(@utc_time, @zone)
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
assert_instance_of Time, time.getutc
assert_equal @utc_offset, time.utc_offset
- time = ActiveSupport::TimeWithZone.new(@date_time, @zone).to_time
+ source = ActiveSupport::TimeWithZone.new(@date_time, @zone)
+ time = source.to_time
assert_instance_of Time, time
assert_equal @date_time, time.getutc
@@ -83,15 +151,17 @@ class DateAndTimeCompatibilityTest < ActiveSupport::TestCase
def test_twz_to_time_does_not_preserve_time_zone
with_preserve_timezone(false) do
- with_env_tz 'US/Eastern' do
- time = ActiveSupport::TimeWithZone.new(@utc_time, @zone).to_time
+ with_env_tz "US/Eastern" do
+ source = ActiveSupport::TimeWithZone.new(@utc_time, @zone)
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
assert_instance_of Time, time.getutc
assert_equal @system_offset, time.utc_offset
- time = ActiveSupport::TimeWithZone.new(@date_time, @zone).to_time
+ source = ActiveSupport::TimeWithZone.new(@date_time, @zone)
+ time = source.to_time
assert_instance_of Time, time
assert_equal @date_time, time.getutc
@@ -101,10 +171,59 @@ class DateAndTimeCompatibilityTest < ActiveSupport::TestCase
end
end
+ def test_twz_to_time_frozen_preserves_timezone
+ with_preserve_timezone(true) do
+ with_env_tz "US/Eastern" do
+ source = ActiveSupport::TimeWithZone.new(@utc_time, @zone).freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_instance_of Time, time.getutc
+ assert_equal @utc_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
+
+ source = ActiveSupport::TimeWithZone.new(@date_time, @zone).freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @date_time, time.getutc
+ assert_instance_of Time, time.getutc
+ assert_equal @utc_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
+ end
+ end
+ end
+
+ def test_twz_to_time_frozen_does_not_preserve_time_zone
+ with_preserve_timezone(false) do
+ with_env_tz "US/Eastern" do
+ source = ActiveSupport::TimeWithZone.new(@utc_time, @zone).freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_instance_of Time, time.getutc
+ assert_equal @system_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
+
+ source = ActiveSupport::TimeWithZone.new(@date_time, @zone).freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @date_time, time.getutc
+ assert_instance_of Time, time.getutc
+ assert_equal @system_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
+ end
+ end
+ end
+
def test_string_to_time_preserves_timezone
with_preserve_timezone(true) do
- with_env_tz 'US/Eastern' do
- time = "2016-04-23T15:11:12+01:00".to_time
+ with_env_tz "US/Eastern" do
+ source = "2016-04-23T15:11:12+01:00"
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
@@ -115,12 +234,41 @@ class DateAndTimeCompatibilityTest < ActiveSupport::TestCase
def test_string_to_time_does_not_preserve_time_zone
with_preserve_timezone(false) do
- with_env_tz 'US/Eastern' do
- time = "2016-04-23T15:11:12+01:00".to_time
+ with_env_tz "US/Eastern" do
+ source = "2016-04-23T15:11:12+01:00"
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_equal @system_offset, time.utc_offset
+ end
+ end
+ end
+
+ def test_string_to_time_frozen_preserves_timezone
+ with_preserve_timezone(true) do
+ with_env_tz "US/Eastern" do
+ source = "2016-04-23T15:11:12+01:00".freeze
+ time = source.to_time
+
+ assert_instance_of Time, time
+ assert_equal @utc_time, time.getutc
+ assert_equal @utc_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
+ end
+ end
+ end
+
+ def test_string_to_time_frozen_does_not_preserve_time_zone
+ with_preserve_timezone(false) do
+ with_env_tz "US/Eastern" do
+ source = "2016-04-23T15:11:12+01:00".freeze
+ time = source.to_time
assert_instance_of Time, time
assert_equal @utc_time, time.getutc
assert_equal @system_offset, time.utc_offset
+ assert_not_predicate time, :frozen?
end
end
end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index 932675a50d..23d17956df 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -1,22 +1,24 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'core_ext/date_and_time_behavior'
-require 'time_zone_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "core_ext/date_and_time_behavior"
+require "time_zone_test_helpers"
class DateExtCalculationsTest < ActiveSupport::TestCase
- def date_time_init(year,month,day,*args)
- Date.new(year,month,day)
+ def date_time_init(year, month, day, *args)
+ Date.new(year, month, day)
end
include DateAndTimeBehavior
include TimeZoneTestHelpers
def test_yesterday_in_calendar_reform
- assert_equal Date.new(1582,10,4), Date.new(1582,10,15).yesterday
+ assert_equal Date.new(1582, 10, 4), Date.new(1582, 10, 15).yesterday
end
def test_tomorrow_in_calendar_reform
- assert_equal Date.new(1582,10,15), Date.new(1582,10,4).tomorrow
+ assert_equal Date.new(1582, 10, 15), Date.new(1582, 10, 4).tomorrow
end
def test_to_s
@@ -30,13 +32,24 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal "2005-02-21", date.to_s(:iso8601)
end
+ def test_to_s_with_single_digit_day
+ date = Date.new(2005, 2, 1)
+ assert_equal "2005-02-01", date.to_s
+ assert_equal "01 Feb", date.to_s(:short)
+ assert_equal "February 01, 2005", date.to_s(:long)
+ assert_equal "February 1st, 2005", date.to_s(:long_ordinal)
+ assert_equal "2005-02-01", date.to_s(:db)
+ assert_equal "01 Feb 2005", date.to_s(:rfc822)
+ assert_equal "2005-02-01", date.to_s(:iso8601)
+ end
+
def test_readable_inspect
assert_equal "Mon, 21 Feb 2005", Date.new(2005, 2, 21).readable_inspect
assert_equal Date.new(2005, 2, 21).readable_inspect, Date.new(2005, 2, 21).inspect
end
def test_to_time
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_equal Time, Date.new(2005, 2, 21).to_time.class
assert_equal Time.local(2005, 2, 21), Date.new(2005, 2, 21).to_time
assert_equal Time.local(2005, 2, 21).utc_offset, Date.new(2005, 2, 21).to_time.utc_offset
@@ -70,110 +83,102 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_change
- assert_equal Date.new(2005, 2, 21), Date.new(2005, 2, 11).change(:day => 21)
- assert_equal Date.new(2007, 5, 11), Date.new(2005, 2, 11).change(:year => 2007, :month => 5)
- assert_equal Date.new(2006,2,22), Date.new(2005,2,22).change(:year => 2006)
- assert_equal Date.new(2005,6,22), Date.new(2005,2,22).change(:month => 6)
+ assert_equal Date.new(2005, 2, 21), Date.new(2005, 2, 11).change(day: 21)
+ assert_equal Date.new(2007, 5, 11), Date.new(2005, 2, 11).change(year: 2007, month: 5)
+ assert_equal Date.new(2006, 2, 22), Date.new(2005, 2, 22).change(year: 2006)
+ assert_equal Date.new(2005, 6, 22), Date.new(2005, 2, 22).change(month: 6)
end
def test_sunday
- assert_equal Date.new(2008,3,2), Date.new(2008,3,02).sunday
- assert_equal Date.new(2008,3,2), Date.new(2008,2,29).sunday
+ assert_equal Date.new(2008, 3, 2), Date.new(2008, 3, 02).sunday
+ assert_equal Date.new(2008, 3, 2), Date.new(2008, 2, 29).sunday
end
def test_beginning_of_week_in_calendar_reform
- assert_equal Date.new(1582,10,1), Date.new(1582,10,15).beginning_of_week #friday
+ assert_equal Date.new(1582, 10, 1), Date.new(1582, 10, 15).beginning_of_week # friday
end
def test_end_of_week_in_calendar_reform
- assert_equal Date.new(1582,10,17), Date.new(1582,10,4).end_of_week #thursday
+ assert_equal Date.new(1582, 10, 17), Date.new(1582, 10, 4).end_of_week # thursday
end
def test_end_of_year
- assert_equal Date.new(2008,12,31).to_s, Date.new(2008,2,22).end_of_year.to_s
+ assert_equal Date.new(2008, 12, 31).to_s, Date.new(2008, 2, 22).end_of_year.to_s
end
def test_end_of_month
- assert_equal Date.new(2005,3,31), Date.new(2005,3,20).end_of_month
- assert_equal Date.new(2005,2,28), Date.new(2005,2,20).end_of_month
- assert_equal Date.new(2005,4,30), Date.new(2005,4,20).end_of_month
+ assert_equal Date.new(2005, 3, 31), Date.new(2005, 3, 20).end_of_month
+ assert_equal Date.new(2005, 2, 28), Date.new(2005, 2, 20).end_of_month
+ assert_equal Date.new(2005, 4, 30), Date.new(2005, 4, 20).end_of_month
end
def test_prev_year_in_leap_years
- assert_equal Date.new(1999,2,28), Date.new(2000,2,29).prev_year
+ assert_equal Date.new(1999, 2, 28), Date.new(2000, 2, 29).prev_year
end
def test_prev_year_in_calendar_reform
- assert_equal Date.new(1582,10,4), Date.new(1583,10,14).prev_year
- end
-
- def test_last_year
- assert_equal Date.new(2004,6,5), Date.new(2005,6,5).last_year
+ assert_equal Date.new(1582, 10, 4), Date.new(1583, 10, 14).prev_year
end
def test_last_year_in_leap_years
- assert_equal Date.new(1999,2,28), Date.new(2000,2,29).last_year
+ assert_equal Date.new(1999, 2, 28), Date.new(2000, 2, 29).last_year
end
def test_last_year_in_calendar_reform
- assert_equal Date.new(1582,10,4), Date.new(1583,10,14).last_year
+ assert_equal Date.new(1582, 10, 4), Date.new(1583, 10, 14).last_year
end
def test_next_year_in_leap_years
- assert_equal Date.new(2001,2,28), Date.new(2000,2,29).next_year
+ assert_equal Date.new(2001, 2, 28), Date.new(2000, 2, 29).next_year
end
def test_next_year_in_calendar_reform
- assert_equal Date.new(1582,10,4), Date.new(1581,10,10).next_year
+ assert_equal Date.new(1582, 10, 4), Date.new(1581, 10, 10).next_year
end
def test_advance
- assert_equal Date.new(2006,2,28), Date.new(2005,2,28).advance(:years => 1)
- assert_equal Date.new(2005,6,28), Date.new(2005,2,28).advance(:months => 4)
- assert_equal Date.new(2005,3,21), Date.new(2005,2,28).advance(:weeks => 3)
- assert_equal Date.new(2005,3,5), Date.new(2005,2,28).advance(:days => 5)
- assert_equal Date.new(2012,9,28), Date.new(2005,2,28).advance(:years => 7, :months => 7)
- assert_equal Date.new(2013,10,3), Date.new(2005,2,28).advance(:years => 7, :months => 19, :days => 5)
- assert_equal Date.new(2013,10,17), Date.new(2005,2,28).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
- assert_equal Date.new(2005,2,28), Date.new(2004,2,29).advance(:years => 1) #leap day plus one year
+ assert_equal Date.new(2006, 2, 28), Date.new(2005, 2, 28).advance(years: 1)
+ assert_equal Date.new(2005, 6, 28), Date.new(2005, 2, 28).advance(months: 4)
+ assert_equal Date.new(2005, 3, 21), Date.new(2005, 2, 28).advance(weeks: 3)
+ assert_equal Date.new(2005, 3, 5), Date.new(2005, 2, 28).advance(days: 5)
+ assert_equal Date.new(2012, 9, 28), Date.new(2005, 2, 28).advance(years: 7, months: 7)
+ assert_equal Date.new(2013, 10, 3), Date.new(2005, 2, 28).advance(years: 7, months: 19, days: 5)
+ assert_equal Date.new(2013, 10, 17), Date.new(2005, 2, 28).advance(years: 7, months: 19, weeks: 2, days: 5)
+ assert_equal Date.new(2005, 2, 28), Date.new(2004, 2, 29).advance(years: 1) # leap day plus one year
end
def test_advance_does_first_years_and_then_days
- assert_equal Date.new(2012, 2, 29), Date.new(2011, 2, 28).advance(:years => 1, :days => 1)
+ assert_equal Date.new(2012, 2, 29), Date.new(2011, 2, 28).advance(years: 1, days: 1)
# If day was done first we would jump to 2012-03-01 instead.
end
def test_advance_does_first_months_and_then_days
- assert_equal Date.new(2010, 3, 29), Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
+ assert_equal Date.new(2010, 3, 29), Date.new(2010, 2, 28).advance(months: 1, days: 1)
# If day was done first we would jump to 2010-04-01 instead.
end
def test_advance_in_calendar_reform
- assert_equal Date.new(1582,10,15), Date.new(1582,10,4).advance(:days => 1)
- assert_equal Date.new(1582,10,4), Date.new(1582,10,15).advance(:days => -1)
+ assert_equal Date.new(1582, 10, 15), Date.new(1582, 10, 4).advance(days: 1)
+ assert_equal Date.new(1582, 10, 4), Date.new(1582, 10, 15).advance(days: -1)
5.upto(14) do |day|
- assert_equal Date.new(1582,10,4), Date.new(1582,9,day).advance(:months => 1)
- assert_equal Date.new(1582,10,4), Date.new(1582,11,day).advance(:months => -1)
- assert_equal Date.new(1582,10,4), Date.new(1581,10,day).advance(:years => 1)
- assert_equal Date.new(1582,10,4), Date.new(1583,10,day).advance(:years => -1)
+ assert_equal Date.new(1582, 10, 4), Date.new(1582, 9, day).advance(months: 1)
+ assert_equal Date.new(1582, 10, 4), Date.new(1582, 11, day).advance(months: -1)
+ assert_equal Date.new(1582, 10, 4), Date.new(1581, 10, day).advance(years: 1)
+ assert_equal Date.new(1582, 10, 4), Date.new(1583, 10, day).advance(years: -1)
end
end
def test_last_week
- assert_equal Date.new(2005,5,9), Date.new(2005,5,17).last_week
- assert_equal Date.new(2006,12,25), Date.new(2007,1,7).last_week
- assert_equal Date.new(2010,2,12), Date.new(2010,2,19).last_week(:friday)
- assert_equal Date.new(2010,2,13), Date.new(2010,2,19).last_week(:saturday)
- assert_equal Date.new(2010,2,27), Date.new(2010,3,4).last_week(:saturday)
+ assert_equal Date.new(2005, 5, 9), Date.new(2005, 5, 17).last_week
+ assert_equal Date.new(2006, 12, 25), Date.new(2007, 1, 7).last_week
+ assert_equal Date.new(2010, 2, 12), Date.new(2010, 2, 19).last_week(:friday)
+ assert_equal Date.new(2010, 2, 13), Date.new(2010, 2, 19).last_week(:saturday)
+ assert_equal Date.new(2010, 2, 27), Date.new(2010, 3, 4).last_week(:saturday)
end
def test_next_week_in_calendar_reform
- assert_equal Date.new(1582,10,15), Date.new(1582,9,30).next_week(:friday)
- assert_equal Date.new(1582,10,18), Date.new(1582,10,4).next_week
- end
-
- def test_last_month_on_31st
- assert_equal Date.new(2004, 2, 29), Date.new(2004, 3, 31).last_month
+ assert_equal Date.new(1582, 10, 15), Date.new(1582, 9, 30).next_week(:friday)
+ assert_equal Date.new(1582, 10, 18), Date.new(1582, 10, 4).next_week
end
def test_last_quarter_on_31st
@@ -185,7 +190,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_yesterday_constructor_when_zone_is_not_set
- with_env_tz 'UTC' do
+ with_env_tz "UTC" do
with_tz_default do
assert_equal(Date.today - 1, Date.yesterday)
end
@@ -193,8 +198,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_yesterday_constructor_when_zone_is_set
- with_env_tz 'UTC' do
- with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
+ with_env_tz "UTC" do
+ with_tz_default ActiveSupport::TimeZone["Eastern Time (US & Canada)"] do # UTC -5
Time.stub(:now, Time.local(2000, 1, 1)) do
assert_equal Date.new(1999, 12, 30), Date.yesterday
end
@@ -207,7 +212,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_tomorrow_constructor_when_zone_is_not_set
- with_env_tz 'UTC' do
+ with_env_tz "UTC" do
with_tz_default do
assert_equal(Date.today + 1, Date.tomorrow)
end
@@ -215,8 +220,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_tomorrow_constructor_when_zone_is_set
- with_env_tz 'UTC' do
- with_tz_default ActiveSupport::TimeZone['Europe/Paris'] do # UTC +1
+ with_env_tz "UTC" do
+ with_tz_default ActiveSupport::TimeZone["Europe/Paris"] do # UTC +1
Time.stub(:now, Time.local(1999, 12, 31, 23)) do
assert_equal Date.new(2000, 1, 2), Date.tomorrow
end
@@ -225,84 +230,101 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_since
- assert_equal Time.local(2005,2,21,0,0,45), Date.new(2005,2,21).since(45)
+ assert_equal Time.local(2005, 2, 21, 0, 0, 45), Date.new(2005, 2, 21).since(45)
end
def test_since_when_zone_is_set
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'UTC' do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "UTC" do
with_tz_default zone do
- assert_equal zone.local(2005,2,21,0,0,45), Date.new(2005,2,21).since(45)
- assert_equal zone, Date.new(2005,2,21).since(45).time_zone
+ assert_equal zone.local(2005, 2, 21, 0, 0, 45), Date.new(2005, 2, 21).since(45)
+ assert_equal zone, Date.new(2005, 2, 21).since(45).time_zone
end
end
end
def test_ago
- assert_equal Time.local(2005,2,20,23,59,15), Date.new(2005,2,21).ago(45)
+ assert_equal Time.local(2005, 2, 20, 23, 59, 15), Date.new(2005, 2, 21).ago(45)
end
def test_ago_when_zone_is_set
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'UTC' do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "UTC" do
with_tz_default zone do
- assert_equal zone.local(2005,2,20,23,59,15), Date.new(2005,2,21).ago(45)
- assert_equal zone, Date.new(2005,2,21).ago(45).time_zone
+ assert_equal zone.local(2005, 2, 20, 23, 59, 15), Date.new(2005, 2, 21).ago(45)
+ assert_equal zone, Date.new(2005, 2, 21).ago(45).time_zone
end
end
end
def test_beginning_of_day
- assert_equal Time.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day
+ assert_equal Time.local(2005, 2, 21, 0, 0, 0), Date.new(2005, 2, 21).beginning_of_day
end
def test_middle_of_day
- assert_equal Time.local(2005,2,21,12,0,0), Date.new(2005,2,21).middle_of_day
+ assert_equal Time.local(2005, 2, 21, 12, 0, 0), Date.new(2005, 2, 21).middle_of_day
end
def test_beginning_of_day_when_zone_is_set
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'UTC' do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "UTC" do
with_tz_default zone do
- assert_equal zone.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day
- assert_equal zone, Date.new(2005,2,21).beginning_of_day.time_zone
+ assert_equal zone.local(2005, 2, 21, 0, 0, 0), Date.new(2005, 2, 21).beginning_of_day
+ assert_equal zone, Date.new(2005, 2, 21).beginning_of_day.time_zone
end
end
end
def test_end_of_day
- assert_equal Time.local(2005,2,21,23,59,59,Rational(999999999, 1000)), Date.new(2005,2,21).end_of_day
+ assert_equal Time.local(2005, 2, 21, 23, 59, 59, Rational(999999999, 1000)), Date.new(2005, 2, 21).end_of_day
end
def test_end_of_day_when_zone_is_set
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'UTC' do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "UTC" do
with_tz_default zone do
- assert_equal zone.local(2005,2,21,23,59,59,Rational(999999999, 1000)), Date.new(2005,2,21).end_of_day
- assert_equal zone, Date.new(2005,2,21).end_of_day.time_zone
+ assert_equal zone.local(2005, 2, 21, 23, 59, 59, Rational(999999999, 1000)), Date.new(2005, 2, 21).end_of_day
+ assert_equal zone, Date.new(2005, 2, 21).end_of_day.time_zone
+ end
+ end
+ end
+
+ def test_all_day
+ beginning_of_day = Time.local(2011, 6, 7, 0, 0, 0)
+ end_of_day = Time.local(2011, 6, 7, 23, 59, 59, Rational(999999999, 1000))
+ assert_equal beginning_of_day..end_of_day, Date.new(2011, 6, 7).all_day
+ end
+
+ def test_all_day_when_zone_is_set
+ zone = ActiveSupport::TimeZone["Hawaii"]
+ with_env_tz "UTC" do
+ with_tz_default zone do
+ beginning_of_day = zone.local(2011, 6, 7, 0, 0, 0)
+ end_of_day = zone.local(2011, 6, 7, 23, 59, 59, Rational(999999999, 1000))
+ assert_equal beginning_of_day..end_of_day, Date.new(2011, 6, 7).all_day
end
end
end
def test_all_week
- assert_equal Date.new(2011,6,6)..Date.new(2011,6,12), Date.new(2011,6,7).all_week
- assert_equal Date.new(2011,6,5)..Date.new(2011,6,11), Date.new(2011,6,7).all_week(:sunday)
+ assert_equal Date.new(2011, 6, 6)..Date.new(2011, 6, 12), Date.new(2011, 6, 7).all_week
+ assert_equal Date.new(2011, 6, 5)..Date.new(2011, 6, 11), Date.new(2011, 6, 7).all_week(:sunday)
end
def test_all_month
- assert_equal Date.new(2011,6,1)..Date.new(2011,6,30), Date.new(2011,6,7).all_month
+ assert_equal Date.new(2011, 6, 1)..Date.new(2011, 6, 30), Date.new(2011, 6, 7).all_month
end
def test_all_quarter
- assert_equal Date.new(2011,4,1)..Date.new(2011,6,30), Date.new(2011,6,7).all_quarter
+ assert_equal Date.new(2011, 4, 1)..Date.new(2011, 6, 30), Date.new(2011, 6, 7).all_quarter
end
def test_all_year
- assert_equal Date.new(2011,1,1)..Date.new(2011,12,31), Date.new(2011,6,7).all_year
+ assert_equal Date.new(2011, 1, 1)..Date.new(2011, 12, 31), Date.new(2011, 6, 7).all_year
end
def test_xmlschema
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
assert_match(/^1980-06-28T00:00:00-04:?00$/, Date.new(1980, 6, 28).xmlschema)
# these tests are only of interest on platforms where older dates #to_time fail over to DateTime
@@ -314,8 +336,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_xmlschema_when_zone_is_set
- with_env_tz 'UTC' do
- with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
+ with_env_tz "UTC" do
+ with_tz_default ActiveSupport::TimeZone["Eastern Time (US & Canada)"] do # UTC -5
assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
assert_match(/^1980-06-28T00:00:00-04:?00$/, Date.new(1980, 6, 28).xmlschema)
end
@@ -325,21 +347,21 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
def test_past
Date.stub(:current, Date.new(2000, 1, 1)) do
assert_equal true, Date.new(1999, 12, 31).past?
- assert_equal false, Date.new(2000,1,1).past?
- assert_equal false, Date.new(2000,1,2).past?
+ assert_equal false, Date.new(2000, 1, 1).past?
+ assert_equal false, Date.new(2000, 1, 2).past?
end
end
def test_future
Date.stub(:current, Date.new(2000, 1, 1)) do
assert_equal false, Date.new(1999, 12, 31).future?
- assert_equal false, Date.new(2000,1,1).future?
- assert_equal true, Date.new(2000,1,2).future?
+ assert_equal false, Date.new(2000, 1, 1).future?
+ assert_equal true, Date.new(2000, 1, 2).future?
end
end
def test_current_returns_date_today_when_zone_not_set
- with_env_tz 'US/Central' do
+ with_env_tz "US/Central" do
Time.stub(:now, Time.local(1999, 12, 31, 23)) do
assert_equal Date.today, Date.current
end
@@ -347,8 +369,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_current_returns_time_zone_today_when_zone_is_set
- Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Central' do
+ Time.zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "US/Central" do
assert_equal ::Time.zone.today, Date.current
end
ensure
@@ -356,9 +378,9 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def test_date_advance_should_not_change_passed_options_hash
- options = { :years => 3, :months => 11, :days => 2 }
- Date.new(2005,2,28).advance(options)
- assert_equal({ :years => 3, :months => 11, :days => 2 }, options)
+ options = { years: 3, months: 11, days: 2 }
+ Date.new(2005, 2, 28).advance(options)
+ assert_equal({ years: 3, months: 11, days: 2 }, options)
end
end
@@ -367,6 +389,10 @@ class DateExtBehaviorTest < ActiveSupport::TestCase
assert Date.new.acts_like_date?
end
+ def test_blank?
+ assert_not Date.new.blank?
+ end
+
def test_freeze_doesnt_clobber_memoized_instance_methods
assert_nothing_raised do
Date.today.freeze.inspect
@@ -379,4 +405,3 @@ class DateExtBehaviorTest < ActiveSupport::TestCase
end
end
end
-
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index fcd739c804..f4c9dfcb25 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -1,11 +1,13 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'core_ext/date_and_time_behavior'
-require 'time_zone_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "core_ext/date_and_time_behavior"
+require "time_zone_test_helpers"
class DateTimeExtCalculationsTest < ActiveSupport::TestCase
- def date_time_init(year,month,day,hour,minute,second,*args)
- DateTime.civil(year,month,day,hour,minute,second)
+ def date_time_init(year, month, day, hour, minute, second, usec = 0)
+ DateTime.civil(year, month, day, hour, minute, second + (usec / 1000000))
end
include DateAndTimeBehavior
@@ -35,26 +37,26 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_custom_date_format
- Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
- assert_equal '20050221143000', DateTime.new(2005, 2, 21, 14, 30, 0).to_s(:custom)
+ Time::DATE_FORMATS[:custom] = "%Y%m%d%H%M%S"
+ assert_equal "20050221143000", DateTime.new(2005, 2, 21, 14, 30, 0).to_s(:custom)
Time::DATE_FORMATS.delete(:custom)
end
def test_localtime
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_instance_of Time, DateTime.new(2016, 3, 11, 15, 11, 12, 0).localtime
assert_equal Time.local(2016, 3, 11, 10, 11, 12), DateTime.new(2016, 3, 11, 15, 11, 12, 0).localtime
assert_equal Time.local(2016, 3, 21, 11, 11, 12), DateTime.new(2016, 3, 21, 15, 11, 12, 0).localtime
- assert_equal Time.local(2016, 4, 1, 11, 11, 12), DateTime.new(2016, 4, 1, 16, 11, 12, Rational(1,24)).localtime
+ assert_equal Time.local(2016, 4, 1, 11, 11, 12), DateTime.new(2016, 4, 1, 16, 11, 12, Rational(1, 24)).localtime
end
end
def test_getlocal
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_instance_of Time, DateTime.new(2016, 3, 11, 15, 11, 12, 0).getlocal
assert_equal Time.local(2016, 3, 11, 10, 11, 12), DateTime.new(2016, 3, 11, 15, 11, 12, 0).getlocal
assert_equal Time.local(2016, 3, 21, 11, 11, 12), DateTime.new(2016, 3, 21, 15, 11, 12, 0).getlocal
- assert_equal Time.local(2016, 4, 1, 11, 11, 12), DateTime.new(2016, 4, 1, 16, 11, 12, Rational(1,24)).getlocal
+ assert_equal Time.local(2016, 4, 1, 11, 11, 12), DateTime.new(2016, 4, 1, 16, 11, 12, Rational(1, 24)).getlocal
end
end
@@ -67,10 +69,16 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_to_time
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_instance_of Time, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
- assert_equal Time.local(2005, 2, 21, 5, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
- assert_equal Time.local(2005, 2, 21, 5, 11, 12).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
+
+ if ActiveSupport.to_time_preserves_timezone
+ assert_equal Time.local(2005, 2, 21, 5, 11, 12).getlocal(0), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
+ assert_equal Time.local(2005, 2, 21, 5, 11, 12).getlocal(0).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
+ else
+ assert_equal Time.local(2005, 2, 21, 5, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
+ assert_equal Time.local(2005, 2, 21, 5, 11, 12).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
+ end
end
end
@@ -84,134 +92,136 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_seconds_since_midnight
- assert_equal 1,DateTime.civil(2005,1,1,0,0,1).seconds_since_midnight
- assert_equal 60,DateTime.civil(2005,1,1,0,1,0).seconds_since_midnight
- assert_equal 3660,DateTime.civil(2005,1,1,1,1,0).seconds_since_midnight
- assert_equal 86399,DateTime.civil(2005,1,1,23,59,59).seconds_since_midnight
+ assert_equal 1, DateTime.civil(2005, 1, 1, 0, 0, 1).seconds_since_midnight
+ assert_equal 60, DateTime.civil(2005, 1, 1, 0, 1, 0).seconds_since_midnight
+ assert_equal 3660, DateTime.civil(2005, 1, 1, 1, 1, 0).seconds_since_midnight
+ assert_equal 86399, DateTime.civil(2005, 1, 1, 23, 59, 59).seconds_since_midnight
end
def test_seconds_until_end_of_day
- assert_equal 0, DateTime.civil(2005,1,1,23,59,59).seconds_until_end_of_day
- assert_equal 1, DateTime.civil(2005,1,1,23,59,58).seconds_until_end_of_day
- assert_equal 60, DateTime.civil(2005,1,1,23,58,59).seconds_until_end_of_day
- assert_equal 3660, DateTime.civil(2005,1,1,22,58,59).seconds_until_end_of_day
- assert_equal 86399, DateTime.civil(2005,1,1,0,0,0).seconds_until_end_of_day
+ assert_equal 0, DateTime.civil(2005, 1, 1, 23, 59, 59).seconds_until_end_of_day
+ assert_equal 1, DateTime.civil(2005, 1, 1, 23, 59, 58).seconds_until_end_of_day
+ assert_equal 60, DateTime.civil(2005, 1, 1, 23, 58, 59).seconds_until_end_of_day
+ assert_equal 3660, DateTime.civil(2005, 1, 1, 22, 58, 59).seconds_until_end_of_day
+ assert_equal 86399, DateTime.civil(2005, 1, 1, 0, 0, 0).seconds_until_end_of_day
end
def test_beginning_of_day
- assert_equal DateTime.civil(2005,2,4,0,0,0), DateTime.civil(2005,2,4,10,10,10).beginning_of_day
+ assert_equal DateTime.civil(2005, 2, 4, 0, 0, 0), DateTime.civil(2005, 2, 4, 10, 10, 10).beginning_of_day
end
def test_middle_of_day
- assert_equal DateTime.civil(2005,2,4,12,0,0), DateTime.civil(2005,2,4,10,10,10).middle_of_day
+ assert_equal DateTime.civil(2005, 2, 4, 12, 0, 0), DateTime.civil(2005, 2, 4, 10, 10, 10).middle_of_day
end
def test_end_of_day
- assert_equal DateTime.civil(2005,2,4,23,59,59), DateTime.civil(2005,2,4,10,10,10).end_of_day
+ assert_equal DateTime.civil(2005, 2, 4, 23, 59, Rational(59999999999, 1000000000)), DateTime.civil(2005, 2, 4, 10, 10, 10).end_of_day
end
def test_beginning_of_hour
- assert_equal DateTime.civil(2005,2,4,19,0,0), DateTime.civil(2005,2,4,19,30,10).beginning_of_hour
+ assert_equal DateTime.civil(2005, 2, 4, 19, 0, 0), DateTime.civil(2005, 2, 4, 19, 30, 10).beginning_of_hour
end
def test_end_of_hour
- assert_equal DateTime.civil(2005,2,4,19,59,59), DateTime.civil(2005,2,4,19,30,10).end_of_hour
+ assert_equal DateTime.civil(2005, 2, 4, 19, 59, Rational(59999999999, 1000000000)), DateTime.civil(2005, 2, 4, 19, 30, 10).end_of_hour
end
def test_beginning_of_minute
- assert_equal DateTime.civil(2005,2,4,19,30,0), DateTime.civil(2005,2,4,19,30,10).beginning_of_minute
+ assert_equal DateTime.civil(2005, 2, 4, 19, 30, 0), DateTime.civil(2005, 2, 4, 19, 30, 10).beginning_of_minute
end
def test_end_of_minute
- assert_equal DateTime.civil(2005,2,4,19,30,59), DateTime.civil(2005,2,4,19,30,10).end_of_minute
+ assert_equal DateTime.civil(2005, 2, 4, 19, 30, Rational(59999999999, 1000000000)), DateTime.civil(2005, 2, 4, 19, 30, 10).end_of_minute
end
def test_end_of_month
- assert_equal DateTime.civil(2005,3,31,23,59,59), DateTime.civil(2005,3,20,10,10,10).end_of_month
- assert_equal DateTime.civil(2005,2,28,23,59,59), DateTime.civil(2005,2,20,10,10,10).end_of_month
- assert_equal DateTime.civil(2005,4,30,23,59,59), DateTime.civil(2005,4,20,10,10,10).end_of_month
- end
-
- def test_last_year
- assert_equal DateTime.civil(2004,6,5,10), DateTime.civil(2005,6,5,10,0,0).last_year
+ assert_equal DateTime.civil(2005, 3, 31, 23, 59, Rational(59999999999, 1000000000)), DateTime.civil(2005, 3, 20, 10, 10, 10).end_of_month
+ assert_equal DateTime.civil(2005, 2, 28, 23, 59, Rational(59999999999, 1000000000)), DateTime.civil(2005, 2, 20, 10, 10, 10).end_of_month
+ assert_equal DateTime.civil(2005, 4, 30, 23, 59, Rational(59999999999, 1000000000)), DateTime.civil(2005, 4, 20, 10, 10, 10).end_of_month
end
def test_ago
- assert_equal DateTime.civil(2005,2,22,10,10,9), DateTime.civil(2005,2,22,10,10,10).ago(1)
- assert_equal DateTime.civil(2005,2,22,9,10,10), DateTime.civil(2005,2,22,10,10,10).ago(3600)
- assert_equal DateTime.civil(2005,2,20,10,10,10), DateTime.civil(2005,2,22,10,10,10).ago(86400*2)
- assert_equal DateTime.civil(2005,2,20,9,9,45), DateTime.civil(2005,2,22,10,10,10).ago(86400*2 + 3600 + 25)
+ assert_equal DateTime.civil(2005, 2, 22, 10, 10, 9), DateTime.civil(2005, 2, 22, 10, 10, 10).ago(1)
+ assert_equal DateTime.civil(2005, 2, 22, 9, 10, 10), DateTime.civil(2005, 2, 22, 10, 10, 10).ago(3600)
+ assert_equal DateTime.civil(2005, 2, 20, 10, 10, 10), DateTime.civil(2005, 2, 22, 10, 10, 10).ago(86400 * 2)
+ assert_equal DateTime.civil(2005, 2, 20, 9, 9, 45), DateTime.civil(2005, 2, 22, 10, 10, 10).ago(86400 * 2 + 3600 + 25)
end
def test_since
- assert_equal DateTime.civil(2005,2,22,10,10,11), DateTime.civil(2005,2,22,10,10,10).since(1)
- assert_equal DateTime.civil(2005,2,22,11,10,10), DateTime.civil(2005,2,22,10,10,10).since(3600)
- assert_equal DateTime.civil(2005,2,24,10,10,10), DateTime.civil(2005,2,22,10,10,10).since(86400*2)
- assert_equal DateTime.civil(2005,2,24,11,10,35), DateTime.civil(2005,2,22,10,10,10).since(86400*2 + 3600 + 25)
- assert_equal DateTime.civil(2005,2,22,10,10,11), DateTime.civil(2005,2,22,10,10,10).since(1.333)
- assert_equal DateTime.civil(2005,2,22,10,10,12), DateTime.civil(2005,2,22,10,10,10).since(1.667)
+ assert_equal DateTime.civil(2005, 2, 22, 10, 10, 11), DateTime.civil(2005, 2, 22, 10, 10, 10).since(1)
+ assert_equal DateTime.civil(2005, 2, 22, 11, 10, 10), DateTime.civil(2005, 2, 22, 10, 10, 10).since(3600)
+ assert_equal DateTime.civil(2005, 2, 24, 10, 10, 10), DateTime.civil(2005, 2, 22, 10, 10, 10).since(86400 * 2)
+ assert_equal DateTime.civil(2005, 2, 24, 11, 10, 35), DateTime.civil(2005, 2, 22, 10, 10, 10).since(86400 * 2 + 3600 + 25)
+ assert_equal DateTime.civil(2005, 2, 22, 10, 10, 11), DateTime.civil(2005, 2, 22, 10, 10, 10).since(1.333)
+ assert_equal DateTime.civil(2005, 2, 22, 10, 10, 12), DateTime.civil(2005, 2, 22, 10, 10, 10).since(1.667)
end
def test_change
- assert_equal DateTime.civil(2006,2,22,15,15,10), DateTime.civil(2005,2,22,15,15,10).change(:year => 2006)
- assert_equal DateTime.civil(2005,6,22,15,15,10), DateTime.civil(2005,2,22,15,15,10).change(:month => 6)
- assert_equal DateTime.civil(2012,9,22,15,15,10), DateTime.civil(2005,2,22,15,15,10).change(:year => 2012, :month => 9)
- assert_equal DateTime.civil(2005,2,22,16), DateTime.civil(2005,2,22,15,15,10).change(:hour => 16)
- assert_equal DateTime.civil(2005,2,22,16,45), DateTime.civil(2005,2,22,15,15,10).change(:hour => 16, :min => 45)
- assert_equal DateTime.civil(2005,2,22,15,45), DateTime.civil(2005,2,22,15,15,10).change(:min => 45)
+ assert_equal DateTime.civil(2006, 2, 22, 15, 15, 10), DateTime.civil(2005, 2, 22, 15, 15, 10).change(year: 2006)
+ assert_equal DateTime.civil(2005, 6, 22, 15, 15, 10), DateTime.civil(2005, 2, 22, 15, 15, 10).change(month: 6)
+ assert_equal DateTime.civil(2012, 9, 22, 15, 15, 10), DateTime.civil(2005, 2, 22, 15, 15, 10).change(year: 2012, month: 9)
+ assert_equal DateTime.civil(2005, 2, 22, 16), DateTime.civil(2005, 2, 22, 15, 15, 10).change(hour: 16)
+ assert_equal DateTime.civil(2005, 2, 22, 16, 45), DateTime.civil(2005, 2, 22, 15, 15, 10).change(hour: 16, min: 45)
+ assert_equal DateTime.civil(2005, 2, 22, 15, 45), DateTime.civil(2005, 2, 22, 15, 15, 10).change(min: 45)
+
+ # datetime with non-zero offset
+ assert_equal DateTime.civil(2005, 2, 22, 15, 15, 10, Rational(-5, 24)), DateTime.civil(2005, 2, 22, 15, 15, 10, 0).change(offset: Rational(-5, 24))
# datetime with fractions of a second
- assert_equal DateTime.civil(2005,2,1,15,15,10.7), DateTime.civil(2005,2,22,15,15,10.7).change(:day => 1)
+ assert_equal DateTime.civil(2005, 2, 1, 15, 15, 10.7), DateTime.civil(2005, 2, 22, 15, 15, 10.7).change(day: 1)
+ assert_equal DateTime.civil(2005, 1, 2, 11, 22, Rational(33000008, 1000000)), DateTime.civil(2005, 1, 2, 11, 22, 33).change(usec: 8)
+ assert_equal DateTime.civil(2005, 1, 2, 11, 22, Rational(33000008, 1000000)), DateTime.civil(2005, 1, 2, 11, 22, 33).change(nsec: 8000)
+ assert_raise(ArgumentError) { DateTime.civil(2005, 1, 2, 11, 22, 0).change(usec: 1, nsec: 1) }
+ assert_raise(ArgumentError) { DateTime.civil(2005, 1, 2, 11, 22, 0).change(usec: 1000000) }
+ assert_raise(ArgumentError) { DateTime.civil(2005, 1, 2, 11, 22, 0).change(nsec: 1000000000) }
+ assert_nothing_raised { DateTime.civil(2005, 1, 2, 11, 22, 0).change(usec: 999999) }
+ assert_nothing_raised { DateTime.civil(2005, 1, 2, 11, 22, 0).change(nsec: 999999999) }
end
def test_advance
- assert_equal DateTime.civil(2006,2,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 1)
- assert_equal DateTime.civil(2005,6,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:months => 4)
- assert_equal DateTime.civil(2005,3,21,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:weeks => 3)
- assert_equal DateTime.civil(2005,3,5,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:days => 5)
- assert_equal DateTime.civil(2012,9,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 7)
- assert_equal DateTime.civil(2013,10,3,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5)
- assert_equal DateTime.civil(2013,10,17,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
- assert_equal DateTime.civil(2001,12,27,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
- assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
- assert_equal DateTime.civil(2005,2,28,20,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5)
- assert_equal DateTime.civil(2005,2,28,15,22,10), DateTime.civil(2005,2,28,15,15,10).advance(:minutes => 7)
- assert_equal DateTime.civil(2005,2,28,15,15,19), DateTime.civil(2005,2,28,15,15,10).advance(:seconds => 9)
- assert_equal DateTime.civil(2005,2,28,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
- assert_equal DateTime.civil(2005,2,28,10,8,1), DateTime.civil(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
- assert_equal DateTime.civil(2013,10,17,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal DateTime.civil(2006, 2, 28, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(years: 1)
+ assert_equal DateTime.civil(2005, 6, 28, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(months: 4)
+ assert_equal DateTime.civil(2005, 3, 21, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(weeks: 3)
+ assert_equal DateTime.civil(2005, 3, 5, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(days: 5)
+ assert_equal DateTime.civil(2012, 9, 28, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 7)
+ assert_equal DateTime.civil(2013, 10, 3, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, days: 5)
+ assert_equal DateTime.civil(2013, 10, 17, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, weeks: 2, days: 5)
+ assert_equal DateTime.civil(2001, 12, 27, 15, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(years: -3, months: -2, days: -1)
+ assert_equal DateTime.civil(2005, 2, 28, 15, 15, 10), DateTime.civil(2004, 2, 29, 15, 15, 10).advance(years: 1) # leap day plus one year
+ assert_equal DateTime.civil(2005, 2, 28, 20, 15, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(hours: 5)
+ assert_equal DateTime.civil(2005, 2, 28, 15, 22, 10), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(minutes: 7)
+ assert_equal DateTime.civil(2005, 2, 28, 15, 15, 19), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(seconds: 9)
+ assert_equal DateTime.civil(2005, 2, 28, 20, 22, 19), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(hours: 5, minutes: 7, seconds: 9)
+ assert_equal DateTime.civil(2005, 2, 28, 10, 8, 1), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(hours: -5, minutes: -7, seconds: -9)
+ assert_equal DateTime.civil(2013, 10, 17, 20, 22, 19), DateTime.civil(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, weeks: 2, days: 5, hours: 5, minutes: 7, seconds: 9)
end
def test_advance_partial_days
- assert_equal DateTime.civil(2012,9,29,13,15,10), DateTime.civil(2012,9,28,1,15,10).advance(:days => 1.5)
- assert_equal DateTime.civil(2012,9,28,13,15,10), DateTime.civil(2012,9,28,1,15,10).advance(:days => 0.5)
- assert_equal DateTime.civil(2012,10,29,13,15,10), DateTime.civil(2012,9,28,1,15,10).advance(:days => 1.5, :months => 1)
+ assert_equal DateTime.civil(2012, 9, 29, 13, 15, 10), DateTime.civil(2012, 9, 28, 1, 15, 10).advance(days: 1.5)
+ assert_equal DateTime.civil(2012, 9, 28, 13, 15, 10), DateTime.civil(2012, 9, 28, 1, 15, 10).advance(days: 0.5)
+ assert_equal DateTime.civil(2012, 10, 29, 13, 15, 10), DateTime.civil(2012, 9, 28, 1, 15, 10).advance(days: 1.5, months: 1)
end
def test_advanced_processes_first_the_date_deltas_and_then_the_time_deltas
# If the time deltas were processed first, the following datetimes would be advanced to 2010/04/01 instead.
- assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59, 59).advance(:months => 1, :seconds => 1)
- assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59).advance(:months => 1, :minutes => 1)
- assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23).advance(:months => 1, :hours => 1)
- assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 22, 58, 59).advance(:months => 1, :hours => 1, :minutes => 1, :seconds => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59, 59).advance(months: 1, seconds: 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59).advance(months: 1, minutes: 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23).advance(months: 1, hours: 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 22, 58, 59).advance(months: 1, hours: 1, minutes: 1, seconds: 1)
end
def test_last_week
- assert_equal DateTime.civil(2005,2,21), DateTime.civil(2005,3,1,15,15,10).last_week
- assert_equal DateTime.civil(2005,2,22), DateTime.civil(2005,3,1,15,15,10).last_week(:tuesday)
- assert_equal DateTime.civil(2005,2,25), DateTime.civil(2005,3,1,15,15,10).last_week(:friday)
- assert_equal DateTime.civil(2006,10,30), DateTime.civil(2006,11,6,0,0,0).last_week
- assert_equal DateTime.civil(2006,11,15), DateTime.civil(2006,11,23,0,0,0).last_week(:wednesday)
+ assert_equal DateTime.civil(2005, 2, 21), DateTime.civil(2005, 3, 1, 15, 15, 10).last_week
+ assert_equal DateTime.civil(2005, 2, 22), DateTime.civil(2005, 3, 1, 15, 15, 10).last_week(:tuesday)
+ assert_equal DateTime.civil(2005, 2, 25), DateTime.civil(2005, 3, 1, 15, 15, 10).last_week(:friday)
+ assert_equal DateTime.civil(2006, 10, 30), DateTime.civil(2006, 11, 6, 0, 0, 0).last_week
+ assert_equal DateTime.civil(2006, 11, 15), DateTime.civil(2006, 11, 23, 0, 0, 0).last_week(:wednesday)
end
def test_date_time_should_have_correct_last_week_for_leap_year
assert_equal DateTime.civil(2016, 2, 29), DateTime.civil(2016, 3, 7).last_week
end
- def test_last_month_on_31st
- assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 3, 31).last_month
- end
-
def test_last_quarter_on_31st
assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 5, 31).last_quarter
end
@@ -227,56 +237,56 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
def test_today_with_offset
Date.stub(:current, Date.new(2000, 1, 1)) do
- assert_equal false, DateTime.civil(1999,12,31,23,59,59, Rational(-18000, 86400)).today?
- assert_equal true, DateTime.civil(2000,1,1,0,0,0, Rational(-18000, 86400)).today?
- assert_equal true, DateTime.civil(2000,1,1,23,59,59, Rational(-18000, 86400)).today?
- assert_equal false, DateTime.civil(2000,1,2,0,0,0, Rational(-18000, 86400)).today?
+ assert_equal false, DateTime.civil(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)).today?
+ assert_equal true, DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-18000, 86400)).today?
+ assert_equal true, DateTime.civil(2000, 1, 1, 23, 59, 59, Rational(-18000, 86400)).today?
+ assert_equal false, DateTime.civil(2000, 1, 2, 0, 0, 0, Rational(-18000, 86400)).today?
end
end
def test_today_without_offset
Date.stub(:current, Date.new(2000, 1, 1)) do
- assert_equal false, DateTime.civil(1999,12,31,23,59,59).today?
- assert_equal true, DateTime.civil(2000,1,1,0).today?
- assert_equal true, DateTime.civil(2000,1,1,23,59,59).today?
- assert_equal false, DateTime.civil(2000,1,2,0).today?
+ assert_equal false, DateTime.civil(1999, 12, 31, 23, 59, 59).today?
+ assert_equal true, DateTime.civil(2000, 1, 1, 0).today?
+ assert_equal true, DateTime.civil(2000, 1, 1, 23, 59, 59).today?
+ assert_equal false, DateTime.civil(2000, 1, 2, 0).today?
end
end
def test_past_with_offset
- DateTime.stub(:current, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) do
- assert_equal true, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).past?
- assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).past?
- assert_equal false, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).past?
+ DateTime.stub(:current, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400))) do
+ assert_equal true, DateTime.civil(2005, 2, 10, 15, 30, 44, Rational(-18000, 86400)).past?
+ assert_equal false, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400)).past?
+ assert_equal false, DateTime.civil(2005, 2, 10, 15, 30, 46, Rational(-18000, 86400)).past?
end
end
def test_past_without_offset
- DateTime.stub(:current, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) do
- assert_equal true, DateTime.civil(2005,2,10,20,30,44).past?
- assert_equal false, DateTime.civil(2005,2,10,20,30,45).past?
- assert_equal false, DateTime.civil(2005,2,10,20,30,46).past?
+ DateTime.stub(:current, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400))) do
+ assert_equal true, DateTime.civil(2005, 2, 10, 20, 30, 44).past?
+ assert_equal false, DateTime.civil(2005, 2, 10, 20, 30, 45).past?
+ assert_equal false, DateTime.civil(2005, 2, 10, 20, 30, 46).past?
end
end
def test_future_with_offset
- DateTime.stub(:current, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) do
- assert_equal false, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).future?
- assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).future?
- assert_equal true, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).future?
+ DateTime.stub(:current, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400))) do
+ assert_equal false, DateTime.civil(2005, 2, 10, 15, 30, 44, Rational(-18000, 86400)).future?
+ assert_equal false, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400)).future?
+ assert_equal true, DateTime.civil(2005, 2, 10, 15, 30, 46, Rational(-18000, 86400)).future?
end
end
def test_future_without_offset
- DateTime.stub(:current, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) do
- assert_equal false, DateTime.civil(2005,2,10,20,30,44).future?
- assert_equal false, DateTime.civil(2005,2,10,20,30,45).future?
- assert_equal true, DateTime.civil(2005,2,10,20,30,46).future?
+ DateTime.stub(:current, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400))) do
+ assert_equal false, DateTime.civil(2005, 2, 10, 20, 30, 44).future?
+ assert_equal false, DateTime.civil(2005, 2, 10, 20, 30, 45).future?
+ assert_equal true, DateTime.civil(2005, 2, 10, 20, 30, 46).future?
end
end
def test_current_returns_date_today_when_zone_is_not_set
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
Time.stub(:now, Time.local(1999, 12, 31, 23, 59, 59)) do
assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
@@ -284,8 +294,8 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_current_returns_time_zone_today_when_zone_is_set
- Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
+ Time.zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "US/Eastern" do
Time.stub(:now, Time.local(1999, 12, 31, 23, 59, 59)) do
assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
@@ -299,7 +309,7 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_current_with_time_zone
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_kind_of DateTime, DateTime.current
end
end
@@ -312,6 +322,10 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert DateTime.new.acts_like_time?
end
+ def test_blank?
+ assert_not DateTime.new.blank?
+ end
+
def test_utc?
assert_equal true, DateTime.civil(2005, 2, 21, 10, 11, 12).utc?
assert_equal true, DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc?
@@ -323,8 +337,8 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal 0, DateTime.civil(2005, 2, 21, 10, 11, 12).utc_offset
assert_equal 0, DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc_offset
assert_equal 21600, DateTime.civil(2005, 2, 21, 10, 11, 12, 0.25).utc_offset
- assert_equal( -21600, DateTime.civil(2005, 2, 21, 10, 11, 12, -0.25).utc_offset )
- assert_equal( -18000, DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).utc_offset )
+ assert_equal(-21600, DateTime.civil(2005, 2, 21, 10, 11, 12, -0.25).utc_offset)
+ assert_equal(-18000, DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).utc_offset)
end
def test_utc
@@ -337,15 +351,15 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_formatted_offset_with_utc
- assert_equal '+00:00', DateTime.civil(2000).formatted_offset
- assert_equal '+0000', DateTime.civil(2000).formatted_offset(false)
- assert_equal 'UTC', DateTime.civil(2000).formatted_offset(true, 'UTC')
+ assert_equal "+00:00", DateTime.civil(2000).formatted_offset
+ assert_equal "+0000", DateTime.civil(2000).formatted_offset(false)
+ assert_equal "UTC", DateTime.civil(2000).formatted_offset(true, "UTC")
end
def test_formatted_offset_with_local
dt = DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24))
- assert_equal '-05:00', dt.formatted_offset
- assert_equal '-0500', dt.formatted_offset(false)
+ assert_equal "-05:00", dt.formatted_offset
+ assert_equal "-0500", dt.formatted_offset(false)
end
def test_compare_with_time
@@ -361,16 +375,16 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_compare_with_time_with_zone
- assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
- assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
- assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
+ assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
+ assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
+ assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone["UTC"]))
end
def test_compare_with_string
assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59).to_s
assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
- assert_equal( -1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1).to_s)
- assert_equal nil, DateTime.civil(2000) <=> "Invalid as Time"
+ assert_equal(-1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1).to_s)
+ assert_nil DateTime.civil(2000) <=> "Invalid as Time"
end
def test_compare_with_integer
@@ -393,27 +407,27 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
def test_to_f
assert_equal 946684800.0, DateTime.civil(2000).to_f
- assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f
- assert_equal 946684800.5, DateTime.civil(1999,12,31,19,0,0.5,Rational(-5,24)).to_f
+ assert_equal 946684800.0, DateTime.civil(1999, 12, 31, 19, 0, 0, Rational(-5, 24)).to_f
+ assert_equal 946684800.5, DateTime.civil(1999, 12, 31, 19, 0, 0.5, Rational(-5, 24)).to_f
end
def test_to_i
assert_equal 946684800, DateTime.civil(2000).to_i
- assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
+ assert_equal 946684800, DateTime.civil(1999, 12, 31, 19, 0, 0, Rational(-5, 24)).to_i
end
def test_usec
assert_equal 0, DateTime.civil(2000).usec
- assert_equal 500000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).usec
+ assert_equal 500000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1, 2)).usec
end
def test_nsec
assert_equal 0, DateTime.civil(2000).nsec
- assert_equal 500000000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).nsec
+ assert_equal 500000000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1, 2)).nsec
end
def test_subsec
assert_equal 0, DateTime.civil(2000).subsec
- assert_equal Rational(1,2), DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).subsec
+ assert_equal Rational(1, 2), DateTime.civil(2000, 1, 1, 0, 0, Rational(1, 2)).subsec
end
end
diff --git a/activesupport/test/core_ext/digest/uuid_test.rb b/activesupport/test/core_ext/digest/uuid_test.rb
index 08e0a1d6e1..94cb7d9418 100644
--- a/activesupport/test/core_ext/digest/uuid_test.rb
+++ b/activesupport/test/core_ext/digest/uuid_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/digest/uuid'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/digest/uuid"
class DigestUUIDExt < ActiveSupport::TestCase
def test_v3_uuids
@@ -18,7 +20,7 @@ class DigestUUIDExt < ActiveSupport::TestCase
def test_invalid_hash_class
assert_raise ArgumentError do
- Digest::UUID.uuid_from_hash(Digest::SHA2, Digest::UUID::OID_NAMESPACE, '1.2.3')
+ Digest::UUID.uuid_from_hash(Digest::SHA2, Digest::UUID::OID_NAMESPACE, "1.2.3")
end
end
end
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index ce69364c68..4a02f27def 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -1,8 +1,10 @@
-require 'abstract_unit'
-require 'active_support/inflector'
-require 'active_support/time'
-require 'active_support/json'
-require 'time_zone_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/inflector"
+require "active_support/time"
+require "active_support/json"
+require "time_zone_test_helpers"
class DurationTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
@@ -12,7 +14,7 @@ class DurationTest < ActiveSupport::TestCase
assert d.is_a?(ActiveSupport::Duration)
assert_kind_of ActiveSupport::Duration, d
assert_kind_of Numeric, d
- assert_kind_of Fixnum, d
+ assert_kind_of Integer, d
assert !d.is_a?(Hash)
k = Class.new
@@ -21,7 +23,7 @@ class DurationTest < ActiveSupport::TestCase
end
def test_instance_of
- assert 1.minute.instance_of?(Fixnum)
+ assert 1.minute.instance_of?(1.class)
assert 2.days.instance_of?(ActiveSupport::Duration)
assert !3.second.instance_of?(Numeric)
end
@@ -29,14 +31,14 @@ class DurationTest < ActiveSupport::TestCase
def test_threequals
assert ActiveSupport::Duration === 1.day
assert !(ActiveSupport::Duration === 1.day.to_i)
- assert !(ActiveSupport::Duration === 'foo')
+ assert !(ActiveSupport::Duration === "foo")
end
def test_equals
assert 1.day == 1.day
assert 1.day == 1.day.to_i
assert 1.day.to_i == 1.day
- assert !(1.day == 'foo')
+ assert !(1.day == "foo")
end
def test_to_s
@@ -54,28 +56,30 @@ class DurationTest < ActiveSupport::TestCase
assert !1.eql?(1.second)
assert 1.minute.eql?(180.seconds - 2.minutes)
assert !1.minute.eql?(60)
- assert !1.minute.eql?('foo')
+ assert !1.minute.eql?("foo")
end
def test_inspect
- assert_equal '0 seconds', 0.seconds.inspect
- assert_equal '1 month', 1.month.inspect
- assert_equal '1 month and 1 day', (1.month + 1.day).inspect
- assert_equal '6 months and -2 days', (6.months - 2.days).inspect
- assert_equal '10 seconds', 10.seconds.inspect
- assert_equal '10 years, 2 months, and 1 day', (10.years + 2.months + 1.day).inspect
- assert_equal '10 years, 2 months, and 1 day', (10.years + 1.month + 1.day + 1.month).inspect
- assert_equal '10 years, 2 months, and 1 day', (1.day + 10.years + 2.months).inspect
- assert_equal '7 days', 7.days.inspect
- assert_equal '1 week', 1.week.inspect
- assert_equal '2 weeks', 1.fortnight.inspect
+ assert_equal "0 seconds", 0.seconds.inspect
+ assert_equal "1 month", 1.month.inspect
+ assert_equal "1 month and 1 day", (1.month + 1.day).inspect
+ assert_equal "6 months and -2 days", (6.months - 2.days).inspect
+ assert_equal "10 seconds", 10.seconds.inspect
+ assert_equal "10 years, 2 months, and 1 day", (10.years + 2.months + 1.day).inspect
+ assert_equal "10 years, 2 months, and 1 day", (10.years + 1.month + 1.day + 1.month).inspect
+ assert_equal "10 years, 2 months, and 1 day", (1.day + 10.years + 2.months).inspect
+ assert_equal "7 days", 7.days.inspect
+ assert_equal "1 week", 1.week.inspect
+ assert_equal "2 weeks", 1.fortnight.inspect
+ assert_equal "0 seconds", (10 % 5.seconds).inspect
+ assert_equal "10 minutes", (10.minutes + 0.seconds).inspect
end
def test_inspect_locale
current_locale = I18n.default_locale
I18n.default_locale = :de
- I18n.backend.store_translations(:de, { support: { array: { last_word_connector: ' und ' } } })
- assert_equal '10 years, 1 month und 1 day', (10.years + 1.month + 1.day).inspect
+ I18n.backend.store_translations(:de, support: { array: { last_word_connector: " und " } })
+ assert_equal "10 years, 1 month und 1 day", (10.years + 1.month + 1.day).inspect
ensure
I18n.default_locale = current_locale
end
@@ -84,12 +88,81 @@ class DurationTest < ActiveSupport::TestCase
assert_nothing_raised { Date.today - Date.today }
end
+ def test_plus
+ assert_equal 2.seconds, 1.second + 1.second
+ assert_instance_of ActiveSupport::Duration, 1.second + 1.second
+ assert_equal 2.seconds, 1.second + 1
+ assert_instance_of ActiveSupport::Duration, 1.second + 1
+ end
+
+ def test_minus
+ assert_equal 1.second, 2.seconds - 1.second
+ assert_instance_of ActiveSupport::Duration, 2.seconds - 1.second
+ assert_equal 1.second, 2.seconds - 1
+ assert_instance_of ActiveSupport::Duration, 2.seconds - 1
+ assert_equal 1.second, 2 - 1.second
+ assert_instance_of ActiveSupport::Duration, 2.seconds - 1
+ end
+
+ def test_multiply
+ assert_equal 7.days, 1.day * 7
+ assert_instance_of ActiveSupport::Duration, 1.day * 7
+ assert_equal 86400, 1.day * 1.second
+ end
+
+ def test_divide
+ assert_equal 1.day, 7.days / 7
+ assert_instance_of ActiveSupport::Duration, 7.days / 7
+
+ assert_equal 1.hour, 1.day / 24
+ assert_instance_of ActiveSupport::Duration, 1.day / 24
+
+ assert_equal 24, 86400 / 1.hour
+ assert_kind_of Integer, 86400 / 1.hour
+
+ assert_equal 24, 1.day / 1.hour
+ assert_kind_of Integer, 1.day / 1.hour
+
+ assert_equal 1, 1.day / 1.day
+ assert_kind_of Integer, 1.day / 1.hour
+ end
+
+ def test_modulo
+ assert_equal 1.minute, 5.minutes % 120
+ assert_instance_of ActiveSupport::Duration, 5.minutes % 120
+
+ assert_equal 1.minute, 5.minutes % 2.minutes
+ assert_instance_of ActiveSupport::Duration, 5.minutes % 2.minutes
+
+ assert_equal 1.minute, 5.minutes % 120.seconds
+ assert_instance_of ActiveSupport::Duration, 5.minutes % 120.seconds
+
+ assert_equal 5.minutes, 5.minutes % 1.hour
+ assert_instance_of ActiveSupport::Duration, 5.minutes % 1.hour
+
+ assert_equal 1.day, 36.days % 604800
+ assert_instance_of ActiveSupport::Duration, 36.days % 604800
+
+ assert_equal 1.day, 36.days % 7.days
+ assert_instance_of ActiveSupport::Duration, 36.days % 7.days
+
+ assert_equal 800.seconds, 8000 % 1.hour
+ assert_instance_of ActiveSupport::Duration, 8000 % 1.hour
+
+ assert_equal 1.month, 13.months % 1.year
+ assert_instance_of ActiveSupport::Duration, 13.months % 1.year
+ end
+
+ def test_date_added_with_multiplied_duration
+ assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 1.day * 2
+ end
+
def test_plus_with_time
assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
end
def test_time_plus_duration_returns_same_time_datatype
- twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Moscow'] , Time.utc(2016,4,28,00,45))
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Moscow"], Time.utc(2016, 4, 28, 00, 45))
now = Time.now.utc
%w( second minute hour day week month year ).each do |unit|
assert_equal((now + 1.send(unit)).class, Time, "Time + 1.#{unit} must be Time")
@@ -99,7 +172,7 @@ class DurationTest < ActiveSupport::TestCase
def test_argument_error
e = assert_raise ArgumentError do
- 1.second.ago('')
+ 1.second.ago("")
end
assert_equal 'expected a time or date, got ""', e.message, "ensure ArgumentError is not being raised by dependencies.rb"
end
@@ -149,54 +222,67 @@ class DurationTest < ActiveSupport::TestCase
def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set
Time.zone = nil
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
Time.stub(:now, Time.local(2000)) do
# since
assert_not_instance_of ActiveSupport::TimeWithZone, 5.seconds.since
- assert_equal Time.local(2000,1,1,0,0,5), 5.seconds.since
+ assert_equal Time.local(2000, 1, 1, 0, 0, 5), 5.seconds.since
# ago
assert_not_instance_of ActiveSupport::TimeWithZone, 5.seconds.ago
- assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago
+ assert_equal Time.local(1999, 12, 31, 23, 59, 55), 5.seconds.ago
end
end
end
def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
- Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
+ Time.zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "US/Eastern" do
Time.stub(:now, Time.local(2000)) do
# since
assert_instance_of ActiveSupport::TimeWithZone, 5.seconds.since
- assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
- assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
+ assert_equal Time.utc(2000, 1, 1, 0, 0, 5), 5.seconds.since.time
+ assert_equal "Eastern Time (US & Canada)", 5.seconds.since.time_zone.name
# ago
assert_instance_of ActiveSupport::TimeWithZone, 5.seconds.ago
- assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
- assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
+ assert_equal Time.utc(1999, 12, 31, 23, 59, 55), 5.seconds.ago.time
+ assert_equal "Eastern Time (US & Canada)", 5.seconds.ago.time_zone.name
end
end
ensure
Time.zone = nil
end
+ def test_before_and_afer
+ t = Time.local(2000)
+ assert_equal t + 1, 1.second.after(t)
+ assert_equal t - 1, 1.second.before(t)
+ end
+
+ def test_before_and_after_without_argument
+ Time.stub(:now, Time.local(2000)) do
+ assert_equal Time.now - 1.second, 1.second.before
+ assert_equal Time.now + 1.second, 1.second.after
+ end
+ end
+
def test_adding_hours_across_dst_boundary
- with_env_tz 'CET' do
- assert_equal Time.local(2009,3,29,0,0,0) + 24.hours, Time.local(2009,3,30,1,0,0)
+ with_env_tz "CET" do
+ assert_equal Time.local(2009, 3, 29, 0, 0, 0) + 24.hours, Time.local(2009, 3, 30, 1, 0, 0)
end
end
def test_adding_day_across_dst_boundary
- with_env_tz 'CET' do
- assert_equal Time.local(2009,3,29,0,0,0) + 1.day, Time.local(2009,3,30,0,0,0)
+ with_env_tz "CET" do
+ assert_equal Time.local(2009, 3, 29, 0, 0, 0) + 1.day, Time.local(2009, 3, 30, 0, 0, 0)
end
end
def test_delegation_with_block_works
counter = 0
assert_nothing_raised do
- 1.minute.times {counter += 1}
+ 1.minute.times { counter += 1 }
end
- assert_equal counter, 60
+ assert_equal 60, counter
end
def test_as_json
@@ -204,12 +290,16 @@ class DurationTest < ActiveSupport::TestCase
end
def test_to_json
- assert_equal '172800', 2.days.to_json
+ assert_equal "172800", 2.days.to_json
end
def test_case_when
- cased = case 1.day when 1.day then "ok" end
- assert_equal cased, "ok"
+ cased = \
+ case 1.day
+ when 1.day
+ "ok"
+ end
+ assert_equal "ok", cased
end
def test_respond_to
@@ -233,6 +323,191 @@ class DurationTest < ActiveSupport::TestCase
assert_equal(1, (61 <=> 1.minute))
end
+ def test_implicit_coercion
+ assert_equal 2.days, 2 * 1.day
+ assert_instance_of ActiveSupport::Duration, 2 * 1.day
+ assert_equal Time.utc(2017, 1, 3), Time.utc(2017, 1, 1) + 2 * 1.day
+ assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 2 * 1.day
+ end
+
+ def test_scalar_coerce
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+ assert_instance_of ActiveSupport::Duration::Scalar, 10 + scalar
+ assert_instance_of ActiveSupport::Duration, 10.seconds + scalar
+ end
+
+ def test_scalar_delegations
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+ assert_kind_of Float, scalar.to_f
+ assert_kind_of Integer, scalar.to_i
+ assert_kind_of String, scalar.to_s
+ end
+
+ def test_scalar_unary_minus
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal(-10, -scalar)
+ assert_instance_of ActiveSupport::Duration::Scalar, -scalar
+ end
+
+ def test_scalar_compare
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal(1, scalar <=> 5)
+ assert_equal(0, scalar <=> 10)
+ assert_equal(-1, scalar <=> 15)
+ assert_nil(scalar <=> "foo")
+ end
+
+ def test_scalar_plus
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal 20, 10 + scalar
+ assert_instance_of ActiveSupport::Duration::Scalar, 10 + scalar
+ assert_equal 20, scalar + 10
+ assert_instance_of ActiveSupport::Duration::Scalar, scalar + 10
+ assert_equal 20, 10.seconds + scalar
+ assert_instance_of ActiveSupport::Duration, 10.seconds + scalar
+ assert_equal 20, scalar + 10.seconds
+ assert_instance_of ActiveSupport::Duration, scalar + 10.seconds
+
+ exception = assert_raises(TypeError) do
+ scalar + "foo"
+ end
+
+ assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
+ end
+
+ def test_scalar_plus_parts
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal({ days: 1, seconds: 10 }, (scalar + 1.day).parts)
+ assert_equal({ days: -1, seconds: 10 }, (scalar + -1.day).parts)
+ end
+
+ def test_scalar_minus
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal 10, 20 - scalar
+ assert_instance_of ActiveSupport::Duration::Scalar, 20 - scalar
+ assert_equal 5, scalar - 5
+ assert_instance_of ActiveSupport::Duration::Scalar, scalar - 5
+ assert_equal 10, 20.seconds - scalar
+ assert_instance_of ActiveSupport::Duration, 20.seconds - scalar
+ assert_equal 5, scalar - 5.seconds
+ assert_instance_of ActiveSupport::Duration, scalar - 5.seconds
+
+ assert_equal({ days: -1, seconds: 10 }, (scalar - 1.day).parts)
+ assert_equal({ days: 1, seconds: 10 }, (scalar - -1.day).parts)
+
+ exception = assert_raises(TypeError) do
+ scalar - "foo"
+ end
+
+ assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
+ end
+
+ def test_scalar_minus_parts
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal({ days: -1, seconds: 10 }, (scalar - 1.day).parts)
+ assert_equal({ days: 1, seconds: 10 }, (scalar - -1.day).parts)
+ end
+
+ def test_scalar_multiply
+ scalar = ActiveSupport::Duration::Scalar.new(5)
+
+ assert_equal 10, 2 * scalar
+ assert_instance_of ActiveSupport::Duration::Scalar, 2 * scalar
+ assert_equal 10, scalar * 2
+ assert_instance_of ActiveSupport::Duration::Scalar, scalar * 2
+ assert_equal 10, 2.seconds * scalar
+ assert_instance_of ActiveSupport::Duration, 2.seconds * scalar
+ assert_equal 10, scalar * 2.seconds
+ assert_instance_of ActiveSupport::Duration, scalar * 2.seconds
+
+ exception = assert_raises(TypeError) do
+ scalar * "foo"
+ end
+
+ assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
+ end
+
+ def test_scalar_multiply_parts
+ scalar = ActiveSupport::Duration::Scalar.new(1)
+ assert_equal({ days: 2 }, (scalar * 2.days).parts)
+ assert_equal(172800, (scalar * 2.days).value)
+ assert_equal({ days: -2 }, (scalar * -2.days).parts)
+ assert_equal(-172800, (scalar * -2.days).value)
+ end
+
+ def test_scalar_divide
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal 10, 100 / scalar
+ assert_instance_of ActiveSupport::Duration::Scalar, 100 / scalar
+ assert_equal 5, scalar / 2
+ assert_instance_of ActiveSupport::Duration::Scalar, scalar / 2
+ assert_equal 10, 100.seconds / scalar
+ assert_instance_of ActiveSupport::Duration, 100.seconds / scalar
+ assert_equal 5, scalar / 2.seconds
+ assert_kind_of Integer, scalar / 2.seconds
+
+ exception = assert_raises(TypeError) do
+ scalar / "foo"
+ end
+
+ assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
+ end
+
+ def test_scalar_modulo
+ scalar = ActiveSupport::Duration::Scalar.new(10)
+
+ assert_equal 1, 31 % scalar
+ assert_instance_of ActiveSupport::Duration::Scalar, 31 % scalar
+ assert_equal 1, scalar % 3
+ assert_instance_of ActiveSupport::Duration::Scalar, scalar % 3
+ assert_equal 1, 31.seconds % scalar
+ assert_instance_of ActiveSupport::Duration, 31.seconds % scalar
+ assert_equal 1, scalar % 3.seconds
+ assert_instance_of ActiveSupport::Duration, scalar % 3.seconds
+
+ exception = assert_raises(TypeError) do
+ scalar % "foo"
+ end
+
+ assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
+ end
+
+ def test_scalar_modulo_parts
+ scalar = ActiveSupport::Duration::Scalar.new(82800)
+ assert_equal({ hours: 1 }, (scalar % 2.hours).parts)
+ assert_equal(3600, (scalar % 2.hours).value)
+ end
+
+ def test_twelve_months_equals_one_year
+ assert_equal 12.months, 1.year
+ end
+
+ def test_thirty_days_does_not_equal_one_month
+ assert_not_equal 30.days, 1.month
+ end
+
+ def test_adding_one_month_maintains_day_of_month
+ (1..11).each do |month|
+ [1, 14, 28].each do |day|
+ assert_equal Date.civil(2016, month + 1, day), Date.civil(2016, month, day) + 1.month
+ end
+ end
+
+ assert_equal Date.civil(2017, 1, 1), Date.civil(2016, 12, 1) + 1.month
+ assert_equal Date.civil(2017, 1, 14), Date.civil(2016, 12, 14) + 1.month
+ assert_equal Date.civil(2017, 1, 28), Date.civil(2016, 12, 28) + 1.month
+
+ assert_equal Date.civil(2015, 2, 28), Date.civil(2015, 1, 31) + 1.month
+ assert_equal Date.civil(2016, 2, 29), Date.civil(2016, 1, 31) + 1.month
+ end
+
# ISO8601 string examples are taken from ISO8601 gem at https://github.com/arnau/ISO8601/blob/b93d466840/spec/iso8601/duration_spec.rb
# published under the conditions of MIT license at https://github.com/arnau/ISO8601/blob/b93d466840/LICENSE
#
@@ -260,7 +535,7 @@ class DurationTest < ActiveSupport::TestCase
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
def test_iso8601_parsing_wrong_patterns_with_raise
- invalid_patterns = ['', 'P', 'PT', 'P1YT', 'T', 'PW', 'P1Y1W', '~P1Y', '.P1Y', 'P1.5Y0.5M', 'P1.5Y1M', 'P1.5MT10.5S']
+ invalid_patterns = ["", "P", "PT", "P1YT", "T", "PW", "P1Y1W", "~P1Y", ".P1Y", "P1.5Y0.5M", "P1.5Y1M", "P1.5MT10.5S"]
invalid_patterns.each do |pattern|
assert_raise ActiveSupport::Duration::ISO8601Parser::ParsingError, pattern.inspect do
ActiveSupport::Duration.parse(pattern)
@@ -270,15 +545,16 @@ class DurationTest < ActiveSupport::TestCase
def test_iso8601_output
expectations = [
- ['P1Y', 1.year ],
- ['P1W', 1.week ],
- ['P1Y1M', 1.year + 1.month ],
- ['P1Y1M1D', 1.year + 1.month + 1.day ],
- ['-P1Y1D', -1.year - 1.day ],
- ['P1Y-1DT-1S', 1.year - 1.day - 1.second ], # Parts with different signs are exists in PostgreSQL interval datatype.
- ['PT1S', 1.second ],
- ['PT1.4S', (1.4).seconds ],
- ['P1Y1M1DT1H', 1.year + 1.month + 1.day + 1.hour],
+ ["P1Y", 1.year ],
+ ["P1W", 1.week ],
+ ["P1Y1M", 1.year + 1.month ],
+ ["P1Y1M1D", 1.year + 1.month + 1.day ],
+ ["-P1Y1D", -1.year - 1.day ],
+ ["P1Y-1DT-1S", 1.year - 1.day - 1.second ], # Parts with different signs are exists in PostgreSQL interval datatype.
+ ["PT1S", 1.second ],
+ ["PT1.4S", (1.4).seconds ],
+ ["P1Y1M1DT1H", 1.year + 1.month + 1.day + 1.hour],
+ ["PT0S", 0.minutes ],
]
expectations.each do |expected_output, duration|
assert_equal expected_output, duration.iso8601, expected_output.inspect
@@ -287,17 +563,17 @@ class DurationTest < ActiveSupport::TestCase
def test_iso8601_output_precision
expectations = [
- [nil, 'P1Y1MT5.55S', 1.year + 1.month + (5.55).seconds ],
- [0, 'P1Y1MT6S', 1.year + 1.month + (5.55).seconds ],
- [1, 'P1Y1MT5.5S', 1.year + 1.month + (5.55).seconds ],
- [2, 'P1Y1MT5.55S', 1.year + 1.month + (5.55).seconds ],
- [3, 'P1Y1MT5.550S', 1.year + 1.month + (5.55).seconds ],
- [nil, 'PT1S', 1.second ],
- [2, 'PT1.00S', 1.second ],
- [nil, 'PT1.4S', (1.4).seconds ],
- [0, 'PT1S', (1.4).seconds ],
- [1, 'PT1.4S', (1.4).seconds ],
- [5, 'PT1.40000S', (1.4).seconds ],
+ [nil, "P1Y1MT8.55S", 1.year + 1.month + (8.55).seconds ],
+ [0, "P1Y1MT9S", 1.year + 1.month + (8.55).seconds ],
+ [1, "P1Y1MT8.6S", 1.year + 1.month + (8.55).seconds ],
+ [2, "P1Y1MT8.55S", 1.year + 1.month + (8.55).seconds ],
+ [3, "P1Y1MT8.550S", 1.year + 1.month + (8.55).seconds ],
+ [nil, "PT1S", 1.second ],
+ [2, "PT1.00S", 1.second ],
+ [nil, "PT1.4S", (1.4).seconds ],
+ [0, "PT1S", (1.4).seconds ],
+ [1, "PT1.4S", (1.4).seconds ],
+ [5, "PT1.40000S", (1.4).seconds ],
]
expectations.each do |precision, expected_output, duration|
assert_equal expected_output, duration.iso8601(precision: precision), expected_output.inspect
@@ -314,7 +590,64 @@ class DurationTest < ActiveSupport::TestCase
time = Time.current
patterns.each do |pattern|
duration = ActiveSupport::Duration.parse(pattern)
- assert_equal time+duration, time+ActiveSupport::Duration.parse(duration.iso8601), pattern.inspect
+ assert_equal time + duration, time + ActiveSupport::Duration.parse(duration.iso8601), pattern.inspect
+ end
+ end
+
+ def test_iso8601_parsing_across_spring_dst_boundary
+ with_env_tz eastern_time_zone do
+ with_tz_default "Eastern Time (US & Canada)" do
+ travel_to Time.utc(2016, 3, 11) do
+ assert_equal 604800, ActiveSupport::Duration.parse("P7D").to_i
+ assert_equal 604800, ActiveSupport::Duration.parse("P1W").to_i
+ end
+ end
end
end
+
+ def test_iso8601_parsing_across_autumn_dst_boundary
+ with_env_tz eastern_time_zone do
+ with_tz_default "Eastern Time (US & Canada)" do
+ travel_to Time.utc(2016, 11, 4) do
+ assert_equal 604800, ActiveSupport::Duration.parse("P7D").to_i
+ assert_equal 604800, ActiveSupport::Duration.parse("P1W").to_i
+ end
+ end
+ end
+ end
+
+ def test_iso8601_parsing_equivalence_with_numeric_extensions_over_long_periods
+ with_env_tz eastern_time_zone do
+ with_tz_default "Eastern Time (US & Canada)" do
+ assert_equal 3.months, ActiveSupport::Duration.parse("P3M")
+ assert_equal 3.months.to_i, ActiveSupport::Duration.parse("P3M").to_i
+ assert_equal 10.months, ActiveSupport::Duration.parse("P10M")
+ assert_equal 10.months.to_i, ActiveSupport::Duration.parse("P10M").to_i
+ assert_equal 3.years, ActiveSupport::Duration.parse("P3Y")
+ assert_equal 3.years.to_i, ActiveSupport::Duration.parse("P3Y").to_i
+ assert_equal 10.years, ActiveSupport::Duration.parse("P10Y")
+ assert_equal 10.years.to_i, ActiveSupport::Duration.parse("P10Y").to_i
+ end
+ end
+ end
+
+ def test_adding_durations_do_not_hold_prior_states
+ time = Time.parse("Nov 29, 2016")
+ # If the implementation adds and subtracts 3 months, the
+ # resulting date would have been in February so the day will
+ # change to the 29th.
+ d1 = 3.months - 3.months
+ d2 = 2.months - 2.months
+
+ assert_equal time + d1, time + d2
+ end
+
+ private
+ def eastern_time_zone
+ if Gem.win_platform?
+ "EST5EDT"
+ else
+ "America/New_York"
+ end
+ end
end
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index 99c3236c35..8d71320931 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/core_ext/array'
-require 'active_support/core_ext/enumerable'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/array"
+require "active_support/core_ext/enumerable"
Payment = Struct.new(:price)
ExpandedPayment = Struct.new(:dollars, :cents)
@@ -22,7 +24,7 @@ class EnumerableTests < ActiveSupport::TestCase
end
end
- def assert_typed_equal(e, v, cls, msg=nil)
+ def assert_typed_equal(e, v, cls, msg = nil)
assert_kind_of(cls, v, msg)
assert_equal(e, v, msg)
end
@@ -33,8 +35,8 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal 60, enum.sum { |i| i * 2 }
enum = GenericEnumerable.new(%w(a b c))
- assert_equal 'abc', enum.sum
- assert_equal 'aabbcc', enum.sum { |i| i * 2 }
+ assert_equal "abc", enum.sum
+ assert_equal "aabbcc", enum.sum { |i| i * 2 }
payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ])
assert_equal 30, payments.sum(&:price)
@@ -70,12 +72,12 @@ class EnumerableTests < ActiveSupport::TestCase
sum = GenericEnumerable.new([1.quo(2), 1.quo(3)]).sum
assert_typed_equal(5.quo(6), sum, Rational)
- sum = GenericEnumerable.new([2.0, 3.0*Complex::I]).sum
+ sum = GenericEnumerable.new([2.0, 3.0 * Complex::I]).sum
assert_typed_equal(Complex(2.0, 3.0), sum, Complex)
assert_typed_equal(2.0, sum.real, Float)
assert_typed_equal(3.0, sum.imag, Float)
- sum = GenericEnumerable.new([1, 2]).sum(10) {|v| v * 2 }
+ sum = GenericEnumerable.new([1, 2]).sum(10) { |v| v * 2 }
assert_typed_equal(16, sum, Integer)
end
@@ -102,7 +104,7 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal 10, (1..4).sum
assert_equal 10, (1..4.5).sum
assert_equal 6, (1...4).sum
- assert_equal 'abc', ('a'..'c').sum
+ assert_equal "abc", ("a".."c").sum
assert_equal 50_000_005_000_000, (0..10_000_000).sum
assert_equal 0, (10..0).sum
assert_equal 5, (10..0).sum(5)
@@ -120,8 +122,8 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal 60, enum.sum { |i| i * 2 }
enum = %w(a b c)
- assert_equal 'abc', enum.sum
- assert_equal 'aabbcc', enum.sum { |i| i * 2 }
+ assert_equal "abc", enum.sum
+ assert_equal "aabbcc", enum.sum { |i| i * 2 }
payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ]
assert_equal 30, payments.sum(&:price)
@@ -157,12 +159,12 @@ class EnumerableTests < ActiveSupport::TestCase
sum = [1.quo(2), 1.quo(3)].sum
assert_typed_equal(5.quo(6), sum, Rational)
- sum = [2.0, 3.0*Complex::I].sum
+ sum = [2.0, 3.0 * Complex::I].sum
assert_typed_equal(Complex(2.0, 3.0), sum, Complex)
assert_typed_equal(2.0, sum.real, Float)
assert_typed_equal(3.0, sum.imag, Float)
- sum = [1, 2].sum(10) {|v| v * 2 }
+ sum = [1, 2].sum(10) { |v| v * 2 }
assert_typed_equal(16, sum, Integer)
end
@@ -171,30 +173,28 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
payments.index_by(&:price))
assert_equal Enumerator, payments.index_by.class
- if Enumerator.method_defined? :size
- assert_equal nil, payments.index_by.size
- assert_equal 42, (1..42).index_by.size
- end
+ assert_nil payments.index_by.size
+ assert_equal 42, (1..42).index_by.size
assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
payments.index_by.each(&:price))
end
def test_many
- assert_equal false, GenericEnumerable.new([] ).many?
- assert_equal false, GenericEnumerable.new([ 1 ] ).many?
- assert_equal true, GenericEnumerable.new([ 1, 2 ] ).many?
-
- assert_equal false, GenericEnumerable.new([] ).many? {|x| x > 1 }
- assert_equal false, GenericEnumerable.new([ 2 ] ).many? {|x| x > 1 }
- assert_equal false, GenericEnumerable.new([ 1, 2 ] ).many? {|x| x > 1 }
- assert_equal true, GenericEnumerable.new([ 1, 2, 2 ]).many? {|x| x > 1 }
+ assert_equal false, GenericEnumerable.new([]).many?
+ assert_equal false, GenericEnumerable.new([ 1 ]).many?
+ assert_equal true, GenericEnumerable.new([ 1, 2 ]).many?
+
+ assert_equal false, GenericEnumerable.new([]).many? { |x| x > 1 }
+ assert_equal false, GenericEnumerable.new([ 2 ]).many? { |x| x > 1 }
+ assert_equal false, GenericEnumerable.new([ 1, 2 ]).many? { |x| x > 1 }
+ assert_equal true, GenericEnumerable.new([ 1, 2, 2 ]).many? { |x| x > 1 }
end
def test_many_iterates_only_on_what_is_needed
- infinity = 1.0/0.0
+ infinity = 1.0 / 0.0
very_long_enum = 0..infinity
assert_equal true, very_long_enum.many?
- assert_equal true, very_long_enum.many?{|x| x > 100}
+ assert_equal true, very_long_enum.many? { |x| x > 100 }
end
def test_exclude?
@@ -206,7 +206,7 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal [1, 2, 4], GenericEnumerable.new((1..5).to_a).without(3, 5)
assert_equal [1, 2, 4], (1..5).to_a.without(3, 5)
assert_equal [1, 2, 4], (1..5).to_set.without(3, 5)
- assert_equal({foo: 1, baz: 3}, {foo: 1, bar: 2, baz: 3}.without(:bar))
+ assert_equal({ foo: 1, baz: 3 }, { foo: 1, bar: 2, baz: 3 }.without(:bar))
end
def test_pluck
diff --git a/activesupport/test/core_ext/file_test.rb b/activesupport/test/core_ext/file_test.rb
index cde0132b97..23e3c277cc 100644
--- a/activesupport/test/core_ext/file_test.rb
+++ b/activesupport/test/core_ext/file_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/file'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/file"
class AtomicWriteTest < ActiveSupport::TestCase
def test_atomic_write_without_errors
diff --git a/activesupport/test/core_ext/hash/transform_keys_test.rb b/activesupport/test/core_ext/hash/transform_keys_test.rb
index 962d3a30b6..b9e41f7b25 100644
--- a/activesupport/test/core_ext/hash/transform_keys_test.rb
+++ b/activesupport/test/core_ext/hash/transform_keys_test.rb
@@ -1,62 +1,64 @@
-require 'abstract_unit'
-require 'active_support/core_ext/hash/keys'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/hash/keys"
class TransformKeysTest < ActiveSupport::TestCase
test "transform_keys returns a new hash with the keys computed from the block" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
mapped = original.transform_keys { |k| "#{k}!".to_sym }
- assert_equal({ a: 'a', b: 'b' }, original)
- assert_equal({ a!: 'a', b!: 'b' }, mapped)
+ assert_equal({ a: "a", b: "b" }, original)
+ assert_equal({ a!: "a", b!: "b" }, mapped)
end
test "transform_keys! modifies the keys of the original" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
mapped = original.transform_keys! { |k| "#{k}!".to_sym }
- assert_equal({ a!: 'a', b!: 'b' }, original)
+ assert_equal({ a!: "a", b!: "b" }, original)
assert_same original, mapped
end
test "transform_keys returns a sized Enumerator if no block is given" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
enumerator = original.transform_keys
assert_equal original.size, enumerator.size
assert_equal Enumerator, enumerator.class
end
test "transform_keys! returns a sized Enumerator if no block is given" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
enumerator = original.transform_keys!
assert_equal original.size, enumerator.size
assert_equal Enumerator, enumerator.class
end
test "transform_keys is chainable with Enumerable methods" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
mapped = original.transform_keys.with_index { |k, i| [k, i].join.to_sym }
- assert_equal({ a0: 'a', b1: 'b' }, mapped)
+ assert_equal({ a0: "a", b1: "b" }, mapped)
end
test "transform_keys! is chainable with Enumerable methods" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
original.transform_keys!.with_index { |k, i| [k, i].join.to_sym }
- assert_equal({ a0: 'a', b1: 'b' }, original)
+ assert_equal({ a0: "a", b1: "b" }, original)
end
test "transform_keys returns a Hash instance when self is inherited from Hash" do
class HashDescendant < ::Hash
def initialize(elements = nil)
super(elements)
- (elements || {}).each_pair{ |key, value| self[key] = value }
+ (elements || {}).each_pair { |key, value| self[key] = value }
end
end
- original = HashDescendant.new({ a: 'a', b: 'b' })
+ original = HashDescendant.new(a: "a", b: "b")
mapped = original.transform_keys { |k| "#{k}!".to_sym }
- assert_equal({ a: 'a', b: 'b' }, original)
- assert_equal({ a!: 'a', b!: 'b' }, mapped)
+ assert_equal({ a: "a", b: "b" }, original)
+ assert_equal({ a!: "a", b!: "b" }, mapped)
assert_equal(::Hash, mapped.class)
end
end
diff --git a/activesupport/test/core_ext/hash/transform_values_test.rb b/activesupport/test/core_ext/hash/transform_values_test.rb
index 114022fbaf..d34b7fa7b9 100644
--- a/activesupport/test/core_ext/hash/transform_values_test.rb
+++ b/activesupport/test/core_ext/hash/transform_values_test.rb
@@ -1,75 +1,77 @@
-require 'abstract_unit'
-require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/core_ext/hash/transform_values'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/hash/indifferent_access"
+require "active_support/core_ext/hash/transform_values"
class TransformValuesTest < ActiveSupport::TestCase
test "transform_values returns a new hash with the values computed from the block" do
- original = { a: 'a', b: 'b' }
- mapped = original.transform_values { |v| v + '!' }
+ original = { a: "a", b: "b" }
+ mapped = original.transform_values { |v| v + "!" }
- assert_equal({ a: 'a', b: 'b' }, original)
- assert_equal({ a: 'a!', b: 'b!' }, mapped)
+ assert_equal({ a: "a", b: "b" }, original)
+ assert_equal({ a: "a!", b: "b!" }, mapped)
end
test "transform_values! modifies the values of the original" do
- original = { a: 'a', b: 'b' }
- mapped = original.transform_values! { |v| v + '!' }
+ original = { a: "a", b: "b" }
+ mapped = original.transform_values! { |v| v + "!" }
- assert_equal({ a: 'a!', b: 'b!' }, original)
+ assert_equal({ a: "a!", b: "b!" }, original)
assert_same original, mapped
end
test "indifferent access is still indifferent after mapping values" do
- original = { a: 'a', b: 'b' }.with_indifferent_access
- mapped = original.transform_values { |v| v + '!' }
+ original = { a: "a", b: "b" }.with_indifferent_access
+ mapped = original.transform_values { |v| v + "!" }
- assert_equal 'a!', mapped[:a]
- assert_equal 'a!', mapped['a']
+ assert_equal "a!", mapped[:a]
+ assert_equal "a!", mapped["a"]
end
# This is to be consistent with the behavior of Ruby's built in methods
# (e.g. #select, #reject) as of 2.2
test "default values do not persist during mapping" do
- original = Hash.new('foo')
- original[:a] = 'a'
- mapped = original.transform_values { |v| v + '!' }
+ original = Hash.new("foo")
+ original[:a] = "a"
+ mapped = original.transform_values { |v| v + "!" }
- assert_equal 'a!', mapped[:a]
+ assert_equal "a!", mapped[:a]
assert_nil mapped[:b]
end
test "default procs do not persist after mapping" do
- original = Hash.new { 'foo' }
- original[:a] = 'a'
- mapped = original.transform_values { |v| v + '!' }
+ original = Hash.new { "foo" }
+ original[:a] = "a"
+ mapped = original.transform_values { |v| v + "!" }
- assert_equal 'a!', mapped[:a]
+ assert_equal "a!", mapped[:a]
assert_nil mapped[:b]
end
test "transform_values returns a sized Enumerator if no block is given" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
enumerator = original.transform_values
assert_equal original.size, enumerator.size
assert_equal Enumerator, enumerator.class
end
test "transform_values! returns a sized Enumerator if no block is given" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
enumerator = original.transform_values!
assert_equal original.size, enumerator.size
assert_equal Enumerator, enumerator.class
end
test "transform_values is chainable with Enumerable methods" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
mapped = original.transform_values.with_index { |v, i| [v, i].join }
- assert_equal({ a: 'a0', b: 'b1' }, mapped)
+ assert_equal({ a: "a0", b: "b1" }, mapped)
end
test "transform_values! is chainable with Enumerable methods" do
- original = { a: 'a', b: 'b' }
+ original = { a: "a", b: "b" }
original.transform_values!.with_index { |v, i| [v, i].join }
- assert_equal({ a: 'a0', b: 'b1' }, original)
+ assert_equal({ a: "a0", b: "b1" }, original)
end
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index be8583e704..17952e9fc7 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -1,55 +1,32 @@
-require 'abstract_unit'
-require 'active_support/core_ext/hash'
-require 'bigdecimal'
-require 'active_support/core_ext/string/access'
-require 'active_support/ordered_hash'
-require 'active_support/core_ext/object/conversions'
-require 'active_support/core_ext/object/deep_dup'
-require 'active_support/inflections'
+# frozen_string_literal: true
-class HashExtTest < ActiveSupport::TestCase
- class IndifferentHash < ActiveSupport::HashWithIndifferentAccess
- end
-
- class SubclassingArray < Array
- end
-
- class SubclassingHash < Hash
- end
-
- class NonIndifferentHash < Hash
- def nested_under_indifferent_access
- self
- end
- end
-
- class HashByConversion
- def initialize(hash)
- @hash = hash
- end
-
- def to_hash
- @hash
- end
- end
+require "abstract_unit"
+require "active_support/core_ext/hash"
+require "bigdecimal"
+require "active_support/core_ext/string/access"
+require "active_support/ordered_hash"
+require "active_support/core_ext/object/conversions"
+require "active_support/core_ext/object/deep_dup"
+require "active_support/inflections"
+class HashExtTest < ActiveSupport::TestCase
def setup
- @strings = { 'a' => 1, 'b' => 2 }
- @nested_strings = { 'a' => { 'b' => { 'c' => 3 } } }
- @symbols = { :a => 1, :b => 2 }
- @nested_symbols = { :a => { :b => { :c => 3 } } }
- @mixed = { :a => 1, 'b' => 2 }
- @nested_mixed = { 'a' => { :b => { 'c' => 3 } } }
- @fixnums = { 0 => 1, 1 => 2 }
- @nested_fixnums = { 0 => { 1 => { 2 => 3} } }
+ @strings = { "a" => 1, "b" => 2 }
+ @nested_strings = { "a" => { "b" => { "c" => 3 } } }
+ @symbols = { a: 1, b: 2 }
+ @nested_symbols = { a: { b: { c: 3 } } }
+ @mixed = { :a => 1, "b" => 2 }
+ @nested_mixed = { "a" => { b: { "c" => 3 } } }
+ @integers = { 0 => 1, 1 => 2 }
+ @nested_integers = { 0 => { 1 => { 2 => 3 } } }
@illegal_symbols = { [] => 3 }
- @nested_illegal_symbols = { [] => { [] => 3} }
- @upcase_strings = { 'A' => 1, 'B' => 2 }
- @nested_upcase_strings = { 'A' => { 'B' => { 'C' => 3 } } }
- @string_array_of_hashes = { 'a' => [ { 'b' => 2 }, { 'c' => 3 }, 4 ] }
- @symbol_array_of_hashes = { :a => [ { :b => 2 }, { :c => 3 }, 4 ] }
- @mixed_array_of_hashes = { :a => [ { :b => 2 }, { 'c' => 3 }, 4 ] }
- @upcase_array_of_hashes = { 'A' => [ { 'B' => 2 }, { 'C' => 3 }, 4 ] }
+ @nested_illegal_symbols = { [] => { [] => 3 } }
+ @upcase_strings = { "A" => 1, "B" => 2 }
+ @nested_upcase_strings = { "A" => { "B" => { "C" => 3 } } }
+ @string_array_of_hashes = { "a" => [ { "b" => 2 }, { "c" => 3 }, 4 ] }
+ @symbol_array_of_hashes = { a: [ { b: 2 }, { c: 3 }, 4 ] }
+ @mixed_array_of_hashes = { a: [ { b: 2 }, { "c" => 3 }, 4 ] }
+ @upcase_array_of_hashes = { "A" => [ { "B" => 2 }, { "C" => 3 }, 4 ] }
end
def test_methods
@@ -75,59 +52,59 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_transform_keys
- assert_equal @upcase_strings, @strings.transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @symbols.transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @mixed.transform_keys{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @strings.transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @symbols.transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @mixed.transform_keys { |key| key.to_s.upcase }
end
def test_transform_keys_not_mutates
transformed_hash = @mixed.dup
- transformed_hash.transform_keys{ |key| key.to_s.upcase }
+ transformed_hash.transform_keys { |key| key.to_s.upcase }
assert_equal @mixed, transformed_hash
end
def test_deep_transform_keys
- assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_transform_keys { |key| key.to_s.upcase }
end
def test_deep_transform_keys_not_mutates
transformed_hash = @nested_mixed.deep_dup
- transformed_hash.deep_transform_keys{ |key| key.to_s.upcase }
+ transformed_hash.deep_transform_keys { |key| key.to_s.upcase }
assert_equal @nested_mixed, transformed_hash
end
def test_transform_keys!
- assert_equal @upcase_strings, @symbols.dup.transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @strings.dup.transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @mixed.dup.transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @symbols.dup.transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @strings.dup.transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @mixed.dup.transform_keys! { |key| key.to_s.upcase }
end
def test_transform_keys_with_bang_mutates
transformed_hash = @mixed.dup
- transformed_hash.transform_keys!{ |key| key.to_s.upcase }
+ transformed_hash.transform_keys! { |key| key.to_s.upcase }
assert_equal @upcase_strings, transformed_hash
- assert_equal @mixed, { :a => 1, "b" => 2 }
+ assert_equal({ :a => 1, "b" => 2 }, @mixed)
end
def test_deep_transform_keys!
- assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
end
def test_deep_transform_keys_with_bang_mutates
transformed_hash = @nested_mixed.deep_dup
- transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase }
+ transformed_hash.deep_transform_keys! { |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, transformed_hash
- assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } }
+ assert_equal({ "a" => { b: { "c" => 3 } } }, @nested_mixed)
end
def test_symbolize_keys
@@ -167,7 +144,7 @@ class HashExtTest < ActiveSupport::TestCase
transformed_hash = @mixed.dup
transformed_hash.deep_symbolize_keys!
assert_equal @symbols, transformed_hash
- assert_equal @mixed, { :a => 1, "b" => 2 }
+ assert_equal({ :a => 1, "b" => 2 }, @mixed)
end
def test_deep_symbolize_keys!
@@ -183,7 +160,7 @@ class HashExtTest < ActiveSupport::TestCase
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_symbolize_keys!
assert_equal @nested_symbols, transformed_hash
- assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } }
+ assert_equal({ "a" => { b: { "c" => 3 } } }, @nested_mixed)
end
def test_symbolize_keys_preserves_keys_that_cant_be_symbolized
@@ -196,14 +173,14 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_dup.deep_symbolize_keys!
end
- def test_symbolize_keys_preserves_fixnum_keys
- assert_equal @fixnums, @fixnums.symbolize_keys
- assert_equal @fixnums, @fixnums.dup.symbolize_keys!
+ def test_symbolize_keys_preserves_integer_keys
+ assert_equal @integers, @integers.symbolize_keys
+ assert_equal @integers, @integers.dup.symbolize_keys!
end
- def test_deep_symbolize_keys_preserves_fixnum_keys
- assert_equal @nested_fixnums, @nested_fixnums.deep_symbolize_keys
- assert_equal @nested_fixnums, @nested_fixnums.deep_dup.deep_symbolize_keys!
+ def test_deep_symbolize_keys_preserves_integer_keys
+ assert_equal @nested_integers, @nested_integers.deep_symbolize_keys
+ assert_equal @nested_integers, @nested_integers.deep_dup.deep_symbolize_keys!
end
def test_stringify_keys
@@ -243,7 +220,7 @@ class HashExtTest < ActiveSupport::TestCase
transformed_hash = @mixed.dup
transformed_hash.stringify_keys!
assert_equal @strings, transformed_hash
- assert_equal @mixed, { :a => 1, "b" => 2 }
+ assert_equal({ :a => 1, "b" => 2 }, @mixed)
end
def test_deep_stringify_keys!
@@ -259,497 +236,45 @@ class HashExtTest < ActiveSupport::TestCase
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_stringify_keys!
assert_equal @nested_strings, transformed_hash
- assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } }
- end
-
- def test_symbolize_keys_for_hash_with_indifferent_access
- assert_instance_of Hash, @symbols.with_indifferent_access.symbolize_keys
- assert_equal @symbols, @symbols.with_indifferent_access.symbolize_keys
- assert_equal @symbols, @strings.with_indifferent_access.symbolize_keys
- assert_equal @symbols, @mixed.with_indifferent_access.symbolize_keys
- end
-
- def test_deep_symbolize_keys_for_hash_with_indifferent_access
- assert_instance_of Hash, @nested_symbols.with_indifferent_access.deep_symbolize_keys
- assert_equal @nested_symbols, @nested_symbols.with_indifferent_access.deep_symbolize_keys
- assert_equal @nested_symbols, @nested_strings.with_indifferent_access.deep_symbolize_keys
- assert_equal @nested_symbols, @nested_mixed.with_indifferent_access.deep_symbolize_keys
- end
-
-
- def test_symbolize_keys_bang_for_hash_with_indifferent_access
- assert_raise(NoMethodError) { @symbols.with_indifferent_access.dup.symbolize_keys! }
- assert_raise(NoMethodError) { @strings.with_indifferent_access.dup.symbolize_keys! }
- assert_raise(NoMethodError) { @mixed.with_indifferent_access.dup.symbolize_keys! }
- end
-
- def test_deep_symbolize_keys_bang_for_hash_with_indifferent_access
- assert_raise(NoMethodError) { @nested_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
- assert_raise(NoMethodError) { @nested_strings.with_indifferent_access.deep_dup.deep_symbolize_keys! }
- assert_raise(NoMethodError) { @nested_mixed.with_indifferent_access.deep_dup.deep_symbolize_keys! }
- end
-
- def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
- assert_equal @illegal_symbols, @illegal_symbols.with_indifferent_access.symbolize_keys
- assert_raise(NoMethodError) { @illegal_symbols.with_indifferent_access.dup.symbolize_keys! }
- end
-
- def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
- assert_equal @nested_illegal_symbols, @nested_illegal_symbols.with_indifferent_access.deep_symbolize_keys
- assert_raise(NoMethodError) { @nested_illegal_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
- end
-
- def test_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access
- assert_equal @fixnums, @fixnums.with_indifferent_access.symbolize_keys
- assert_raise(NoMethodError) { @fixnums.with_indifferent_access.dup.symbolize_keys! }
- end
-
- def test_deep_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access
- assert_equal @nested_fixnums, @nested_fixnums.with_indifferent_access.deep_symbolize_keys
- assert_raise(NoMethodError) { @nested_fixnums.with_indifferent_access.deep_dup.deep_symbolize_keys! }
- end
-
- def test_stringify_keys_for_hash_with_indifferent_access
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.stringify_keys
- assert_equal @strings, @symbols.with_indifferent_access.stringify_keys
- assert_equal @strings, @strings.with_indifferent_access.stringify_keys
- assert_equal @strings, @mixed.with_indifferent_access.stringify_keys
- end
-
- def test_deep_stringify_keys_for_hash_with_indifferent_access
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.deep_stringify_keys
- assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_stringify_keys
- assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_stringify_keys
- assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_stringify_keys
- end
-
- def test_stringify_keys_bang_for_hash_with_indifferent_access
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.dup.stringify_keys!
- assert_equal @strings, @symbols.with_indifferent_access.dup.stringify_keys!
- assert_equal @strings, @strings.with_indifferent_access.dup.stringify_keys!
- assert_equal @strings, @mixed.with_indifferent_access.dup.stringify_keys!
- end
-
- def test_deep_stringify_keys_bang_for_hash_with_indifferent_access
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.dup.deep_stringify_keys!
- assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_dup.deep_stringify_keys!
- assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_dup.deep_stringify_keys!
- assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_dup.deep_stringify_keys!
- end
-
- def test_nested_under_indifferent_access
- foo = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
- assert_kind_of ActiveSupport::HashWithIndifferentAccess, foo["foo"]
-
- foo = { "foo" => NonIndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
- assert_kind_of NonIndifferentHash, foo["foo"]
-
- foo = { "foo" => IndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
- assert_kind_of IndifferentHash, foo["foo"]
- end
-
- def test_indifferent_assorted
- @strings = @strings.with_indifferent_access
- @symbols = @symbols.with_indifferent_access
- @mixed = @mixed.with_indifferent_access
-
- assert_equal 'a', @strings.__send__(:convert_key, :a)
-
- assert_equal 1, @strings.fetch('a')
- assert_equal 1, @strings.fetch(:a.to_s)
- assert_equal 1, @strings.fetch(:a)
-
- hashes = { :@strings => @strings, :@symbols => @symbols, :@mixed => @mixed }
- method_map = { :'[]' => 1, :fetch => 1, :values_at => [1],
- :has_key? => true, :include? => true, :key? => true,
- :member? => true }
-
- hashes.each do |name, hash|
- method_map.sort_by(&:to_s).each do |meth, expected|
- assert_equal(expected, hash.__send__(meth, 'a'),
- "Calling #{name}.#{meth} 'a'")
- assert_equal(expected, hash.__send__(meth, :a),
- "Calling #{name}.#{meth} :a")
- end
- end
-
- assert_equal [1, 2], @strings.values_at('a', 'b')
- assert_equal [1, 2], @strings.values_at(:a, :b)
- assert_equal [1, 2], @symbols.values_at('a', 'b')
- assert_equal [1, 2], @symbols.values_at(:a, :b)
- assert_equal [1, 2], @mixed.values_at('a', 'b')
- assert_equal [1, 2], @mixed.values_at(:a, :b)
- end
-
- def test_indifferent_reading
- hash = HashWithIndifferentAccess.new
- hash["a"] = 1
- hash["b"] = true
- hash["c"] = false
- hash["d"] = nil
-
- assert_equal 1, hash[:a]
- assert_equal true, hash[:b]
- assert_equal false, hash[:c]
- assert_equal nil, hash[:d]
- assert_equal nil, hash[:e]
- end
-
- def test_indifferent_reading_with_nonnil_default
- hash = HashWithIndifferentAccess.new(1)
- hash["a"] = 1
- hash["b"] = true
- hash["c"] = false
- hash["d"] = nil
-
- assert_equal 1, hash[:a]
- assert_equal true, hash[:b]
- assert_equal false, hash[:c]
- assert_equal nil, hash[:d]
- assert_equal 1, hash[:e]
- end
-
- def test_indifferent_writing
- hash = HashWithIndifferentAccess.new
- hash[:a] = 1
- hash['b'] = 2
- hash[3] = 3
-
- assert_equal hash['a'], 1
- assert_equal hash['b'], 2
- assert_equal hash[:a], 1
- assert_equal hash[:b], 2
- assert_equal hash[3], 3
- end
-
- def test_indifferent_update
- hash = HashWithIndifferentAccess.new
- hash[:a] = 'a'
- hash['b'] = 'b'
-
- updated_with_strings = hash.update(@strings)
- updated_with_symbols = hash.update(@symbols)
- updated_with_mixed = hash.update(@mixed)
-
- assert_equal updated_with_strings[:a], 1
- assert_equal updated_with_strings['a'], 1
- assert_equal updated_with_strings['b'], 2
-
- assert_equal updated_with_symbols[:a], 1
- assert_equal updated_with_symbols['b'], 2
- assert_equal updated_with_symbols[:b], 2
-
- assert_equal updated_with_mixed[:a], 1
- assert_equal updated_with_mixed['b'], 2
-
- assert [updated_with_strings, updated_with_symbols, updated_with_mixed].all? { |h| h.keys.size == 2 }
- end
-
- def test_update_with_to_hash_conversion
- hash = HashWithIndifferentAccess.new
- hash.update HashByConversion.new({ :a => 1 })
- assert_equal hash['a'], 1
- end
-
- def test_indifferent_merging
- hash = HashWithIndifferentAccess.new
- hash[:a] = 'failure'
- hash['b'] = 'failure'
-
- other = { 'a' => 1, :b => 2 }
-
- merged = hash.merge(other)
-
- assert_equal HashWithIndifferentAccess, merged.class
- assert_equal 1, merged[:a]
- assert_equal 2, merged['b']
-
- hash.update(other)
-
- assert_equal 1, hash[:a]
- assert_equal 2, hash['b']
- end
-
- def test_merge_with_to_hash_conversion
- hash = HashWithIndifferentAccess.new
- merged = hash.merge HashByConversion.new({ :a => 1 })
- assert_equal merged['a'], 1
- end
-
- def test_indifferent_replace
- hash = HashWithIndifferentAccess.new
- hash[:a] = 42
-
- replaced = hash.replace(b: 12)
-
- assert hash.key?('b')
- assert !hash.key?(:a)
- assert_equal 12, hash[:b]
- assert_same hash, replaced
- end
-
- def test_replace_with_to_hash_conversion
- hash = HashWithIndifferentAccess.new
- hash[:a] = 42
-
- replaced = hash.replace(HashByConversion.new(b: 12))
-
- assert hash.key?('b')
- assert !hash.key?(:a)
- assert_equal 12, hash[:b]
- assert_same hash, replaced
- end
-
- def test_indifferent_merging_with_block
- hash = HashWithIndifferentAccess.new
- hash[:a] = 1
- hash['b'] = 3
-
- other = { 'a' => 4, :b => 2, 'c' => 10 }
-
- merged = hash.merge(other) { |key, old, new| old > new ? old : new }
-
- assert_equal HashWithIndifferentAccess, merged.class
- assert_equal 4, merged[:a]
- assert_equal 3, merged['b']
- assert_equal 10, merged[:c]
-
- other_indifferent = HashWithIndifferentAccess.new('a' => 9, :b => 2)
-
- merged = hash.merge(other_indifferent) { |key, old, new| old + new }
-
- assert_equal HashWithIndifferentAccess, merged.class
- assert_equal 10, merged[:a]
- assert_equal 5, merged[:b]
- end
-
- def test_indifferent_reverse_merging
- hash = HashWithIndifferentAccess.new key: :old_value
- hash.reverse_merge! key: :new_value
- assert_equal :old_value, hash[:key]
-
- hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value')
- hash.reverse_merge!(:some => 'noclobber', :another => 'clobber')
- assert_equal 'value', hash[:some]
- assert_equal 'clobber', hash[:another]
- end
-
- def test_indifferent_deleting
- get_hash = proc{ { :a => 'foo' }.with_indifferent_access }
- hash = get_hash.call
- assert_equal hash.delete(:a), 'foo'
- assert_equal hash.delete(:a), nil
- hash = get_hash.call
- assert_equal hash.delete('a'), 'foo'
- assert_equal hash.delete('a'), nil
- end
-
- def test_indifferent_select
- hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| v == 1}
-
- assert_equal({ 'a' => 1 }, hash)
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
- end
-
- def test_indifferent_select_returns_enumerator
- enum = ActiveSupport::HashWithIndifferentAccess.new(@strings).select
- assert_instance_of Enumerator, enum
- end
-
- def test_indifferent_select_returns_a_hash_when_unchanged
- hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| true}
-
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
- end
-
- def test_indifferent_select_bang
- indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
- indifferent_strings.select! {|k,v| v == 1}
-
- assert_equal({ 'a' => 1 }, indifferent_strings)
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
- end
-
- def test_indifferent_reject
- hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject {|k,v| v != 1}
-
- assert_equal({ 'a' => 1 }, hash)
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
- end
-
- def test_indifferent_reject_returns_enumerator
- enum = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject
- assert_instance_of Enumerator, enum
- end
-
- def test_indifferent_reject_bang
- indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
- indifferent_strings.reject! {|k,v| v != 1}
-
- assert_equal({ 'a' => 1 }, indifferent_strings)
- assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
- end
-
- def test_indifferent_to_hash
- # Should convert to a Hash with String keys.
- assert_equal @strings, @mixed.with_indifferent_access.to_hash
-
- # Should preserve the default value.
- mixed_with_default = @mixed.dup
- mixed_with_default.default = '1234'
- roundtrip = mixed_with_default.with_indifferent_access.to_hash
- assert_equal @strings, roundtrip
- assert_equal '1234', roundtrip.default
-
- # Ensure nested hashes are not HashWithIndiffereneAccess
- new_to_hash = @nested_mixed.with_indifferent_access.to_hash
- assert_not new_to_hash.instance_of?(HashWithIndifferentAccess)
- assert_not new_to_hash["a"].instance_of?(HashWithIndifferentAccess)
- assert_not new_to_hash["a"]["b"].instance_of?(HashWithIndifferentAccess)
- end
-
- def test_lookup_returns_the_same_object_that_is_stored_in_hash_indifferent_access
- hash = HashWithIndifferentAccess.new {|h, k| h[k] = []}
- hash[:a] << 1
-
- assert_equal [1], hash[:a]
- end
-
- def test_with_indifferent_access_has_no_side_effects_on_existing_hash
- hash = {content: [{:foo => :bar, 'bar' => 'baz'}]}
- hash.with_indifferent_access
-
- assert_equal [:foo, "bar"], hash[:content].first.keys
- end
-
- def test_indifferent_hash_with_array_of_hashes
- hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
- assert_equal "1", hash[:urls][:url].first[:address]
-
- hash = hash.to_hash
- assert_not hash.instance_of?(HashWithIndifferentAccess)
- assert_not hash["urls"].instance_of?(HashWithIndifferentAccess)
- assert_not hash["urls"]["url"].first.instance_of?(HashWithIndifferentAccess)
- end
-
- def test_should_preserve_array_subclass_when_value_is_array
- array = SubclassingArray.new
- array << { "address" => "1" }
- hash = { "urls" => { "url" => array }}.with_indifferent_access
- assert_equal SubclassingArray, hash[:urls][:url].class
- end
-
- def test_should_preserve_array_class_when_hash_value_is_frozen_array
- array = SubclassingArray.new
- array << { "address" => "1" }
- hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
- assert_equal SubclassingArray, hash[:urls][:url].class
- end
-
- def test_stringify_and_symbolize_keys_on_indifferent_preserves_hash
- h = HashWithIndifferentAccess.new
- h[:first] = 1
- h = h.stringify_keys
- assert_equal 1, h['first']
- h = HashWithIndifferentAccess.new
- h['first'] = 1
- h = h.symbolize_keys
- assert_equal 1, h[:first]
- end
-
- def test_deep_stringify_and_deep_symbolize_keys_on_indifferent_preserves_hash
- h = HashWithIndifferentAccess.new
- h[:first] = 1
- h = h.deep_stringify_keys
- assert_equal 1, h['first']
- h = HashWithIndifferentAccess.new
- h['first'] = 1
- h = h.deep_symbolize_keys
- assert_equal 1, h[:first]
- end
-
- def test_to_options_on_indifferent_preserves_hash
- h = HashWithIndifferentAccess.new
- h['first'] = 1
- h.to_options!
- assert_equal 1, h['first']
- end
-
- def test_to_options_on_indifferent_preserves_works_as_hash_with_dup
- h = HashWithIndifferentAccess.new({ a: { b: 'b' } })
- dup = h.dup
-
- dup[:a][:c] = 'c'
- assert_equal 'c', h[:a][:c]
- end
-
- def test_indifferent_sub_hashes
- h = {'user' => {'id' => 5}}.with_indifferent_access
- ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
-
- h = {:user => {:id => 5}}.with_indifferent_access
- ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
- end
-
- def test_indifferent_duplication
- # Should preserve default value
- h = HashWithIndifferentAccess.new
- h.default = '1234'
- assert_equal h.default, h.dup.default
-
- # Should preserve class for subclasses
- h = IndifferentHash.new
- assert_equal h.class, h.dup.class
- end
-
- def test_nested_dig_indifferent_access
- skip if RUBY_VERSION < "2.3.0"
- data = {"this" => {"views" => 1234}}.with_indifferent_access
- assert_equal 1234, data.dig(:this, :views)
+ assert_equal({ "a" => { b: { "c" => 3 } } }, @nested_mixed)
end
def test_assert_valid_keys
assert_nothing_raised do
- { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
- { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
+ { failure: "stuff", funny: "business" }.assert_valid_keys([ :failure, :funny ])
+ { failure: "stuff", funny: "business" }.assert_valid_keys(:failure, :funny)
end
# not all valid keys are required to be present
assert_nothing_raised do
- { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny, :sunny ])
- { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny, :sunny)
+ { failure: "stuff", funny: "business" }.assert_valid_keys([ :failure, :funny, :sunny ])
+ { failure: "stuff", funny: "business" }.assert_valid_keys(:failure, :funny, :sunny)
end
exception = assert_raise ArgumentError do
- { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
+ { failore: "stuff", funny: "business" }.assert_valid_keys([ :failure, :funny ])
end
assert_equal "Unknown key: :failore. Valid keys are: :failure, :funny", exception.message
exception = assert_raise ArgumentError do
- { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
+ { failore: "stuff", funny: "business" }.assert_valid_keys(:failure, :funny)
end
assert_equal "Unknown key: :failore. Valid keys are: :failure, :funny", exception.message
exception = assert_raise ArgumentError do
- { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure ])
+ { failore: "stuff", funny: "business" }.assert_valid_keys([ :failure ])
end
assert_equal "Unknown key: :failore. Valid keys are: :failure", exception.message
exception = assert_raise ArgumentError do
- { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure)
+ { failore: "stuff", funny: "business" }.assert_valid_keys(:failure)
end
assert_equal "Unknown key: :failore. Valid keys are: :failure", exception.message
end
- def test_assorted_keys_not_stringified
- original = {Object.new => 2, 1 => 2, [] => true}
- indiff = original.with_indifferent_access
- assert(!indiff.keys.any? {|k| k.kind_of? String}, "A key was converted to a string!")
- end
-
def test_deep_merge
- hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
- hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
- expected = { :a => 1, :b => "b", :c => { :c1 => 2, :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
+ hash_1 = { a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } } }
+ hash_2 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } }
+ expected = { a: 1, b: "b", c: { c1: 2, c2: "c2", c3: { d1: "d1", d2: "d2" } } }
assert_equal expected, hash_1.deep_merge(hash_2)
hash_1.deep_merge!(hash_2)
@@ -757,60 +282,29 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_deep_merge_with_block
- hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
- hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
- expected = { :a => [:a, "a", 1], :b => "b", :c => { :c1 => [:c1, "c1", 2], :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
- assert_equal(expected, hash_1.deep_merge(hash_2) { |k,o,n| [k, o, n] })
+ hash_1 = { a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } } }
+ hash_2 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } }
+ expected = { a: [:a, "a", 1], b: "b", c: { c1: [:c1, "c1", 2], c2: "c2", c3: { d1: "d1", d2: "d2" } } }
+ assert_equal(expected, hash_1.deep_merge(hash_2) { |k, o, n| [k, o, n] })
- hash_1.deep_merge!(hash_2) { |k,o,n| [k, o, n] }
+ hash_1.deep_merge!(hash_2) { |k, o, n| [k, o, n] }
assert_equal expected, hash_1
end
def test_deep_merge_with_falsey_values
hash_1 = { e: false }
- hash_2 = { e: 'e' }
- expected = { e: [:e, false, 'e'] }
+ hash_2 = { e: "e" }
+ expected = { e: [:e, false, "e"] }
assert_equal(expected, hash_1.deep_merge(hash_2) { |k, o, n| [k, o, n] })
hash_1.deep_merge!(hash_2) { |k, o, n| [k, o, n] }
assert_equal expected, hash_1
end
- def test_deep_merge_on_indifferent_access
- hash_1 = HashWithIndifferentAccess.new({ :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } })
- hash_2 = HashWithIndifferentAccess.new({ :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } })
- hash_3 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
- expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } }
- assert_equal expected, hash_1.deep_merge(hash_2)
- assert_equal expected, hash_1.deep_merge(hash_3)
-
- hash_1.deep_merge!(hash_2)
- assert_equal expected, hash_1
- end
-
- def test_store_on_indifferent_access
- hash = HashWithIndifferentAccess.new
- hash.store(:test1, 1)
- hash.store('test1', 11)
- hash[:test2] = 2
- hash['test2'] = 22
- expected = { "test1" => 11, "test2" => 22 }
- assert_equal expected, hash
- end
-
- def test_constructor_on_indifferent_access
- hash = HashWithIndifferentAccess[:foo, 1]
- assert_equal 1, hash[:foo]
- assert_equal 1, hash['foo']
- hash[:foo] = 3
- assert_equal 3, hash[:foo]
- assert_equal 3, hash['foo']
- end
-
def test_reverse_merge
- defaults = { :a => "x", :b => "y", :c => 10 }.freeze
- options = { :a => 1, :b => 2 }
- expected = { :a => 1, :b => 2, :c => 10 }
+ defaults = { d: 0, a: "x", b: "y", c: 10 }.freeze
+ options = { a: 1, b: 2 }
+ expected = { d: 0, a: 1, b: 2, c: 10 }
# Should merge defaults into options, creating a new hash.
assert_equal expected, options.reverse_merge(defaults)
@@ -821,15 +315,33 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal expected, merged.reverse_merge!(defaults)
assert_equal expected, merged
+ # Make the order consistent with the non-overwriting reverse merge.
+ assert_equal expected.keys, merged.keys
+
# Should be an alias for reverse_merge!
merged = options.dup
assert_equal expected, merged.reverse_update(defaults)
assert_equal expected, merged
end
+ def test_with_defaults_aliases_reverse_merge
+ defaults = { a: "x", b: "y", c: 10 }.freeze
+ options = { a: 1, b: 2 }
+ expected = { a: 1, b: 2, c: 10 }
+
+ # Should be an alias for reverse_merge
+ assert_equal expected, options.with_defaults(defaults)
+ assert_not_equal expected, options
+
+ # Should be an alias for reverse_merge!
+ merged = options.dup
+ assert_equal expected, merged.with_defaults!(defaults)
+ assert_equal expected, merged
+ end
+
def test_slice
- original = { :a => 'x', :b => 'y', :c => 10 }
- expected = { :a => 'x', :b => 'y' }
+ original = { a: "x", b: "y", c: 10 }
+ expected = { a: "x", b: "y" }
# Should return a new hash with only the given keys.
assert_equal expected, original.slice(:a, :b)
@@ -837,15 +349,15 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_slice_inplace
- original = { :a => 'x', :b => 'y', :c => 10 }
- expected = { :c => 10 }
+ 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)
end
def test_slice_with_an_array_key
- original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
+ original = { :a => "x", :b => "y", :c => 10, [:a, :b] => "an array key" }
expected = { [:a, :b] => "an array key", :c => 10 }
# Should return a new hash with only the given keys when given an array key.
@@ -854,53 +366,21 @@ class HashExtTest < ActiveSupport::TestCase
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' }
+ 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)
end
def test_slice_with_splatted_keys
- original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
- expected = { :a => 'x', :b => "y" }
+ original = { :a => "x", :b => "y", :c => 10, [:a, :b] => "an array key" }
+ expected = { a: "x", b: "y" }
# Should grab each of the splatted keys.
assert_equal expected, original.slice(*[:a, :b])
end
- def test_indifferent_slice
- original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
- expected = { :a => 'x', :b => 'y' }.with_indifferent_access
-
- [['a', 'b'], [:a, :b]].each do |keys|
- # 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)
- end
- end
-
- def test_indifferent_slice_access_with_symbols
- original = {'login' => 'bender', 'password' => 'shiny', 'stuff' => 'foo'}
- original = original.with_indifferent_access
-
- slice = original.slice(:login, :password)
-
- assert_equal 'bender', slice[:login]
- assert_equal 'bender', slice['login']
- end
-
def test_slice_bang_does_not_override_default
hash = Hash.new(0)
hash.update(a: 1, b: 2)
@@ -920,39 +400,27 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_extract
- original = {:a => 1, :b => 2, :c => 3, :d => 4}
- expected = {:a => 1, :b => 2}
- remaining = {:c => 3, :d => 4}
+ original = { a: 1, b: 2, c: 3, d: 4 }
+ expected = { a: 1, b: 2 }
+ remaining = { c: 3, d: 4 }
assert_equal expected, original.extract!(:a, :b, :x)
assert_equal remaining, original
end
def test_extract_nils
- original = {:a => nil, :b => nil}
- expected = {:a => nil}
+ original = { a: nil, b: nil }
+ expected = { a: nil }
extracted = original.extract!(:a, :x)
assert_equal expected, extracted
- assert_equal nil, extracted[:a]
- assert_equal nil, extracted[:x]
- end
-
- def test_indifferent_extract
- original = {:a => 1, 'b' => 2, :c => 3, 'd' => 4}.with_indifferent_access
- expected = {:a => 1, :b => 2}.with_indifferent_access
- remaining = {:c => 3, :d => 4}.with_indifferent_access
-
- [['a', 'b'], [:a, :b]].each do |keys|
- copy = original.dup
- assert_equal expected, copy.extract!(*keys)
- assert_equal remaining, copy
- end
+ assert_nil extracted[:a]
+ assert_nil extracted[:x]
end
def test_except
- original = { :a => 'x', :b => 'y', :c => 10 }
- expected = { :a => 'x', :b => 'y' }
+ original = { a: "x", b: "y", c: 10 }
+ expected = { a: "x", b: "y" }
# Should return a new hash without the given keys.
assert_equal expected, original.except(:c)
@@ -964,8 +432,8 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_except_with_more_than_one_argument
- original = { :a => 'x', :b => 'y', :c => 10 }
- expected = { :a => 'x' }
+ original = { a: "x", b: "y", c: 10 }
+ expected = { a: "x" }
assert_equal expected, original.except(:b, :c)
@@ -974,15 +442,15 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_except_with_original_frozen
- original = { :a => 'x', :b => 'y' }
+ original = { a: "x", b: "y" }
original.freeze
assert_nothing_raised { original.except(:a) }
- assert_raise(RuntimeError) { original.except!(:a) }
+ assert_raise(frozen_error_class) { original.except!(:a) }
end
def test_except_does_not_delete_values_in_original
- original = { :a => 'x', :b => 'y' }
+ original = { a: "x", b: "y" }
assert_not_called(original, :delete) do
original.except(:a)
end
@@ -999,6 +467,10 @@ class HashExtTest < ActiveSupport::TestCase
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact)
assert_equal(hash_with_only_nil_values, h)
+
+ h = @symbols.dup
+ assert_equal(@symbols, h.compact)
+ assert_equal(@symbols, h)
end
def test_compact!
@@ -1012,71 +484,20 @@ class HashExtTest < ActiveSupport::TestCase
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact!)
assert_equal({}, h)
- end
-
- def test_new_with_to_hash_conversion
- hash = HashWithIndifferentAccess.new(HashByConversion.new(a: 1))
- assert hash.key?('a')
- assert_equal 1, hash[:a]
- end
- def test_dup_with_default_proc
- hash = HashWithIndifferentAccess.new
- hash.default_proc = proc { |h, v| raise "walrus" }
- assert_nothing_raised { hash.dup }
- end
-
- def test_dup_with_default_proc_sets_proc
- hash = HashWithIndifferentAccess.new
- hash.default_proc = proc { |h, k| k + 1 }
- new_hash = hash.dup
-
- assert_equal 3, new_hash[2]
-
- new_hash.default = 2
- assert_equal 2, new_hash[:non_existant]
- end
-
- def test_to_hash_with_raising_default_proc
- hash = HashWithIndifferentAccess.new
- hash.default_proc = proc { |h, k| raise "walrus" }
-
- assert_nothing_raised { hash.to_hash }
- end
-
- def test_new_from_hash_copying_default_should_not_raise_when_default_proc_does
- hash = Hash.new
- hash.default_proc = proc { |h, k| raise "walrus" }
-
- assert_deprecated { HashWithIndifferentAccess.new_from_hash_copying_default(hash) }
- end
-
- def test_new_with_to_hash_conversion_copies_default
- normal_hash = Hash.new(3)
- normal_hash[:a] = 1
-
- hash = HashWithIndifferentAccess.new(HashByConversion.new(normal_hash))
- assert_equal 1, hash[:a]
- assert_equal 3, hash[:b]
- end
-
- def test_new_with_to_hash_conversion_copies_default_proc
- normal_hash = Hash.new { 1 + 2 }
- normal_hash[:a] = 1
-
- hash = HashWithIndifferentAccess.new(HashByConversion.new(normal_hash))
- assert_equal 1, hash[:a]
- assert_equal 3, hash[:b]
+ h = @symbols.dup
+ assert_nil(h.compact!)
+ assert_equal(@symbols, h)
end
end
class IWriteMyOwnXML
def to_xml(options = {})
options[:indent] ||= 2
- xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
+ xml = options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
xml.instruct! unless options[:skip_instruct]
xml.level_one do
- xml.tag!(:second_level, 'content')
+ xml.tag!(:second_level, "content")
end
end
end
@@ -1089,139 +510,139 @@ class HashExtToParamTests < ActiveSupport::TestCase
end
def test_string_hash
- assert_equal '', {}.to_param
- assert_equal 'hello=world', { :hello => "world" }.to_param
- assert_equal 'hello=10', { "hello" => 10 }.to_param
- assert_equal 'hello=world&say_bye=true', {:hello => "world", "say_bye" => true}.to_param
+ assert_equal "", {}.to_param
+ assert_equal "hello=world", { hello: "world" }.to_param
+ assert_equal "hello=10", { "hello" => 10 }.to_param
+ assert_equal "hello=world&say_bye=true", { :hello => "world", "say_bye" => true }.to_param
end
def test_number_hash
- assert_equal '10=20&30=40&50=60', {10 => 20, 30 => 40, 50 => 60}.to_param
+ assert_equal "10=20&30=40&50=60", { 10 => 20, 30 => 40, 50 => 60 }.to_param
end
def test_to_param_hash
- assert_equal 'custom-1=param-1&custom2-1=param2-1', {ToParam.new('custom') => ToParam.new('param'), ToParam.new('custom2') => ToParam.new('param2')}.to_param
+ assert_equal "custom-1=param-1&custom2-1=param2-1", { ToParam.new("custom") => ToParam.new("param"), ToParam.new("custom2") => ToParam.new("param2") }.to_param
end
def test_to_param_hash_escapes_its_keys_and_values
- assert_equal 'param+1=A+string+with+%2F+characters+%26+that+should+be+%3F+escaped', { 'param 1' => 'A string with / characters & that should be ? escaped' }.to_param
+ assert_equal "param+1=A+string+with+%2F+characters+%26+that+should+be+%3F+escaped", { "param 1" => "A string with / characters & that should be ? escaped" }.to_param
end
def test_to_param_orders_by_key_in_ascending_order
- assert_equal 'a=2&b=1&c=0', Hash[*%w(b 1 c 0 a 2)].to_param
+ assert_equal "a=2&b=1&c=0", Hash[*%w(b 1 c 0 a 2)].to_param
end
end
class HashToXmlTest < ActiveSupport::TestCase
def setup
- @xml_options = { :root => :person, :skip_instruct => true, :indent => 0 }
+ @xml_options = { root: :person, skip_instruct: true, indent: 0 }
end
def test_one_level
- xml = { :name => "David", :street => "Paulina" }.to_xml(@xml_options)
+ xml = { name: "David", street: "Paulina" }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<street>Paulina</street>))
- assert xml.include?(%(<name>David</name>))
+ assert_includes xml, %(<street>Paulina</street>)
+ assert_includes xml, %(<name>David</name>)
end
def test_one_level_dasherize_false
- xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:dasherize => false))
+ xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(dasherize: false))
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<street_name>Paulina</street_name>))
- assert xml.include?(%(<name>David</name>))
+ assert_includes xml, %(<street_name>Paulina</street_name>)
+ assert_includes xml, %(<name>David</name>)
end
def test_one_level_dasherize_true
- xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:dasherize => true))
+ xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(dasherize: true))
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<street-name>Paulina</street-name>))
- assert xml.include?(%(<name>David</name>))
+ assert_includes xml, %(<street-name>Paulina</street-name>)
+ assert_includes xml, %(<name>David</name>)
end
def test_one_level_camelize_true
- xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(: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>))
+ assert_includes xml, %(<StreetName>Paulina</StreetName>)
+ assert_includes xml, %(<Name>David</Name>)
end
def test_one_level_camelize_lower
- xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:camelize => :lower))
+ xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(camelize: :lower))
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<streetName>Paulina</streetName>))
- assert xml.include?(%(<name>David</name>))
+ assert_includes xml, %(<streetName>Paulina</streetName>)
+ assert_includes xml, %(<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)
+ 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)
- assert xml.include?(%(<street>Paulina</street>))
- assert xml.include?(%(<name>David</name>))
- assert xml.include?(%(<age type="integer">26</age>))
- assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>))
- assert xml.include?(%(<moved-on type="date">2005-11-15</moved-on>))
- assert xml.include?(%(<resident type="symbol">yes</resident>))
+ assert_includes xml, %(<street>Paulina</street>)
+ assert_includes xml, %(<name>David</name>)
+ assert_includes xml, %(<age type="integer">26</age>)
+ assert_includes xml, %(<age-in-millis type="integer">820497600000</age-in-millis>)
+ assert_includes xml, %(<moved-on type="date">2005-11-15</moved-on>)
+ assert_includes xml, %(<resident type="symbol">yes</resident>)
end
def test_one_level_with_nils
- xml = { :name => "David", :street => "Paulina", :age => nil }.to_xml(@xml_options)
+ xml = { name: "David", street: "Paulina", age: nil }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<street>Paulina</street>))
- assert xml.include?(%(<name>David</name>))
- assert xml.include?(%(<age nil="true"/>))
+ assert_includes xml, %(<street>Paulina</street>)
+ assert_includes xml, %(<name>David</name>)
+ assert_includes xml, %(<age nil="true"/>)
end
def test_one_level_with_skipping_types
- xml = { :name => "David", :street => "Paulina", :age => nil }.to_xml(@xml_options.merge(:skip_types => true))
+ xml = { name: "David", street: "Paulina", age: nil }.to_xml(@xml_options.merge(skip_types: true))
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<street>Paulina</street>))
- assert xml.include?(%(<name>David</name>))
- assert xml.include?(%(<age nil="true"/>))
+ assert_includes xml, %(<street>Paulina</street>)
+ assert_includes xml, %(<name>David</name>)
+ assert_includes xml, %(<age nil="true"/>)
end
def test_one_level_with_yielding
- xml = { :name => "David", :street => "Paulina" }.to_xml(@xml_options) do |x|
+ xml = { name: "David", street: "Paulina" }.to_xml(@xml_options) do |x|
x.creator("Rails")
end
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<street>Paulina</street>))
- assert xml.include?(%(<name>David</name>))
- assert xml.include?(%(<creator>Rails</creator>))
+ assert_includes xml, %(<street>Paulina</street>)
+ assert_includes xml, %(<name>David</name>)
+ assert_includes xml, %(<creator>Rails</creator>)
end
def test_two_levels
- xml = { :name => "David", :address => { :street => "Paulina" } }.to_xml(@xml_options)
+ xml = { name: "David", address: { street: "Paulina" } }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<address><street>Paulina</street></address>))
- assert xml.include?(%(<name>David</name>))
+ assert_includes xml, %(<address><street>Paulina</street></address>)
+ assert_includes xml, %(<name>David</name>)
end
def test_two_levels_with_second_level_overriding_to_xml
- xml = { :name => "David", :address => { :street => "Paulina" }, :child => IWriteMyOwnXML.new }.to_xml(@xml_options)
+ xml = { name: "David", address: { street: "Paulina" }, child: IWriteMyOwnXML.new }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<address><street>Paulina</street></address>))
- assert xml.include?(%(<level_one><second_level>content</second_level></level_one>))
+ assert_includes xml, %(<address><street>Paulina</street></address>)
+ assert_includes xml, %(<level_one><second_level>content</second_level></level_one>)
end
def test_two_levels_with_array
- xml = { :name => "David", :addresses => [{ :street => "Paulina" }, { :street => "Evergreen" }] }.to_xml(@xml_options)
+ xml = { name: "David", addresses: [{ street: "Paulina" }, { street: "Evergreen" }] }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
- assert xml.include?(%(<addresses type="array"><address>))
- assert xml.include?(%(<address><street>Paulina</street></address>))
- assert xml.include?(%(<address><street>Evergreen</street></address>))
- assert xml.include?(%(<name>David</name>))
+ assert_includes xml, %(<addresses type="array"><address>)
+ assert_includes xml, %(<address><street>Paulina</street></address>)
+ assert_includes xml, %(<address><street>Evergreen</street></address>)
+ assert_includes xml, %(<name>David</name>)
end
def test_three_levels_with_array
- xml = { :name => "David", :addresses => [{ :streets => [ { :name => "Paulina" }, { :name => "Paulina" } ] } ] }.to_xml(@xml_options)
- assert xml.include?(%(<addresses type="array"><address><streets type="array"><street><name>))
+ xml = { name: "David", addresses: [{ streets: [ { name: "Paulina" }, { name: "Paulina" } ] } ] }.to_xml(@xml_options)
+ assert_includes xml, %(<addresses type="array"><address><streets type="array"><street><name>)
end
def test_timezoned_attributes
xml = {
- :created_at => Time.utc(1999,2,2),
- :local_created_at => Time.utc(1999,2,2).in_time_zone('Eastern Time (US & Canada)')
+ created_at: Time.utc(1999, 2, 2),
+ local_created_at: Time.utc(1999, 2, 2).in_time_zone("Eastern Time (US & Canada)")
}.to_xml(@xml_options)
assert_match %r{<created-at type=\"dateTime\">1999-02-02T00:00:00Z</created-at>}, xml
assert_match %r{<local-created-at type=\"dateTime\">1999-02-01T19:00:00-05:00</local-created-at>}, xml
@@ -1260,17 +681,17 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_topic_hash = {
- :title => "The First Topic",
- :author_name => "David",
- :id => 1,
- :approved => false,
- :replies_count => 0,
- :replies_close_in => 2592000000,
- :written_on => Date.new(2003, 7, 16),
- :viewed_at => Time.utc(2003, 7, 16, 9, 28),
- :content => "Have a nice day",
- :author_email_address => "david@loudthinking.com",
- :parent_id => nil
+ title: "The First Topic",
+ author_name: "David",
+ id: 1,
+ approved: false,
+ replies_count: 0,
+ replies_close_in: 2592000000,
+ written_on: Date.new(2003, 7, 16),
+ viewed_at: Time.utc(2003, 7, 16, 9, 28),
+ content: "Have a nice day",
+ author_email_address: "david@loudthinking.com",
+ parent_id: nil
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
@@ -1295,18 +716,18 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_topic_hash = {
- :title => "The First Topic",
- :author_name => "David",
- :id => 1,
- :approved => true,
- :replies_count => 0,
- :replies_close_in => 2592000000,
- :written_on => Date.new(2003, 7, 16),
- :viewed_at => Time.utc(2003, 7, 16, 9, 28),
- :author_email_address => "david@loudthinking.com",
- :parent_id => nil,
- :ad_revenue => BigDecimal("1.50"),
- :optimum_viewing_angle => 135.0,
+ title: "The First Topic",
+ author_name: "David",
+ id: 1,
+ approved: true,
+ replies_count: 0,
+ replies_close_in: 2592000000,
+ written_on: Date.new(2003, 7, 16),
+ viewed_at: Time.utc(2003, 7, 16, 9, 28),
+ author_email_address: "david@loudthinking.com",
+ parent_id: nil,
+ ad_revenue: BigDecimal("1.50"),
+ optimum_viewing_angle: 135.0,
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
@@ -1325,12 +746,12 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_topic_hash = {
- :title => nil,
- :id => nil,
- :approved => nil,
- :written_on => nil,
- :viewed_at => nil,
- :parent_id => nil
+ title: nil,
+ id: nil,
+ approved: nil,
+ written_on: nil,
+ viewed_at: nil,
+ parent_id: nil
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
@@ -1369,17 +790,17 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_topic_hash = {
- :title => "The First Topic",
- :author_name => "David",
- :id => 1,
- :approved => false,
- :replies_count => 0,
- :replies_close_in => 2592000000,
- :written_on => Date.new(2003, 7, 16),
- :viewed_at => Time.utc(2003, 7, 16, 9, 28),
- :content => "Have a nice day",
- :author_email_address => "david@loudthinking.com",
- :parent_id => nil
+ title: "The First Topic",
+ author_name: "David",
+ id: 1,
+ approved: false,
+ replies_count: 0,
+ replies_close_in: 2592000000,
+ written_on: Date.new(2003, 7, 16),
+ viewed_at: Time.utc(2003, 7, 16, 9, 28),
+ content: "Have a nice day",
+ author_email_address: "david@loudthinking.com",
+ parent_id: nil
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
@@ -1395,14 +816,14 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_topic_hash = {
- :id => "175756086",
- :owner => "55569174@N00",
- :secret => "0279bf37a1",
- :server => "76",
- :title => "Colored Pencil PhotoBooth Fun",
- :ispublic => "1",
- :isfriend => "0",
- :isfamily => "0",
+ id: "175756086",
+ owner: "55569174@N00",
+ secret: "0279bf37a1",
+ server: "76",
+ title: "Colored Pencil PhotoBooth Fun",
+ ispublic: "1",
+ isfriend: "0",
+ isfamily: "0",
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["rsp"]["photos"]["photo"]
@@ -1430,7 +851,7 @@ class HashToXmlTest < ActiveSupport::TestCase
<posts type="array"></posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => []}}
+ expected_blog_hash = { "blog" => { "posts" => [] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1441,7 +862,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => []}}
+ expected_blog_hash = { "blog" => { "posts" => [] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1453,7 +874,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => ["a post"]}}
+ expected_blog_hash = { "blog" => { "posts" => ["a post"] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1466,7 +887,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => ["a post", "another post"]}}
+ expected_blog_hash = { "blog" => { "posts" => ["a post", "another post"] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1478,12 +899,12 @@ class HashToXmlTest < ActiveSupport::TestCase
</blog>
XML
hash = Hash.from_xml(blog_xml)
- assert hash.has_key?('blog')
- assert hash['blog'].has_key?('logo')
+ assert hash.has_key?("blog")
+ assert hash["blog"].has_key?("logo")
- file = hash['blog']['logo']
- assert_equal 'logo.png', file.original_filename
- assert_equal 'image/png', file.content_type
+ file = hash["blog"]["logo"]
+ assert_equal "logo.png", file.original_filename
+ assert_equal "image/png", file.content_type
end
def test_file_from_xml_with_defaults
@@ -1493,9 +914,9 @@ class HashToXmlTest < ActiveSupport::TestCase
</logo>
</blog>
XML
- file = Hash.from_xml(blog_xml)['blog']['logo']
- assert_equal 'untitled', file.original_filename
- assert_equal 'application/octet-stream', file.content_type
+ file = Hash.from_xml(blog_xml)["blog"]["logo"]
+ assert_equal "untitled", file.original_filename
+ assert_equal "application/octet-stream", file.content_type
end
def test_tag_with_attrs_and_whitespace
@@ -1504,7 +925,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</blog>
XML
hash = Hash.from_xml(xml)
- assert_equal "bacon is the best", hash['blog']['name']
+ assert_equal "bacon is the best", hash["blog"]["name"]
end
def test_empty_cdata_from_xml
@@ -1527,13 +948,13 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_bacon_hash = {
- :weight => 0.5,
- :chunky => true,
- :price => BigDecimal("12.50"),
- :expires_at => Time.utc(2007,12,25,12,34,56),
- :notes => "",
- :illustration => "babe.png",
- :caption => "That'll do, pig."
+ weight: 0.5,
+ chunky: true,
+ price: BigDecimal("12.50"),
+ expires_at: Time.utc(2007, 12, 25, 12, 34, 56),
+ notes: "",
+ illustration: "babe.png",
+ caption: "That'll do, pig."
}.stringify_keys
assert_equal expected_bacon_hash, Hash.from_xml(bacon_xml)["bacon"]
@@ -1549,8 +970,8 @@ class HashToXmlTest < ActiveSupport::TestCase
EOT
expected_product_hash = {
- :weight => 0.5,
- :image => {'type' => 'ProductImage', 'filename' => 'image.gif' },
+ weight: 0.5,
+ image: { "type" => "ProductImage", "filename" => "image.gif" },
}.stringify_keys
assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
@@ -1573,81 +994,26 @@ class HashToXmlTest < ActiveSupport::TestCase
end
def test_from_xml_array_one
- expected = { 'numbers' => { 'type' => 'Array', 'value' => '1' }}
+ expected = { "numbers" => { "type" => "Array", "value" => "1" } }
assert_equal expected, Hash.from_xml('<numbers type="Array"><value>1</value></numbers>')
end
def test_from_xml_array_many
- expected = { 'numbers' => { 'type' => 'Array', 'value' => [ '1', '2' ] }}
+ expected = { "numbers" => { "type" => "Array", "value" => [ "1", "2" ] } }
assert_equal expected, Hash.from_xml('<numbers type="Array"><value>1</value><value>2</value></numbers>')
end
def test_from_trusted_xml_allows_symbol_and_yaml_types
- expected = { 'product' => { 'name' => :value }}
+ expected = { "product" => { "name" => :value } }
assert_equal expected, Hash.from_trusted_xml('<product><name type="symbol">value</name></product>')
assert_equal expected, Hash.from_trusted_xml('<product><name type="yaml">:value</name></product>')
end
- def test_should_use_default_proc_for_unknown_key
- hash_wia = HashWithIndifferentAccess.new { 1 + 2 }
- assert_equal 3, hash_wia[:new_key]
- end
-
- def test_should_return_nil_if_no_key_is_supplied
- hash_wia = HashWithIndifferentAccess.new { 1 + 2 }
- assert_equal nil, hash_wia.default
- end
-
- def test_should_use_default_value_for_unknown_key
- hash_wia = HashWithIndifferentAccess.new(3)
- assert_equal 3, hash_wia[:new_key]
- end
-
- def test_should_use_default_value_if_no_key_is_supplied
- hash_wia = HashWithIndifferentAccess.new(3)
- assert_equal 3, hash_wia.default
- end
-
- def test_should_nil_if_no_default_value_is_supplied
- hash_wia = HashWithIndifferentAccess.new
- assert_nil hash_wia.default
- end
-
- def test_should_return_dup_for_with_indifferent_access
- hash_wia = HashWithIndifferentAccess.new
- assert_equal hash_wia, hash_wia.with_indifferent_access
- assert_not_same hash_wia, hash_wia.with_indifferent_access
- end
-
- def test_allows_setting_frozen_array_values_with_indifferent_access
- value = [1, 2, 3].freeze
- hash = HashWithIndifferentAccess.new
- hash[:key] = value
- assert_equal hash[:key], value
- end
-
- def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
- hash = Hash.new(3)
- hash_wia = hash.with_indifferent_access
- assert_equal 3, hash_wia.default
- end
-
- def test_should_copy_the_default_proc_when_converting_to_hash_with_indifferent_access
- hash = Hash.new do
- 2 + 1
- end
- assert_equal 3, hash[:foo]
-
- hash_wia = hash.with_indifferent_access
- assert_equal 3, hash_wia[:foo]
- assert_equal 3, hash_wia[:bar]
- end
-
# The XML builder seems to fail miserably when trying to tag something
# with the same name as a Kernel method (throw, test, loop, select ...)
def test_kernel_method_names_to_xml
- hash = { :throw => { :ball => 'red' } }
- expected = '<person><throw><ball>red</ball></throw></person>'
+ hash = { throw: { ball: "red" } }
+ expected = "<person><throw><ball>red</ball></throw></person>"
assert_nothing_raised do
assert_equal expected, hash.to_xml(@xml_options)
@@ -1662,30 +1028,30 @@ class HashToXmlTest < ActiveSupport::TestCase
def test_escaping_to_xml
hash = {
- :bare_string => 'First & Last Name',
- :pre_escaped_string => 'First &amp; Last Name'
+ bare_string: "First & Last Name",
+ pre_escaped_string: "First &amp; Last Name"
}.stringify_keys
- expected_xml = '<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>'
+ expected_xml = "<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>"
assert_equal expected_xml, hash.to_xml(@xml_options)
end
def test_unescaping_from_xml
- xml_string = '<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>'
+ xml_string = "<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>"
expected_hash = {
- :bare_string => 'First & Last Name',
- :pre_escaped_string => 'First &amp; Last Name'
+ bare_string: "First & Last Name",
+ pre_escaped_string: "First &amp; Last Name"
}.stringify_keys
- assert_equal expected_hash, Hash.from_xml(xml_string)['person']
+ assert_equal expected_hash, Hash.from_xml(xml_string)["person"]
end
def test_roundtrip_to_xml_from_xml
hash = {
- :bare_string => 'First & Last Name',
- :pre_escaped_string => 'First &amp; Last Name'
+ bare_string: "First & Last Name",
+ pre_escaped_string: "First &amp; Last Name"
}.stringify_keys
- assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))['person']
+ assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))["person"]
end
def test_datetime_xml_type_with_utc_time
@@ -1694,7 +1060,7 @@ class HashToXmlTest < ActiveSupport::TestCase
<alert_at type="datetime">2008-02-10T15:30:45Z</alert_at>
</alert>
XML
- alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
+ alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
assert alert_at.utc?
assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
end
@@ -1705,7 +1071,7 @@ class HashToXmlTest < ActiveSupport::TestCase
<alert_at type="datetime">2008-02-10T10:30:45-05:00</alert_at>
</alert>
XML
- alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
+ alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
assert alert_at.utc?
assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
end
@@ -1716,7 +1082,7 @@ class HashToXmlTest < ActiveSupport::TestCase
<alert_at type="datetime">2050-02-10T15:30:45Z</alert_at>
</alert>
XML
- alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
+ alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
assert alert_at.utc?
assert_equal 2050, alert_at.year
assert_equal 2, alert_at.month
@@ -1727,20 +1093,20 @@ class HashToXmlTest < ActiveSupport::TestCase
end
def test_to_xml_dups_options
- options = {:skip_instruct => true}
+ options = { skip_instruct: true }
{}.to_xml(options)
# :builder, etc, shouldn't be added to options
- assert_equal({:skip_instruct => true}, options)
+ assert_equal({ skip_instruct: true }, options)
end
def test_expansion_count_is_limited
expected =
case ActiveSupport::XmlMini.backend.name
- when 'ActiveSupport::XmlMini_REXML'; RuntimeError
- when 'ActiveSupport::XmlMini_Nokogiri'; Nokogiri::XML::SyntaxError
- when 'ActiveSupport::XmlMini_NokogiriSAX'; RuntimeError
- when 'ActiveSupport::XmlMini_LibXML'; LibXML::XML::Error
- when 'ActiveSupport::XmlMini_LibXMLSAX'; LibXML::XML::Error
+ when "ActiveSupport::XmlMini_REXML"; RuntimeError
+ when "ActiveSupport::XmlMini_Nokogiri"; Nokogiri::XML::SyntaxError
+ when "ActiveSupport::XmlMini_NokogiriSAX"; RuntimeError
+ when "ActiveSupport::XmlMini_LibXML"; LibXML::XML::Error
+ when "ActiveSupport::XmlMini_LibXMLSAX"; LibXML::XML::Error
end
assert_raise expected do
diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb
index 41736fb672..14169b084d 100644
--- a/activesupport/test/core_ext/integer_ext_test.rb
+++ b/activesupport/test/core_ext/integer_ext_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/integer'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/integer"
class IntegerExtTest < ActiveSupport::TestCase
PRIME = 22953686867719691230002707821868552601124472329079
@@ -19,12 +21,12 @@ class IntegerExtTest < ActiveSupport::TestCase
def test_ordinalize
# These tests are mostly just to ensure that the ordinalize method exists.
# Its results are tested comprehensively in the inflector test cases.
- assert_equal '1st', 1.ordinalize
- assert_equal '8th', 8.ordinalize
+ assert_equal "1st", 1.ordinalize
+ assert_equal "8th", 8.ordinalize
end
def test_ordinal
- assert_equal 'st', 1.ordinal
- assert_equal 'th', 8.ordinal
+ assert_equal "st", 1.ordinal
+ assert_equal "th", 8.ordinal
end
end
diff --git a/activesupport/test/core_ext/kernel/concern_test.rb b/activesupport/test/core_ext/kernel/concern_test.rb
index 478a00d2d2..b40ff6a623 100644
--- a/activesupport/test/core_ext/kernel/concern_test.rb
+++ b/activesupport/test/core_ext/kernel/concern_test.rb
@@ -1,9 +1,11 @@
-require 'abstract_unit'
-require 'active_support/core_ext/kernel/concern'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/kernel/concern"
class KernelConcernTest < ActiveSupport::TestCase
def test_may_be_defined_at_toplevel
- mod = ::TOPLEVEL_BINDING.eval 'concern(:ToplevelConcern) { }'
+ mod = ::TOPLEVEL_BINDING.eval "concern(:ToplevelConcern) { }"
assert_equal mod, ::ToplevelConcern
assert_kind_of ActiveSupport::Concern, ::ToplevelConcern
assert_not Object.ancestors.include?(::ToplevelConcern), mod.ancestors.inspect
diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb
index 503e6595cb..ef11e10af8 100644
--- a/activesupport/test/core_ext/kernel_test.rb
+++ b/activesupport/test/core_ext/kernel_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/kernel'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/kernel"
class KernelTest < ActiveSupport::TestCase
def test_silence_warnings
@@ -49,19 +51,3 @@ class KernelSuppressTest < ActiveSupport::TestCase
suppress(LoadError, ArgumentError) { raise ArgumentError }
end
end
-
-class MockStdErr
- attr_reader :output
- def puts(message)
- @output ||= []
- @output << message
- end
-
- def info(message)
- puts(message)
- end
-
- def write(message)
- puts(message)
- end
-end
diff --git a/activesupport/test/core_ext/load_error_test.rb b/activesupport/test/core_ext/load_error_test.rb
index b2a75a2bcc..41b11d0c33 100644
--- a/activesupport/test/core_ext/load_error_test.rb
+++ b/activesupport/test/core_ext/load_error_test.rb
@@ -1,26 +1,19 @@
-require 'abstract_unit'
-require 'active_support/core_ext/load_error'
+# frozen_string_literal: true
-
-class TestMissingSourceFile < ActiveSupport::TestCase
- def test_it_is_deprecated
- assert_deprecated do
- MissingSourceFile.new
- end
- end
-end
+require "abstract_unit"
+require "active_support/core_ext/load_error"
class TestLoadError < ActiveSupport::TestCase
def test_with_require
- assert_raise(LoadError) { require 'no_this_file_don\'t_exist' }
+ assert_raise(LoadError) { require "no_this_file_don't_exist" }
end
def test_with_load
- assert_raise(LoadError) { load 'nor_does_this_one' }
+ assert_raise(LoadError) { load "nor_does_this_one" }
end
def test_path
- begin load 'nor/this/one.rb'
+ begin load "nor/this/one.rb"
rescue LoadError => e
- assert_equal 'nor/this/one.rb', e.path
+ assert_equal "nor/this/one.rb", e.path
end
end
end
diff --git a/activesupport/test/core_ext/marshal_test.rb b/activesupport/test/core_ext/marshal_test.rb
index 380f64c6fd..7ac051b4b1 100644
--- a/activesupport/test/core_ext/marshal_test.rb
+++ b/activesupport/test/core_ext/marshal_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/core_ext/marshal'
-require 'dependencies_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/marshal"
+require "dependencies_test_helpers"
class MarshalTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
@@ -12,13 +14,26 @@ class MarshalTest < ActiveSupport::TestCase
end
test "that Marshal#load still works" do
- sanity_data = ["test", [1, 2, 3], {a: [1, 2, 3]}, ActiveSupport::TestCase]
+ sanity_data = ["test", [1, 2, 3], { a: [1, 2, 3] }, ActiveSupport::TestCase]
sanity_data.each do |obj|
dumped = Marshal.dump(obj)
assert_equal Marshal.method(:load).super_method.call(dumped), Marshal.load(dumped)
end
end
+ test "that Marshal#load still works when passed a proc" do
+ example_string = "test"
+
+ example_proc = Proc.new do |o|
+ if o.is_a?(String)
+ o.capitalize!
+ end
+ end
+
+ dumped = Marshal.dump(example_string)
+ assert_equal Marshal.load(dumped, example_proc), "Test"
+ end
+
test "that a missing class is autoloaded from string" do
dumped = nil
with_autoloading_fixtures do
diff --git a/activesupport/test/core_ext/module/anonymous_test.rb b/activesupport/test/core_ext/module/anonymous_test.rb
index cb556af772..606f22c9b5 100644
--- a/activesupport/test/core_ext/module/anonymous_test.rb
+++ b/activesupport/test/core_ext/module/anonymous_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/anonymous'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/anonymous"
class AnonymousTest < ActiveSupport::TestCase
test "an anonymous class or module are anonymous" do
@@ -11,4 +13,4 @@ class AnonymousTest < ActiveSupport::TestCase
assert !Kernel.anonymous?
assert !Object.anonymous?
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/core_ext/module/attr_internal_test.rb b/activesupport/test/core_ext/module/attr_internal_test.rb
index 2aea14cf2b..c2a28eced4 100644
--- a/activesupport/test/core_ext/module/attr_internal_test.rb
+++ b/activesupport/test/core_ext/module/attr_internal_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/attr_internal'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/attr_internal"
class AttrInternalTest < ActiveSupport::TestCase
def setup
@@ -10,44 +12,44 @@ class AttrInternalTest < ActiveSupport::TestCase
def test_reader
assert_nothing_raised { @target.attr_internal_reader :foo }
- assert !@instance.instance_variable_defined?('@_foo')
+ assert !@instance.instance_variable_defined?("@_foo")
assert_raise(NoMethodError) { @instance.foo = 1 }
- @instance.instance_variable_set('@_foo', 1)
+ @instance.instance_variable_set("@_foo", 1)
assert_nothing_raised { assert_equal 1, @instance.foo }
end
def test_writer
assert_nothing_raised { @target.attr_internal_writer :foo }
- assert !@instance.instance_variable_defined?('@_foo')
+ assert !@instance.instance_variable_defined?("@_foo")
assert_nothing_raised { assert_equal 1, @instance.foo = 1 }
- assert_equal 1, @instance.instance_variable_get('@_foo')
+ assert_equal 1, @instance.instance_variable_get("@_foo")
assert_raise(NoMethodError) { @instance.foo }
end
def test_accessor
assert_nothing_raised { @target.attr_internal :foo }
- assert !@instance.instance_variable_defined?('@_foo')
+ assert !@instance.instance_variable_defined?("@_foo")
assert_nothing_raised { assert_equal 1, @instance.foo = 1 }
- assert_equal 1, @instance.instance_variable_get('@_foo')
+ assert_equal 1, @instance.instance_variable_get("@_foo")
assert_nothing_raised { assert_equal 1, @instance.foo }
end
def test_naming_format
- assert_equal '@_%s', Module.attr_internal_naming_format
- assert_nothing_raised { Module.attr_internal_naming_format = '@abc%sdef' }
+ assert_equal "@_%s", Module.attr_internal_naming_format
+ assert_nothing_raised { Module.attr_internal_naming_format = "@abc%sdef" }
@target.attr_internal :foo
- assert !@instance.instance_variable_defined?('@_foo')
- assert !@instance.instance_variable_defined?('@abcfoodef')
+ assert !@instance.instance_variable_defined?("@_foo")
+ assert !@instance.instance_variable_defined?("@abcfoodef")
assert_nothing_raised { @instance.foo = 1 }
- assert !@instance.instance_variable_defined?('@_foo')
- assert @instance.instance_variable_defined?('@abcfoodef')
+ assert !@instance.instance_variable_defined?("@_foo")
+ assert @instance.instance_variable_defined?("@abcfoodef")
ensure
- Module.attr_internal_naming_format = '@_%s'
+ Module.attr_internal_naming_format = "@_%s"
end
end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb b/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
index a9fd878b80..e0fbd1002c 100644
--- a/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
+++ b/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/attribute_accessors_per_thread'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/attribute_accessors_per_thread"
class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
def setup
@@ -8,6 +10,12 @@ class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
thread_mattr_accessor :bar, instance_writer: false
thread_mattr_reader :shaq, instance_reader: false
thread_mattr_accessor :camp, instance_accessor: false
+
+ def self.name; "MyClass" end
+ end
+
+ @subclass = Class.new(@class) do
+ def self.name; "SubMyClass" end
end
@object = @class.new
@@ -57,23 +65,23 @@ class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
def test_values_should_not_bleed_between_threads
threads = []
threads << Thread.new do
- @class.foo = 'things'
+ @class.foo = "things"
sleep 1
- assert_equal 'things', @class.foo
+ assert_equal "things", @class.foo
end
threads << Thread.new do
- @class.foo = 'other things'
+ @class.foo = "other things"
sleep 1
- assert_equal 'other things', @class.foo
+ assert_equal "other things", @class.foo
end
-
+
threads << Thread.new do
- @class.foo = 'really other things'
+ @class.foo = "really other things"
sleep 1
- assert_equal 'really other things', @class.foo
+ assert_equal "really other things", @class.foo
end
-
+
threads.each { |t| t.join }
end
@@ -108,8 +116,18 @@ class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
end
def test_should_return_same_value_by_class_or_instance_accessor
- @class.foo = 'fries'
+ @class.foo = "fries"
assert_equal @class.foo, @object.foo
end
+
+ def test_should_not_affect_superclass_if_subclass_set_value
+ @class.foo = "super"
+ assert_equal "super", @class.foo
+ assert_nil @subclass.foo
+
+ @subclass.foo = "sub"
+ assert_equal "super", @class.foo
+ assert_equal "sub", @subclass.foo
+ end
end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb
index 0b0f3a2808..f1d6859a88 100644
--- a/activesupport/test/core_ext/module/attribute_accessor_test.rb
+++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb
@@ -1,18 +1,27 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/attribute_accessors'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/attribute_accessors"
class ModuleAttributeAccessorTest < ActiveSupport::TestCase
def setup
m = @module = Module.new do
mattr_accessor :foo
- mattr_accessor :bar, :instance_writer => false
- mattr_reader :shaq, :instance_reader => false
- mattr_accessor :camp, :instance_accessor => false
+ mattr_accessor :bar, instance_writer: false
+ mattr_reader :shaq, instance_reader: false
+ mattr_accessor :camp, instance_accessor: false
- cattr_accessor(:defa) { 'default_accessor_value' }
- cattr_reader(:defr) { 'default_reader_value' }
- cattr_writer(:defw) { 'default_writer_value' }
+ cattr_accessor(:defa) { "default_accessor_value" }
+ cattr_reader(:defr) { "default_reader_value" }
+ cattr_writer(:defw) { "default_writer_value" }
+ cattr_accessor(:deff) { false }
cattr_accessor(:quux) { :quux }
+
+ cattr_accessor :def_accessor, default: "default_accessor_value"
+ cattr_reader :def_reader, default: "default_reader_value"
+ cattr_writer :def_writer, default: "default_writer_value"
+ cattr_accessor :def_false, default: false
+ cattr_accessor(:def_priority, default: false) { :no_priority }
end
@class = Class.new
@class.instance_eval { include m }
@@ -24,6 +33,21 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
assert_nil @object.foo
end
+ def test_mattr_default_keyword_arguments
+ assert_equal "default_accessor_value", @module.def_accessor
+ assert_equal "default_reader_value", @module.def_reader
+ assert_equal "default_writer_value", @module.class_variable_get(:@@def_writer)
+ end
+
+ def test_mattr_can_default_to_false
+ assert_equal false, @module.def_false
+ assert_equal false, @module.deff
+ end
+
+ def test_mattr_default_priority
+ assert_equal false, @module.def_priority
+ end
+
def test_should_set_mattr_value
@module.foo = :test
assert_equal :test, @object.foo
@@ -86,14 +110,28 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
end
def test_should_use_default_value_if_block_passed
- assert_equal 'default_accessor_value', @module.defa
- assert_equal 'default_reader_value', @module.defr
- assert_equal 'default_writer_value', @module.class_variable_get('@@defw')
+ assert_equal "default_accessor_value", @module.defa
+ assert_equal "default_reader_value", @module.defr
+ assert_equal "default_writer_value", @module.class_variable_get("@@defw")
end
- def test_should_not_invoke_default_value_block_multiple_times
+ def test_method_invocation_should_not_invoke_the_default_block
count = 0
- @module.cattr_accessor(:defcount){ count += 1 }
+
+ @module.cattr_accessor(:defcount) { count += 1 }
+
assert_equal 1, count
+ assert_no_difference "count" do
+ @module.defcount
+ end
+ end
+
+ def test_declaring_multiple_attributes_at_once_invokes_the_block_multiple_times
+ count = 0
+
+ @module.cattr_accessor(:defn1, :defn2) { count += 1 }
+
+ assert_equal 1, @module.defn1
+ assert_equal 2, @module.defn2
end
end
diff --git a/activesupport/test/core_ext/module/attribute_aliasing_test.rb b/activesupport/test/core_ext/module/attribute_aliasing_test.rb
index 29c3053b47..187a0f4da2 100644
--- a/activesupport/test/core_ext/module/attribute_aliasing_test.rb
+++ b/activesupport/test/core_ext/module/attribute_aliasing_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/aliasing'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/aliasing"
module AttributeAliasing
class Content
@@ -52,8 +54,8 @@ class AttributeAliasingTest < ActiveSupport::TestCase
assert_equal "No, really, this is not a joke.", e.Data
assert e.Data?
- e.Data = "Uppercased methods are teh suck"
- assert_equal "Uppercased methods are teh suck", e.body
+ e.Data = "Uppercased methods are the suck"
+ assert_equal "Uppercased methods are the suck", e.body
assert e.body?
end
end
diff --git a/activesupport/test/core_ext/module/concerning_test.rb b/activesupport/test/core_ext/module/concerning_test.rb
index 07d860b71c..192c3d5a9c 100644
--- a/activesupport/test/core_ext/module/concerning_test.rb
+++ b/activesupport/test/core_ext/module/concerning_test.rb
@@ -1,10 +1,12 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/concerning'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/concerning"
class ModuleConcerningTest < ActiveSupport::TestCase
def test_concerning_declares_a_concern_and_includes_it_immediately
- klass = Class.new { concerning(:Foo) { } }
- assert klass.ancestors.include?(klass::Foo), klass.ancestors.inspect
+ klass = Class.new { concerning(:Foo) {} }
+ assert_includes klass.ancestors, klass::Foo, klass.ancestors.inspect
end
end
@@ -21,13 +23,13 @@ class ModuleConcernTest < ActiveSupport::TestCase
assert klass.const_defined?(:Baz, false)
assert !ModuleConcernTest.const_defined?(:Baz)
assert_kind_of ActiveSupport::Concern, klass::Baz
- assert !klass.ancestors.include?(klass::Baz), klass.ancestors.inspect
+ assert_not_includes klass.ancestors, klass::Baz, klass.ancestors.inspect
# Public method visibility by default
- assert klass::Baz.public_instance_methods.map(&:to_s).include?('should_be_public')
+ assert_includes klass::Baz.public_instance_methods.map(&:to_s), "should_be_public"
# Calls included hook
- assert_equal 1, Class.new { include klass::Baz }.instance_variable_get('@foo')
+ assert_equal 1, Class.new { include klass::Baz }.instance_variable_get("@foo")
end
class Foo
diff --git a/activesupport/test/core_ext/module/introspection_test.rb b/activesupport/test/core_ext/module/introspection_test.rb
new file mode 100644
index 0000000000..76d3012239
--- /dev/null
+++ b/activesupport/test/core_ext/module/introspection_test.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/introspection"
+
+module ParentA
+ module B
+ module C; end
+ module FrozenC; end
+ FrozenC.freeze
+ end
+
+ module FrozenB; end
+ FrozenB.freeze
+end
+
+class IntrospectionTest < ActiveSupport::TestCase
+ def test_parent_name
+ assert_equal "ParentA", ParentA::B.parent_name
+ assert_equal "ParentA::B", ParentA::B::C.parent_name
+ assert_nil ParentA.parent_name
+ end
+
+ def test_parent_name_when_frozen
+ assert_equal "ParentA", ParentA::FrozenB.parent_name
+ assert_equal "ParentA::B", ParentA::B::FrozenC.parent_name
+ end
+
+ def test_parent
+ assert_equal ParentA::B, ParentA::B::C.parent
+ assert_equal ParentA, ParentA::B.parent
+ assert_equal Object, ParentA.parent
+ end
+
+ def test_parents
+ assert_equal [ParentA::B, ParentA, Object], ParentA::B::C.parents
+ assert_equal [ParentA, Object], ParentA::B.parents
+ end
+end
diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb
deleted file mode 100644
index a3146cabe1..0000000000
--- a/activesupport/test/core_ext/module/qualified_const_test.rb
+++ /dev/null
@@ -1,118 +0,0 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/qualified_const'
-
-module QualifiedConstTestMod
- X = false
-
- module M
- X = 1
-
- class C
- X = 2
- end
- end
-
- module N
- include M
- end
-end
-
-class QualifiedConstTest < ActiveSupport::TestCase
- test "Object.qualified_const_defined?" do
- assert_deprecated do
- assert Object.qualified_const_defined?("QualifiedConstTestMod")
- assert !Object.qualified_const_defined?("NonExistingQualifiedConstTestMod")
-
- assert Object.qualified_const_defined?("QualifiedConstTestMod::X")
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::Y")
-
- assert Object.qualified_const_defined?("QualifiedConstTestMod::M::X")
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::M::Y")
-
- if Module.method(:const_defined?).arity == 1
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
- else
- assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X", false)
- assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X", true)
- end
- end
- end
-
- test "mod.qualified_const_defined?" do
- assert_deprecated do
- assert QualifiedConstTestMod.qualified_const_defined?("M")
- assert !QualifiedConstTestMod.qualified_const_defined?("NonExistingM")
-
- assert QualifiedConstTestMod.qualified_const_defined?("M::X")
- assert !QualifiedConstTestMod.qualified_const_defined?("M::Y")
-
- assert QualifiedConstTestMod.qualified_const_defined?("M::C::X")
- assert !QualifiedConstTestMod.qualified_const_defined?("M::C::Y")
-
- if Module.method(:const_defined?).arity == 1
- assert !QualifiedConstTestMod.qualified_const_defined?("QualifiedConstTestMod::N::X")
- else
- assert QualifiedConstTestMod.qualified_const_defined?("N::X")
- assert !QualifiedConstTestMod.qualified_const_defined?("N::X", false)
- assert QualifiedConstTestMod.qualified_const_defined?("N::X", true)
- end
- end
- end
-
- test "qualified_const_get" do
- assert_deprecated do
- assert_equal false, Object.qualified_const_get("QualifiedConstTestMod::X")
- assert_equal false, QualifiedConstTestMod.qualified_const_get("X")
- assert_equal 1, QualifiedConstTestMod.qualified_const_get("M::X")
- assert_equal 1, QualifiedConstTestMod.qualified_const_get("N::X")
- assert_equal 2, QualifiedConstTestMod.qualified_const_get("M::C::X")
-
- assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y")}
- end
- end
-
- test "qualified_const_set" do
- assert_deprecated do
- begin
- m = Module.new
- assert_equal m, Object.qualified_const_set("QualifiedConstTestMod2", m)
- assert_equal m, ::QualifiedConstTestMod2
-
- # We are going to assign to existing constants on purpose, so silence warnings.
- silence_warnings do
- assert_equal true, QualifiedConstTestMod.qualified_const_set("QualifiedConstTestMod::X", true)
- assert_equal true, QualifiedConstTestMod::X
-
- assert_equal 10, QualifiedConstTestMod::M.qualified_const_set("X", 10)
- assert_equal 10, QualifiedConstTestMod::M::X
- end
- ensure
- silence_warnings do
- QualifiedConstTestMod.qualified_const_set('QualifiedConstTestMod::X', false)
- QualifiedConstTestMod::M.qualified_const_set('X', 1)
- end
- end
- end
- end
-
- test "reject absolute paths" do
- assert_deprecated do
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")}
-
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")}
-
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)}
- end
- end
-
- private
-
- def assert_raise_with_message(expected_exception, expected_message, &block)
- exception = assert_raise(expected_exception, &block)
- assert_equal expected_message, exception.message
- end
-end
diff --git a/activesupport/test/core_ext/module/reachable_test.rb b/activesupport/test/core_ext/module/reachable_test.rb
index 80eb31a5c4..097a72fa5b 100644
--- a/activesupport/test/core_ext/module/reachable_test.rb
+++ b/activesupport/test/core_ext/module/reachable_test.rb
@@ -1,15 +1,21 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/reachable'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/reachable"
class AnonymousTest < ActiveSupport::TestCase
test "an anonymous class or module is not reachable" do
- assert !Module.new.reachable?
- assert !Class.new.reachable?
+ assert_deprecated do
+ assert !Module.new.reachable?
+ assert !Class.new.reachable?
+ end
end
test "ordinary named classes or modules are reachable" do
- assert Kernel.reachable?
- assert Object.reachable?
+ assert_deprecated do
+ assert Kernel.reachable?
+ assert Object.reachable?
+ end
end
test "a named class or module whose constant has gone is not reachable" do
@@ -19,8 +25,10 @@ class AnonymousTest < ActiveSupport::TestCase
self.class.send(:remove_const, :C)
self.class.send(:remove_const, :M)
- assert !c.reachable?
- assert !m.reachable?
+ assert_deprecated do
+ assert !c.reachable?
+ assert !m.reachable?
+ end
end
test "a named class or module whose constants store different objects are not reachable" do
@@ -33,9 +41,11 @@ class AnonymousTest < ActiveSupport::TestCase
eval "class C; end"
eval "module M; end"
- assert C.reachable?
- assert M.reachable?
- assert !c.reachable?
- assert !m.reachable?
+ assert_deprecated do
+ assert C.reachable?
+ assert M.reachable?
+ assert !c.reachable?
+ assert !m.reachable?
+ end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/core_ext/module/remove_method_test.rb b/activesupport/test/core_ext/module/remove_method_test.rb
index 0d684dc70e..8493be8d08 100644
--- a/activesupport/test/core_ext/module/remove_method_test.rb
+++ b/activesupport/test/core_ext/module/remove_method_test.rb
@@ -1,51 +1,52 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/remove_method'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/remove_method"
module RemoveMethodTests
class A
def do_something
- return 1
+ 1
end
def do_something_protected
- return 1
+ 1
end
protected :do_something_protected
def do_something_private
- return 1
+ 1
end
private :do_something_private
class << self
def do_something_else
- return 2
+ 2
end
end
end
end
class RemoveMethodTest < ActiveSupport::TestCase
-
def test_remove_method_from_an_object
- RemoveMethodTests::A.class_eval{
- self.remove_possible_method(:do_something)
+ RemoveMethodTests::A.class_eval {
+ remove_possible_method(:do_something)
}
assert !RemoveMethodTests::A.new.respond_to?(:do_something)
end
def test_remove_singleton_method_from_an_object
- RemoveMethodTests::A.class_eval{
- self.remove_possible_singleton_method(:do_something_else)
+ RemoveMethodTests::A.class_eval {
+ remove_possible_singleton_method(:do_something_else)
}
assert !RemoveMethodTests::A.respond_to?(:do_something_else)
end
def test_redefine_method_in_an_object
- RemoveMethodTests::A.class_eval{
- self.redefine_method(:do_something) { return 100 }
- self.redefine_method(:do_something_protected) { return 100 }
- self.redefine_method(:do_something_private) { return 100 }
+ RemoveMethodTests::A.class_eval {
+ redefine_method(:do_something) { return 100 }
+ redefine_method(:do_something_protected) { return 100 }
+ redefine_method(:do_something_private) { return 100 }
}
assert_equal 100, RemoveMethodTests::A.new.do_something
assert_equal 100, RemoveMethodTests::A.new.send(:do_something_protected)
@@ -55,5 +56,4 @@ class RemoveMethodTest < ActiveSupport::TestCase
assert RemoveMethodTests::A.protected_method_defined? :do_something_protected
assert RemoveMethodTests::A.private_method_defined? :do_something_private
end
-
end
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index ae4aed0554..e918823074 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -1,74 +1,63 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module'
+# frozen_string_literal: true
-module One
- Constant1 = "Hello World"
- Constant2 = "What's up?"
-end
-
-class Ab
- include One
- Constant1 = "Hello World" # Will have different object id than One::Constant1
- Constant3 = "Goodbye World"
-end
-
-module Yz
- module Zy
- class Cd
- include One
- end
- end
-end
+require "abstract_unit"
+require "active_support/core_ext/module"
Somewhere = Struct.new(:street, :city) do
attr_accessor :name
end
-class Someone < Struct.new(:name, :place)
- delegate :street, :city, :to_f, :to => :place
- delegate :name=, :to => :place, :prefix => true
- delegate :upcase, :to => "place.city"
- delegate :table_name, :to => :class
- delegate :table_name, :to => :class, :prefix => true
+Someone = Struct.new(:name, :place) do
+ delegate :street, :city, :to_f, to: :place
+ delegate :name=, to: :place, prefix: true
+ delegate :upcase, to: "place.city"
+ delegate :table_name, to: :class
+ delegate :table_name, to: :class, prefix: true
def self.table_name
- 'some_table'
+ "some_table"
end
- FAILED_DELEGATE_LINE = __LINE__ + 1
- delegate :foo, :to => :place
+ self::FAILED_DELEGATE_LINE = __LINE__ + 1
+ delegate :foo, to: :place
- FAILED_DELEGATE_LINE_2 = __LINE__ + 1
- delegate :bar, :to => :place, :allow_nil => true
+ self::FAILED_DELEGATE_LINE_2 = __LINE__ + 1
+ delegate :bar, to: :place, allow_nil: true
+
+ private
+
+ def private_name
+ "Private"
+ end
end
-Invoice = Struct.new(:client) do
- delegate :street, :city, :name, :to => :client, :prefix => true
- delegate :street, :city, :name, :to => :client, :prefix => :customer
+Invoice = Struct.new(:client) do
+ delegate :street, :city, :name, to: :client, prefix: true
+ delegate :street, :city, :name, to: :client, prefix: :customer
end
-Project = Struct.new(:description, :person) do
- delegate :name, :to => :person, :allow_nil => true
- delegate :to_f, :to => :description, :allow_nil => true
+Project = Struct.new(:description, :person) do
+ delegate :name, to: :person, allow_nil: true
+ delegate :to_f, to: :description, allow_nil: true
end
Developer = Struct.new(:client) do
- delegate :name, :to => :client, :prefix => nil
+ delegate :name, to: :client, prefix: nil
end
Event = Struct.new(:case) do
- delegate :foo, :to => :case
+ delegate :foo, to: :case
end
Tester = Struct.new(:client) do
- delegate :name, :to => :client, :prefix => false
+ delegate :name, to: :client, prefix: false
def foo; 1; end
end
Product = Struct.new(:name) do
- delegate :name, :to => :manufacturer, :prefix => true
- delegate :name, :to => :type, :prefix => true
+ delegate :name, to: :manufacturer, prefix: true
+ delegate :name, to: :type, prefix: true
def manufacturer
@manufacturer ||= begin
@@ -83,6 +72,36 @@ Product = Struct.new(:name) do
end
end
+module ExtraMissing
+ def method_missing(sym, *args)
+ if sym == :extra_missing
+ 42
+ else
+ super
+ end
+ end
+
+ def respond_to_missing?(sym, priv = false)
+ sym == :extra_missing || super
+ end
+end
+
+DecoratedTester = Struct.new(:client) do
+ include ExtraMissing
+
+ delegate_missing_to :client
+end
+
+class DecoratedReserved
+ delegate_missing_to :case
+
+ attr_reader :case
+
+ def initialize(kase)
+ @case = kase
+ end
+end
+
class Block
def hello?
true
@@ -94,15 +113,15 @@ HasBlock = Struct.new(:block) do
end
class ParameterSet
- delegate :[], :[]=, :to => :@params
+ delegate :[], :[]=, to: :@params
def initialize
- @params = {:foo => "bar"}
+ @params = { foo: "bar" }
end
end
class Name
- delegate :upcase, :to => :@full_name
+ delegate :upcase, to: :@full_name
def initialize(first, last)
@full_name = "#{first} #{last}"
@@ -112,8 +131,8 @@ end
class SideEffect
attr_reader :ints
- delegate :to_i, :to => :shift, :allow_nil => true
- delegate :to_s, :to => :shift
+ delegate :to_i, to: :shift, allow_nil: true
+ delegate :to_s, to: :shift
def initialize
@ints = [1, 2, 3]
@@ -160,8 +179,8 @@ class ModuleTest < ActiveSupport::TestCase
end
def test_delegation_to_class_method
- assert_equal 'some_table', @david.table_name
- assert_equal 'some_table', @david.class_table_name
+ assert_equal "some_table", @david.table_name
+ assert_equal "some_table", @david.class_table_name
end
def test_missing_delegation_target
@@ -169,27 +188,42 @@ class ModuleTest < ActiveSupport::TestCase
Name.send :delegate, :nowhere
end
assert_raise(ArgumentError) do
- Name.send :delegate, :noplace, :tos => :hollywood
+ Name.send :delegate, :noplace, tos: :hollywood
+ end
+ end
+
+ def test_delegation_target_when_prefix_is_true
+ assert_nothing_raised do
+ Name.send :delegate, :go, to: :you, prefix: true
+ end
+ assert_nothing_raised do
+ Name.send :delegate, :go, to: :_you, prefix: true
+ end
+ assert_raise(ArgumentError) do
+ Name.send :delegate, :go, to: :You, prefix: true
+ end
+ assert_raise(ArgumentError) do
+ Name.send :delegate, :go, to: :@you, prefix: true
end
end
def test_delegation_prefix
invoice = Invoice.new(@david)
- assert_equal invoice.client_name, "David"
- assert_equal invoice.client_street, "Paulina"
- assert_equal invoice.client_city, "Chicago"
+ assert_equal "David", invoice.client_name
+ assert_equal "Paulina", invoice.client_street
+ assert_equal "Chicago", invoice.client_city
end
def test_delegation_custom_prefix
invoice = Invoice.new(@david)
- assert_equal invoice.customer_name, "David"
- assert_equal invoice.customer_street, "Paulina"
- assert_equal invoice.customer_city, "Chicago"
+ assert_equal "David", invoice.customer_name
+ assert_equal "Paulina", invoice.customer_street
+ assert_equal "Chicago", invoice.customer_city
end
def test_delegation_prefix_with_nil_or_false
- assert_equal Developer.new(@david).name, "David"
- assert_equal Tester.new(@david).name, "David"
+ assert_equal "David", Developer.new(@david).name
+ assert_equal "David", Tester.new(@david).name
end
def test_delegation_prefix_with_instance_variable
@@ -198,14 +232,14 @@ class ModuleTest < ActiveSupport::TestCase
def initialize(client)
@client = client
end
- delegate :name, :address, :to => :@client, :prefix => true
+ delegate :name, :address, to: :@client, prefix: true
end
end
end
def test_delegation_with_allow_nil
rails = Project.new("Rails", Someone.new("David"))
- assert_equal rails.name, "David"
+ assert_equal "David", rails.name
end
def test_delegation_with_allow_nil_and_nil_value
@@ -226,7 +260,7 @@ class ModuleTest < ActiveSupport::TestCase
def test_delegation_with_allow_nil_and_nil_value_and_prefix
Project.class_eval do
- delegate :name, :to => :person, :allow_nil => true, :prefix => true
+ delegate :name, to: :person, allow_nil: true, prefix: true
end
rails = Project.new("Rails")
assert_nil rails.person_name
@@ -255,7 +289,7 @@ class ModuleTest < ActiveSupport::TestCase
assert_nothing_raised do
Class.new(parent) do
class << self
- delegate :parent_method, :to => :superclass
+ delegate :parent_method, to: :superclass
end
end
end
@@ -277,7 +311,7 @@ class ModuleTest < ActiveSupport::TestCase
rescue NoMethodError => e
file_and_line = "#{__FILE__}:#{Someone::FAILED_DELEGATE_LINE}"
# We can't simply check the first line of the backtrace, because JRuby reports the call to __send__ in the backtrace.
- assert e.backtrace.any?{|a| a.include?(file_and_line)},
+ assert e.backtrace.any? { |a| a.include?(file_and_line) },
"[#{e.backtrace.inspect}] did not include [#{file_and_line}]"
end
@@ -287,7 +321,7 @@ class ModuleTest < ActiveSupport::TestCase
rescue NoMethodError => e
file_and_line = "#{__FILE__}:#{Someone::FAILED_DELEGATE_LINE_2}"
# We can't simply check the first line of the backtrace, because JRuby reports the call to __send__ in the backtrace.
- assert e.backtrace.any?{|a| a.include?(file_and_line)},
+ assert e.backtrace.any? { |a| a.include?(file_and_line) },
"[#{e.backtrace.inspect}] did not include [#{file_and_line}]"
end
@@ -297,12 +331,12 @@ class ModuleTest < ActiveSupport::TestCase
assert_equal 1, se.to_i
assert_equal [2, 3], se.ints
- assert_equal '2', se.to_s
+ assert_equal "2", se.to_s
assert_equal [3], se.ints
end
def test_delegation_doesnt_mask_nested_no_method_error_on_nil_receiver
- product = Product.new('Widget')
+ product = Product.new("Widget")
# Nested NoMethodError is a different name from the delegation
assert_raise(NoMethodError) { product.manufacturer_name }
@@ -316,245 +350,94 @@ class ModuleTest < ActiveSupport::TestCase
assert has_block.hello?
end
- def test_parent
- assert_equal Yz::Zy, Yz::Zy::Cd.parent
- assert_equal Yz, Yz::Zy.parent
- assert_equal Object, Yz.parent
+ def test_delegate_missing_to_with_method
+ assert_equal "David", DecoratedTester.new(@david).name
end
- def test_parents
- assert_equal [Yz::Zy, Yz, Object], Yz::Zy::Cd.parents
- assert_equal [Yz, Object], Yz::Zy.parents
+ def test_delegate_missing_to_with_reserved_methods
+ assert_equal "David", DecoratedReserved.new(@david).name
end
- def test_local_constants
- ActiveSupport::Deprecation.silence do
- assert_equal %w(Constant1 Constant3), Ab.local_constants.sort.map(&:to_s)
+ def test_delegate_missing_to_does_not_delegate_to_private_methods
+ e = assert_raises(NoMethodError) do
+ DecoratedReserved.new(@david).private_name
end
- end
- def test_local_constants_is_deprecated
- assert_deprecated { Ab.local_constants.sort.map(&:to_s) }
+ assert_match(/undefined method `private_name' for/, e.message)
end
-end
-module BarMethodAliaser
- def self.included(foo_class)
- foo_class.class_eval do
- include BarMethods
- alias_method_chain :bar, :baz
+ def test_delegate_missing_to_does_not_delegate_to_fake_methods
+ e = assert_raises(NoMethodError) do
+ DecoratedReserved.new(@david).my_fake_method
end
- end
-end
-
-module BarMethods
- def bar_with_baz
- bar_without_baz << '_with_baz'
- end
-
- def quux_with_baz!
- quux_without_baz! << '_with_baz'
- end
-
- def quux_with_baz?
- false
- end
-
- def quux_with_baz=(v)
- send(:quux_without_baz=, v) << '_with_baz'
- end
-
- def duck_with_orange
- duck_without_orange << '_with_orange'
- end
-end
-
-class MethodAliasingTest < ActiveSupport::TestCase
- def setup
- Object.const_set :FooClassWithBarMethod, Class.new { def bar() 'bar' end }
- @instance = FooClassWithBarMethod.new
- end
- def teardown
- Object.instance_eval { remove_const :FooClassWithBarMethod }
+ assert_match(/undefined method `my_fake_method' for/, e.message)
end
- def test_alias_method_chain_deprecated
- assert_deprecated(/alias_method_chain/) do
- Module.new do
- def base
- end
-
- def base_with_deprecated
- end
-
- alias_method_chain :base, :deprecated
- end
+ def test_delegate_missing_to_raises_delegation_error_if_target_nil
+ e = assert_raises(Module::DelegationError) do
+ DecoratedTester.new(nil).name
end
- end
-
- def test_alias_method_chain
- assert_deprecated(/alias_method_chain/) do
- assert @instance.respond_to?(:bar)
- feature_aliases = [:bar_with_baz, :bar_without_baz]
-
- feature_aliases.each do |method|
- assert !@instance.respond_to?(method)
- end
-
- assert_equal 'bar', @instance.bar
-
- FooClassWithBarMethod.class_eval { include BarMethodAliaser }
-
- feature_aliases.each do |method|
- assert_respond_to @instance, method
- end
- assert_equal 'bar_with_baz', @instance.bar
- assert_equal 'bar', @instance.bar_without_baz
- end
+ assert_equal "name delegated to client, but client is nil", e.message
end
- def test_alias_method_chain_with_punctuation_method
- assert_deprecated(/alias_method_chain/) do
- FooClassWithBarMethod.class_eval do
- def quux!; 'quux' end
- end
+ def test_delegate_missing_to_affects_respond_to
+ assert DecoratedTester.new(@david).respond_to?(:name)
+ assert_not DecoratedTester.new(@david).respond_to?(:private_name)
+ assert_not DecoratedTester.new(@david).respond_to?(:my_fake_method)
- assert !@instance.respond_to?(:quux_with_baz!)
- FooClassWithBarMethod.class_eval do
- include BarMethodAliaser
- alias_method_chain :quux!, :baz
- end
- assert_respond_to @instance, :quux_with_baz!
-
- assert_equal 'quux_with_baz', @instance.quux!
- assert_equal 'quux', @instance.quux_without_baz!
- end
+ assert DecoratedTester.new(@david).respond_to?(:name, true)
+ assert_not DecoratedTester.new(@david).respond_to?(:private_name, true)
+ assert_not DecoratedTester.new(@david).respond_to?(:my_fake_method, true)
end
- def test_alias_method_chain_with_same_names_between_predicates_and_bang_methods
- assert_deprecated(/alias_method_chain/) do
- FooClassWithBarMethod.class_eval do
- def quux!; 'quux!' end
- def quux?; true end
- def quux=(v); 'quux=' end
- end
+ def test_delegate_missing_to_respects_superclass_missing
+ assert_equal 42, DecoratedTester.new(@david).extra_missing
- assert !@instance.respond_to?(:quux_with_baz!)
- assert !@instance.respond_to?(:quux_with_baz?)
- assert !@instance.respond_to?(:quux_with_baz=)
-
- FooClassWithBarMethod.class_eval { include BarMethodAliaser }
- assert_respond_to @instance, :quux_with_baz!
- assert_respond_to @instance, :quux_with_baz?
- assert_respond_to @instance, :quux_with_baz=
-
-
- FooClassWithBarMethod.alias_method_chain :quux!, :baz
- assert_equal 'quux!_with_baz', @instance.quux!
- assert_equal 'quux!', @instance.quux_without_baz!
-
- FooClassWithBarMethod.alias_method_chain :quux?, :baz
- assert_equal false, @instance.quux?
- assert_equal true, @instance.quux_without_baz?
-
- FooClassWithBarMethod.alias_method_chain :quux=, :baz
- assert_equal 'quux=_with_baz', @instance.send(:quux=, 1234)
- assert_equal 'quux=', @instance.send(:quux_without_baz=, 1234)
- end
+ assert_respond_to DecoratedTester.new(@david), :extra_missing
end
- def test_alias_method_chain_with_feature_punctuation
- assert_deprecated(/alias_method_chain/) do
- FooClassWithBarMethod.class_eval do
- def quux; 'quux' end
- def quux?; 'quux?' end
- include BarMethodAliaser
- alias_method_chain :quux, :baz!
- end
-
- assert_nothing_raised do
- assert_equal 'quux_with_baz', @instance.quux_with_baz!
- end
-
- assert_raise(NameError) do
- FooClassWithBarMethod.alias_method_chain :quux?, :baz!
- end
- end
+ def test_delegate_with_case
+ event = Event.new(Tester.new)
+ assert_equal 1, event.foo
end
- def test_alias_method_chain_yields_target_and_punctuation
- assert_deprecated(/alias_method_chain/) do
- args = nil
-
- FooClassWithBarMethod.class_eval do
- def quux?; end
- include BarMethods
-
- FooClassWithBarMethod.alias_method_chain :quux?, :baz do |target, punctuation|
- args = [target, punctuation]
- end
+ def test_private_delegate
+ location = Class.new do
+ def initialize(place)
+ @place = place
end
- assert_not_nil args
- assert_equal 'quux', args[0]
- assert_equal '?', args[1]
+ private(*delegate(:street, :city, to: :@place))
end
- end
- def test_alias_method_chain_preserves_private_method_status
- assert_deprecated(/alias_method_chain/) do
- FooClassWithBarMethod.class_eval do
- def duck; 'duck' end
- include BarMethodAliaser
- private :duck
- alias_method_chain :duck, :orange
- end
+ place = location.new(Somewhere.new("Such street", "Sad city"))
- assert_raise NoMethodError do
- @instance.duck
- end
+ assert_not place.respond_to?(:street)
+ assert_not place.respond_to?(:city)
- assert_equal 'duck_with_orange', @instance.instance_eval { duck }
- assert FooClassWithBarMethod.private_method_defined?(:duck)
- end
+ assert place.respond_to?(:street, true) # Asking for private method
+ assert place.respond_to?(:city, true)
end
- def test_alias_method_chain_preserves_protected_method_status
- assert_deprecated(/alias_method_chain/) do
- FooClassWithBarMethod.class_eval do
- def duck; 'duck' end
- include BarMethodAliaser
- protected :duck
- alias_method_chain :duck, :orange
+ def test_private_delegate_prefixed
+ location = Class.new do
+ def initialize(place)
+ @place = place
end
- assert_raise NoMethodError do
- @instance.duck
- end
-
- assert_equal 'duck_with_orange', @instance.instance_eval { duck }
- assert FooClassWithBarMethod.protected_method_defined?(:duck)
+ private(*delegate(:street, :city, to: :@place, prefix: :the))
end
- end
- def test_alias_method_chain_preserves_public_method_status
- assert_deprecated(/alias_method_chain/) do
- FooClassWithBarMethod.class_eval do
- def duck; 'duck' end
- include BarMethodAliaser
- public :duck
- alias_method_chain :duck, :orange
- end
+ place = location.new(Somewhere.new("Such street", "Sad city"))
- assert_equal 'duck_with_orange', @instance.duck
- assert FooClassWithBarMethod.public_method_defined?(:duck)
- end
- end
+ assert_not place.respond_to?(:street)
+ assert_not place.respond_to?(:city)
- def test_delegate_with_case
- event = Event.new(Tester.new)
- assert_equal 1, event.foo
+ assert_not place.respond_to?(:the_street)
+ assert place.respond_to?(:the_street, true)
+ assert_not place.respond_to?(:the_city)
+ assert place.respond_to?(:the_city, true)
end
end
diff --git a/activesupport/test/core_ext/name_error_test.rb b/activesupport/test/core_ext/name_error_test.rb
index 7525f80cf0..d1dace3713 100644
--- a/activesupport/test/core_ext/name_error_test.rb
+++ b/activesupport/test/core_ext/name_error_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/name_error'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/name_error"
class NameErrorTest < ActiveSupport::TestCase
def test_name_error_should_set_missing_name
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
index 5654aeb4f8..4b9073da54 100644
--- a/activesupport/test/core_ext/numeric_ext_test.rb
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -1,18 +1,20 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'active_support/core_ext/numeric'
-require 'active_support/core_ext/integer'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "active_support/core_ext/numeric"
+require "active_support/core_ext/integer"
class NumericExtTimeAndDateTimeTest < ActiveSupport::TestCase
def setup
- @now = Time.local(2005,2,10,15,30,45)
- @dtnow = DateTime.civil(2005,2,10,15,30,45)
+ @now = Time.local(2005, 2, 10, 15, 30, 45)
+ @dtnow = DateTime.civil(2005, 2, 10, 15, 30, 45)
@seconds = {
1.minute => 60,
10.minutes => 600,
1.hour + 15.minutes => 4500,
2.days + 4.hours + 30.minutes => 189000,
- 5.years + 1.month + 1.fortnight => 161589600
+ 5.years + 1.month + 1.fortnight => 161624106
}
end
@@ -23,53 +25,53 @@ class NumericExtTimeAndDateTimeTest < ActiveSupport::TestCase
end
def test_irregular_durations
- assert_equal @now.advance(:days => 3000), 3000.days.since(@now)
- assert_equal @now.advance(:months => 1), 1.month.since(@now)
- assert_equal @now.advance(:months => -1), 1.month.until(@now)
- assert_equal @now.advance(:years => 20), 20.years.since(@now)
- assert_equal @dtnow.advance(:days => 3000), 3000.days.since(@dtnow)
- assert_equal @dtnow.advance(:months => 1), 1.month.since(@dtnow)
- assert_equal @dtnow.advance(:months => -1), 1.month.until(@dtnow)
- assert_equal @dtnow.advance(:years => 20), 20.years.since(@dtnow)
+ assert_equal @now.advance(days: 3000), 3000.days.since(@now)
+ assert_equal @now.advance(months: 1), 1.month.since(@now)
+ assert_equal @now.advance(months: -1), 1.month.until(@now)
+ assert_equal @now.advance(years: 20), 20.years.since(@now)
+ assert_equal @dtnow.advance(days: 3000), 3000.days.since(@dtnow)
+ assert_equal @dtnow.advance(months: 1), 1.month.since(@dtnow)
+ assert_equal @dtnow.advance(months: -1), 1.month.until(@dtnow)
+ assert_equal @dtnow.advance(years: 20), 20.years.since(@dtnow)
end
def test_duration_addition
- assert_equal @now.advance(:days => 1).advance(:months => 1), (1.day + 1.month).since(@now)
- assert_equal @now.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@now)
- assert_equal @now.advance(:years => 2), (4.years - 2.years).since(@now)
- assert_equal @dtnow.advance(:days => 1).advance(:months => 1), (1.day + 1.month).since(@dtnow)
- assert_equal @dtnow.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@dtnow)
- assert_equal @dtnow.advance(:years => 2), (4.years - 2.years).since(@dtnow)
+ assert_equal @now.advance(days: 1).advance(months: 1), (1.day + 1.month).since(@now)
+ assert_equal @now.advance(days: 7), (1.week + 5.seconds - 5.seconds).since(@now)
+ assert_equal @now.advance(years: 2), (4.years - 2.years).since(@now)
+ assert_equal @dtnow.advance(days: 1).advance(months: 1), (1.day + 1.month).since(@dtnow)
+ assert_equal @dtnow.advance(days: 7), (1.week + 5.seconds - 5.seconds).since(@dtnow)
+ assert_equal @dtnow.advance(years: 2), (4.years - 2.years).since(@dtnow)
end
def test_time_plus_duration
assert_equal @now + 8, @now + 8.seconds
assert_equal @now + 22.9, @now + 22.9.seconds
- assert_equal @now.advance(:days => 15), @now + 15.days
- assert_equal @now.advance(:months => 1), @now + 1.month
+ assert_equal @now.advance(days: 15), @now + 15.days
+ assert_equal @now.advance(months: 1), @now + 1.month
assert_equal @dtnow.since(8), @dtnow + 8.seconds
assert_equal @dtnow.since(22.9), @dtnow + 22.9.seconds
- assert_equal @dtnow.advance(:days => 15), @dtnow + 15.days
- assert_equal @dtnow.advance(:months => 1), @dtnow + 1.month
+ assert_equal @dtnow.advance(days: 15), @dtnow + 15.days
+ assert_equal @dtnow.advance(months: 1), @dtnow + 1.month
end
def test_chaining_duration_operations
- assert_equal @now.advance(:days => 2).advance(:months => -3), @now + 2.days - 3.months
- assert_equal @now.advance(:days => 1).advance(:months => 2), @now + 1.day + 2.months
- assert_equal @dtnow.advance(:days => 2).advance(:months => -3), @dtnow + 2.days - 3.months
- assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months
+ assert_equal @now.advance(days: 2).advance(months: -3), @now + 2.days - 3.months
+ assert_equal @now.advance(days: 1).advance(months: 2), @now + 1.day + 2.months
+ assert_equal @dtnow.advance(days: 2).advance(months: -3), @dtnow + 2.days - 3.months
+ assert_equal @dtnow.advance(days: 1).advance(months: 2), @dtnow + 1.day + 2.months
end
def test_duration_after_conversion_is_no_longer_accurate
- assert_equal 30.days.to_i.seconds.since(@now), 1.month.to_i.seconds.since(@now)
- assert_equal 365.25.days.to_f.seconds.since(@now), 1.year.to_f.seconds.since(@now)
- assert_equal 30.days.to_i.seconds.since(@dtnow), 1.month.to_i.seconds.since(@dtnow)
- assert_equal 365.25.days.to_f.seconds.since(@dtnow), 1.year.to_f.seconds.since(@dtnow)
+ assert_equal (1.year / 12).to_i.seconds.since(@now), 1.month.to_i.seconds.since(@now)
+ assert_equal 365.2425.days.to_f.seconds.since(@now), 1.year.to_f.seconds.since(@now)
+ assert_equal (1.year / 12).to_i.seconds.since(@dtnow), 1.month.to_i.seconds.since(@dtnow)
+ assert_equal 365.2425.days.to_f.seconds.since(@dtnow), 1.year.to_f.seconds.since(@dtnow)
end
def test_add_one_year_to_leap_day
- assert_equal Time.utc(2005,2,28,15,15,10), Time.utc(2004,2,29,15,15,10) + 1.year
- assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10) + 1.year
+ assert_equal Time.utc(2005, 2, 28, 15, 15, 10), Time.utc(2004, 2, 29, 15, 15, 10) + 1.year
+ assert_equal DateTime.civil(2005, 2, 28, 15, 15, 10), DateTime.civil(2004, 2, 29, 15, 15, 10) + 1.year
end
end
@@ -83,16 +85,16 @@ class NumericExtDateTest < ActiveSupport::TestCase
assert_equal @today >> 1, @today + 1.month
assert_equal @today.to_time.since(1), @today + 1.second
assert_equal @today.to_time.since(60), @today + 1.minute
- assert_equal @today.to_time.since(60*60), @today + 1.hour
+ assert_equal @today.to_time.since(60 * 60), @today + 1.hour
end
def test_chaining_duration_operations
- assert_equal @today.advance(:days => 2).advance(:months => -3), @today + 2.days - 3.months
- assert_equal @today.advance(:days => 1).advance(:months => 2), @today + 1.day + 2.months
+ assert_equal @today.advance(days: 2).advance(months: -3), @today + 2.days - 3.months
+ assert_equal @today.advance(days: 1).advance(months: 2), @today + 1.day + 2.months
end
def test_add_one_year_to_leap_day
- assert_equal Date.new(2005,2,28), Date.new(2004,2,29) + 1.year
+ assert_equal Date.new(2005, 2, 28), Date.new(2004, 2, 29) + 1.year
end
end
@@ -102,12 +104,12 @@ class NumericExtSizeTest < ActiveSupport::TestCase
assert_equal 1024.kilobytes, 1.megabyte
assert_equal 3584.0.kilobytes, 3.5.megabytes
assert_equal 3584.0.megabytes, 3.5.gigabytes
- assert_equal 1.kilobyte ** 4, 1.terabyte
+ assert_equal 1.kilobyte**4, 1.terabyte
assert_equal 1024.kilobytes + 2.megabytes, 3.megabytes
assert_equal 2.gigabytes / 4, 512.megabytes
assert_equal 256.megabytes * 20 + 5.gigabytes, 10.gigabytes
- assert_equal 1.kilobyte ** 5, 1.petabyte
- assert_equal 1.kilobyte ** 6, 1.exabyte
+ assert_equal 1.kilobyte**5, 1.petabyte
+ assert_equal 1.kilobyte**6, 1.exabyte
end
def test_units_as_bytes_independently
@@ -154,53 +156,52 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
def test_to_s__phone
assert_equal("555-1234", 5551234.to_s(:phone))
assert_equal("800-555-1212", 8005551212.to_s(:phone))
- assert_equal("(800) 555-1212", 8005551212.to_s(:phone, :area_code => true))
- assert_equal("800 555 1212", 8005551212.to_s(:phone, :delimiter => " "))
- assert_equal("(800) 555-1212 x 123", 8005551212.to_s(:phone, :area_code => true, :extension => 123))
- assert_equal("800-555-1212", 8005551212.to_s(:phone, :extension => " "))
- assert_equal("555.1212", 5551212.to_s(:phone, :delimiter => '.'))
- assert_equal("+1-800-555-1212", 8005551212.to_s(:phone, :country_code => 1))
- assert_equal("+18005551212", 8005551212.to_s(:phone, :country_code => 1, :delimiter => ''))
+ assert_equal("(800) 555-1212", 8005551212.to_s(:phone, area_code: true))
+ assert_equal("800 555 1212", 8005551212.to_s(:phone, delimiter: " "))
+ assert_equal("(800) 555-1212 x 123", 8005551212.to_s(:phone, area_code: true, extension: 123))
+ assert_equal("800-555-1212", 8005551212.to_s(:phone, extension: " "))
+ assert_equal("555.1212", 5551212.to_s(:phone, delimiter: "."))
+ assert_equal("+1-800-555-1212", 8005551212.to_s(:phone, country_code: 1))
+ assert_equal("+18005551212", 8005551212.to_s(:phone, country_code: 1, delimiter: ""))
assert_equal("22-555-1212", 225551212.to_s(:phone))
- assert_equal("+45-22-555-1212", 225551212.to_s(:phone, :country_code => 45))
+ assert_equal("+45-22-555-1212", 225551212.to_s(:phone, country_code: 45))
end
def test_to_s__currency
assert_equal("$1,234,567,890.50", 1234567890.50.to_s(:currency))
assert_equal("$1,234,567,890.51", 1234567890.506.to_s(:currency))
assert_equal("-$1,234,567,890.50", -1234567890.50.to_s(:currency))
- assert_equal("-$ 1,234,567,890.50", -1234567890.50.to_s(:currency, :format => "%u %n"))
- assert_equal("($1,234,567,890.50)", -1234567890.50.to_s(:currency, :negative_format => "(%u%n)"))
- assert_equal("$1,234,567,892", 1234567891.50.to_s(:currency, :precision => 0))
- assert_equal("$1,234,567,890.5", 1234567890.50.to_s(:currency, :precision => 1))
- assert_equal("&pound;1234567890,50", 1234567890.50.to_s(:currency, :unit => "&pound;", :separator => ",", :delimiter => ""))
+ assert_equal("-$ 1,234,567,890.50", -1234567890.50.to_s(:currency, format: "%u %n"))
+ assert_equal("($1,234,567,890.50)", -1234567890.50.to_s(:currency, negative_format: "(%u%n)"))
+ assert_equal("$1,234,567,892", 1234567891.50.to_s(:currency, precision: 0))
+ assert_equal("$1,234,567,890.5", 1234567890.50.to_s(:currency, precision: 1))
+ assert_equal("&pound;1234567890,50", 1234567890.50.to_s(:currency, unit: "&pound;", separator: ",", delimiter: ""))
end
-
def test_to_s__rounded
assert_equal("-111.235", -111.2346.to_s(:rounded))
assert_equal("111.235", 111.2346.to_s(:rounded))
- assert_equal("31.83", 31.825.to_s(:rounded, :precision => 2))
- assert_equal("111.23", 111.2346.to_s(:rounded, :precision => 2))
- assert_equal("111.00", 111.to_s(:rounded, :precision => 2))
- assert_equal("3268", (32.6751 * 100.00).to_s(:rounded, :precision => 0))
- assert_equal("112", 111.50.to_s(:rounded, :precision => 0))
- assert_equal("1234567892", 1234567891.50.to_s(:rounded, :precision => 0))
- assert_equal("0", 0.to_s(:rounded, :precision => 0))
- assert_equal("0.00100", 0.001.to_s(:rounded, :precision => 5))
- assert_equal("0.001", 0.00111.to_s(:rounded, :precision => 3))
- assert_equal("10.00", 9.995.to_s(:rounded, :precision => 2))
- assert_equal("11.00", 10.995.to_s(:rounded, :precision => 2))
- assert_equal("0.00", -0.001.to_s(:rounded, :precision => 2))
+ assert_equal("31.83", 31.825.to_s(:rounded, precision: 2))
+ assert_equal("111.23", 111.2346.to_s(:rounded, precision: 2))
+ assert_equal("111.00", 111.to_s(:rounded, precision: 2))
+ assert_equal("3268", (32.6751 * 100.00).to_s(:rounded, precision: 0))
+ assert_equal("112", 111.50.to_s(:rounded, precision: 0))
+ assert_equal("1234567892", 1234567891.50.to_s(:rounded, precision: 0))
+ assert_equal("0", 0.to_s(:rounded, precision: 0))
+ assert_equal("0.00100", 0.001.to_s(:rounded, precision: 5))
+ assert_equal("0.001", 0.00111.to_s(:rounded, precision: 3))
+ assert_equal("10.00", 9.995.to_s(:rounded, precision: 2))
+ assert_equal("11.00", 10.995.to_s(:rounded, precision: 2))
+ assert_equal("0.00", -0.001.to_s(:rounded, precision: 2))
end
def test_to_s__percentage
assert_equal("100.000%", 100.to_s(:percentage))
- assert_equal("100%", 100.to_s(:percentage, :precision => 0))
- assert_equal("302.06%", 302.0574.to_s(:percentage, :precision => 2))
- assert_equal("123.4%", 123.400.to_s(:percentage, :precision => 3, :strip_insignificant_zeros => true))
- assert_equal("1.000,000%", 1000.to_s(:percentage, :delimiter => '.', :separator => ','))
- assert_equal("1000.000 %", 1000.to_s(:percentage, :format => "%n %"))
+ assert_equal("100%", 100.to_s(:percentage, precision: 0))
+ assert_equal("302.06%", 302.0574.to_s(:percentage, precision: 2))
+ assert_equal("123.4%", 123.400.to_s(:percentage, precision: 3, strip_insignificant_zeros: true))
+ assert_equal("1.000,000%", 1000.to_s(:percentage, delimiter: ".", separator: ","))
+ assert_equal("1000.000 %", 1000.to_s(:percentage, format: "%n %"))
end
def test_to_s__delimited
@@ -216,214 +217,189 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
end
def test_to_s__delimited__with_options_hash
- assert_equal '12 345 678', 12345678.to_s(:delimited, :delimiter => ' ')
- assert_equal '12,345,678-05', 12345678.05.to_s(:delimited, :separator => '-')
- assert_equal '12.345.678,05', 12345678.05.to_s(:delimited, :separator => ',', :delimiter => '.')
- assert_equal '12.345.678,05', 12345678.05.to_s(:delimited, :delimiter => '.', :separator => ',')
+ assert_equal "12 345 678", 12345678.to_s(:delimited, delimiter: " ")
+ assert_equal "12,345,678-05", 12345678.05.to_s(:delimited, separator: "-")
+ assert_equal "12.345.678,05", 12345678.05.to_s(:delimited, separator: ",", delimiter: ".")
+ assert_equal "12.345.678,05", 12345678.05.to_s(:delimited, delimiter: ".", separator: ",")
end
-
def test_to_s__rounded_with_custom_delimiter_and_separator
- assert_equal '31,83', 31.825.to_s(:rounded, :precision => 2, :separator => ',')
- assert_equal '1.231,83', 1231.825.to_s(:rounded, :precision => 2, :separator => ',', :delimiter => '.')
+ assert_equal "31,83", 31.825.to_s(:rounded, precision: 2, separator: ",")
+ assert_equal "1.231,83", 1231.825.to_s(:rounded, precision: 2, separator: ",", delimiter: ".")
end
def test_to_s__rounded__with_significant_digits
- assert_equal "124000", 123987.to_s(:rounded, :precision => 3, :significant => true)
- assert_equal "120000000", 123987876.to_s(:rounded, :precision => 2, :significant => true )
- assert_equal "9775", 9775.to_s(:rounded, :precision => 4, :significant => true )
- assert_equal "5.4", 5.3923.to_s(:rounded, :precision => 2, :significant => true )
- assert_equal "5", 5.3923.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "1", 1.232.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "7", 7.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "1", 1.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "53", 52.7923.to_s(:rounded, :precision => 2, :significant => true )
- assert_equal "9775.00", 9775.to_s(:rounded, :precision => 6, :significant => true )
- assert_equal "5.392900", 5.3929.to_s(:rounded, :precision => 7, :significant => true )
- assert_equal "0.0", 0.to_s(:rounded, :precision => 2, :significant => true )
- assert_equal "0", 0.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "0.0001", 0.0001.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "0.000100", 0.0001.to_s(:rounded, :precision => 3, :significant => true )
- assert_equal "0.0001", 0.0001111.to_s(:rounded, :precision => 1, :significant => true )
- assert_equal "10.0", 9.995.to_s(:rounded, :precision => 3, :significant => true)
- assert_equal "9.99", 9.994.to_s(:rounded, :precision => 3, :significant => true)
- assert_equal "11.0", 10.995.to_s(:rounded, :precision => 3, :significant => true)
+ assert_equal "124000", 123987.to_s(:rounded, precision: 3, significant: true)
+ assert_equal "120000000", 123987876.to_s(:rounded, precision: 2, significant: true)
+ assert_equal "9775", 9775.to_s(:rounded, precision: 4, significant: true)
+ assert_equal "5.4", 5.3923.to_s(:rounded, precision: 2, significant: true)
+ assert_equal "5", 5.3923.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "1", 1.232.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "7", 7.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "1", 1.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "53", 52.7923.to_s(:rounded, precision: 2, significant: true)
+ assert_equal "9775.00", 9775.to_s(:rounded, precision: 6, significant: true)
+ assert_equal "5.392900", 5.3929.to_s(:rounded, precision: 7, significant: true)
+ assert_equal "0.0", 0.to_s(:rounded, precision: 2, significant: true)
+ assert_equal "0", 0.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "0.0001", 0.0001.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "0.000100", 0.0001.to_s(:rounded, precision: 3, significant: true)
+ assert_equal "0.0001", 0.0001111.to_s(:rounded, precision: 1, significant: true)
+ assert_equal "10.0", 9.995.to_s(:rounded, precision: 3, significant: true)
+ assert_equal "9.99", 9.994.to_s(:rounded, precision: 3, significant: true)
+ assert_equal "11.0", 10.995.to_s(:rounded, precision: 3, significant: true)
end
def test_to_s__rounded__with_strip_insignificant_zeros
- assert_equal "9775.43", 9775.43.to_s(:rounded, :precision => 4, :strip_insignificant_zeros => true )
- assert_equal "9775.2", 9775.2.to_s(:rounded, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
- assert_equal "0", 0.to_s(:rounded, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
+ assert_equal "9775.43", 9775.43.to_s(:rounded, precision: 4, strip_insignificant_zeros: true)
+ assert_equal "9775.2", 9775.2.to_s(:rounded, precision: 6, significant: true, strip_insignificant_zeros: true)
+ assert_equal "0", 0.to_s(:rounded, precision: 6, significant: true, strip_insignificant_zeros: true)
end
def test_to_s__rounded__with_significant_true_and_zero_precision
# Zero precision with significant is a mistake (would always return zero),
# so we treat it as if significant was false (increases backwards compatibility for number_to_human_size)
- assert_equal "124", 123.987.to_s(:rounded, :precision => 0, :significant => true)
- assert_equal "12", 12.to_s(:rounded, :precision => 0, :significant => true )
+ assert_equal "124", 123.987.to_s(:rounded, precision: 0, significant: true)
+ assert_equal "12", 12.to_s(:rounded, precision: 0, significant: true)
end
def test_to_s__human_size
- assert_equal '0 Bytes', 0.to_s(:human_size)
- assert_equal '1 Byte', 1.to_s(:human_size)
- assert_equal '3 Bytes', 3.14159265.to_s(:human_size)
- assert_equal '123 Bytes', 123.0.to_s(:human_size)
- assert_equal '123 Bytes', 123.to_s(:human_size)
- assert_equal '1.21 KB', 1234.to_s(:human_size)
- assert_equal '12.1 KB', 12345.to_s(:human_size)
- assert_equal '1.18 MB', 1234567.to_s(:human_size)
- assert_equal '1.15 GB', 1234567890.to_s(:human_size)
- assert_equal '1.12 TB', 1234567890123.to_s(:human_size)
- assert_equal '1.1 PB', 1234567890123456.to_s(:human_size)
- assert_equal '1.07 EB', 1234567890123456789.to_s(:human_size)
- assert_equal '1030 EB', exabytes(1026).to_s(:human_size)
- assert_equal '444 KB', kilobytes(444).to_s(:human_size)
- assert_equal '1020 MB', megabytes(1023).to_s(:human_size)
- assert_equal '3 TB', terabytes(3).to_s(:human_size)
- assert_equal '1.2 MB', 1234567.to_s(:human_size, :precision => 2)
- assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :precision => 4)
- assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 2)
- assert_equal '1.01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4)
- assert_equal '10 KB', kilobytes(10.000).to_s(:human_size, :precision => 4)
- assert_equal '1 Byte', 1.1.to_s(:human_size)
- assert_equal '10 Bytes', 10.to_s(:human_size)
- end
-
- def test_to_s__human_size_with_si_prefix
- assert_deprecated do
- assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :prefix => :si)
- assert_equal '123 Bytes', 123.0.to_s(:human_size, :prefix => :si)
- assert_equal '123 Bytes', 123.to_s(:human_size, :prefix => :si)
- assert_equal '1.23 KB', 1234.to_s(:human_size, :prefix => :si)
- assert_equal '12.3 KB', 12345.to_s(:human_size, :prefix => :si)
- assert_equal '1.23 MB', 1234567.to_s(:human_size, :prefix => :si)
- assert_equal '1.23 GB', 1234567890.to_s(:human_size, :prefix => :si)
- assert_equal '1.23 TB', 1234567890123.to_s(:human_size, :prefix => :si)
- assert_equal '1.23 PB', 1234567890123456.to_s(:human_size, :prefix => :si)
- assert_equal '1.23 EB', 1234567890123456789.to_s(:human_size, :prefix => :si)
- end
+ assert_equal "0 Bytes", 0.to_s(:human_size)
+ assert_equal "1 Byte", 1.to_s(:human_size)
+ assert_equal "3 Bytes", 3.14159265.to_s(:human_size)
+ assert_equal "123 Bytes", 123.0.to_s(:human_size)
+ assert_equal "123 Bytes", 123.to_s(:human_size)
+ assert_equal "1.21 KB", 1234.to_s(:human_size)
+ assert_equal "12.1 KB", 12345.to_s(:human_size)
+ assert_equal "1.18 MB", 1234567.to_s(:human_size)
+ assert_equal "1.15 GB", 1234567890.to_s(:human_size)
+ assert_equal "1.12 TB", 1234567890123.to_s(:human_size)
+ assert_equal "1.1 PB", 1234567890123456.to_s(:human_size)
+ assert_equal "1.07 EB", 1234567890123456789.to_s(:human_size)
+ assert_equal "1030 EB", exabytes(1026).to_s(:human_size)
+ assert_equal "444 KB", kilobytes(444).to_s(:human_size)
+ assert_equal "1020 MB", megabytes(1023).to_s(:human_size)
+ assert_equal "3 TB", terabytes(3).to_s(:human_size)
+ assert_equal "1.2 MB", 1234567.to_s(:human_size, precision: 2)
+ assert_equal "3 Bytes", 3.14159265.to_s(:human_size, precision: 4)
+ assert_equal "1 KB", kilobytes(1.0123).to_s(:human_size, precision: 2)
+ assert_equal "1.01 KB", kilobytes(1.0100).to_s(:human_size, precision: 4)
+ assert_equal "10 KB", kilobytes(10.000).to_s(:human_size, precision: 4)
+ assert_equal "1 Byte", 1.1.to_s(:human_size)
+ assert_equal "10 Bytes", 10.to_s(:human_size)
end
def test_to_s__human_size_with_options_hash
- assert_equal '1.2 MB', 1234567.to_s(:human_size, :precision => 2)
- assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :precision => 4)
- assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 2)
- assert_equal '1.01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4)
- assert_equal '10 KB', kilobytes(10.000).to_s(:human_size, :precision => 4)
- assert_equal '1 TB', 1234567890123.to_s(:human_size, :precision => 1)
- assert_equal '500 MB', 524288000.to_s(:human_size, :precision=>3)
- assert_equal '10 MB', 9961472.to_s(:human_size, :precision=>0)
- assert_equal '40 KB', 41010.to_s(:human_size, :precision => 1)
- assert_equal '40 KB', 41100.to_s(:human_size, :precision => 2)
- assert_equal '1.0 KB', kilobytes(1.0123).to_s(:human_size, :precision => 2, :strip_insignificant_zeros => false)
- assert_equal '1.012 KB', kilobytes(1.0123).to_s(:human_size, :precision => 3, :significant => false)
- assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 0, :significant => true) #ignores significant it precision is 0
+ assert_equal "1.2 MB", 1234567.to_s(:human_size, precision: 2)
+ assert_equal "3 Bytes", 3.14159265.to_s(:human_size, precision: 4)
+ assert_equal "1 KB", kilobytes(1.0123).to_s(:human_size, precision: 2)
+ assert_equal "1.01 KB", kilobytes(1.0100).to_s(:human_size, precision: 4)
+ assert_equal "10 KB", kilobytes(10.000).to_s(:human_size, precision: 4)
+ assert_equal "1 TB", 1234567890123.to_s(:human_size, precision: 1)
+ assert_equal "500 MB", 524288000.to_s(:human_size, precision: 3)
+ assert_equal "10 MB", 9961472.to_s(:human_size, precision: 0)
+ assert_equal "40 KB", 41010.to_s(:human_size, precision: 1)
+ assert_equal "40 KB", 41100.to_s(:human_size, precision: 2)
+ assert_equal "1.0 KB", kilobytes(1.0123).to_s(:human_size, precision: 2, strip_insignificant_zeros: false)
+ assert_equal "1.012 KB", kilobytes(1.0123).to_s(:human_size, precision: 3, significant: false)
+ assert_equal "1 KB", kilobytes(1.0123).to_s(:human_size, precision: 0, significant: true) # ignores significant it precision is 0
end
def test_to_s__human_size_with_custom_delimiter_and_separator
- assert_equal '1,01 KB', kilobytes(1.0123).to_s(:human_size, :precision => 3, :separator => ',')
- assert_equal '1,01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4, :separator => ',')
- assert_equal '1.000,1 TB', terabytes(1000.1).to_s(:human_size, :precision => 5, :delimiter => '.', :separator => ',')
+ assert_equal "1,01 KB", kilobytes(1.0123).to_s(:human_size, precision: 3, separator: ",")
+ assert_equal "1,01 KB", kilobytes(1.0100).to_s(:human_size, precision: 4, separator: ",")
+ assert_equal "1.000,1 TB", terabytes(1000.1).to_s(:human_size, precision: 5, delimiter: ".", separator: ",")
end
def test_number_to_human
- assert_equal '-123', -123.to_s(:human)
- assert_equal '-0.5', -0.5.to_s(:human)
- assert_equal '0', 0.to_s(:human)
- assert_equal '0.5', 0.5.to_s(:human)
- assert_equal '123', 123.to_s(:human)
- assert_equal '1.23 Thousand', 1234.to_s(:human)
- assert_equal '12.3 Thousand', 12345.to_s(:human)
- assert_equal '1.23 Million', 1234567.to_s(:human)
- assert_equal '1.23 Billion', 1234567890.to_s(:human)
- assert_equal '1.23 Trillion', 1234567890123.to_s(:human)
- assert_equal '1.23 Quadrillion', 1234567890123456.to_s(:human)
- assert_equal '1230 Quadrillion', 1234567890123456789.to_s(:human)
- assert_equal '490 Thousand', 489939.to_s(:human, :precision => 2)
- assert_equal '489.9 Thousand', 489939.to_s(:human, :precision => 4)
- assert_equal '489 Thousand', 489000.to_s(:human, :precision => 4)
- assert_equal '489.0 Thousand', 489000.to_s(:human, :precision => 4, :strip_insignificant_zeros => false)
- assert_equal '1.2346 Million', 1234567.to_s(:human, :precision => 4, :significant => false)
- assert_equal '1,2 Million', 1234567.to_s(:human, :precision => 1, :significant => false, :separator => ',')
- assert_equal '1 Million', 1234567.to_s(:human, :precision => 0, :significant => true, :separator => ',') #significant forced to false
+ assert_equal "-123", -123.to_s(:human)
+ assert_equal "-0.5", -0.5.to_s(:human)
+ assert_equal "0", 0.to_s(:human)
+ assert_equal "0.5", 0.5.to_s(:human)
+ assert_equal "123", 123.to_s(:human)
+ assert_equal "1.23 Thousand", 1234.to_s(:human)
+ assert_equal "12.3 Thousand", 12345.to_s(:human)
+ assert_equal "1.23 Million", 1234567.to_s(:human)
+ assert_equal "1.23 Billion", 1234567890.to_s(:human)
+ assert_equal "1.23 Trillion", 1234567890123.to_s(:human)
+ assert_equal "1.23 Quadrillion", 1234567890123456.to_s(:human)
+ assert_equal "1230 Quadrillion", 1234567890123456789.to_s(:human)
+ assert_equal "490 Thousand", 489939.to_s(:human, precision: 2)
+ assert_equal "489.9 Thousand", 489939.to_s(:human, precision: 4)
+ assert_equal "489 Thousand", 489000.to_s(:human, precision: 4)
+ assert_equal "489.0 Thousand", 489000.to_s(:human, precision: 4, strip_insignificant_zeros: false)
+ assert_equal "1.2346 Million", 1234567.to_s(:human, precision: 4, significant: false)
+ assert_equal "1,2 Million", 1234567.to_s(:human, precision: 1, significant: false, separator: ",")
+ assert_equal "1 Million", 1234567.to_s(:human, precision: 0, significant: true, separator: ",") # significant forced to false
end
def test_number_to_human_with_custom_units
- #Only integers
- volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
- assert_equal '123 lt', 123456.to_s(:human, :units => volume)
- assert_equal '12 ml', 12.to_s(:human, :units => volume)
- assert_equal '1.23 m3', 1234567.to_s(:human, :units => volume)
-
- #Including fractionals
- distance = {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"}
- assert_equal '1.23 mm', 0.00123.to_s(:human, :units => distance)
- assert_equal '1.23 cm', 0.0123.to_s(:human, :units => distance)
- assert_equal '1.23 dm', 0.123.to_s(:human, :units => distance)
- assert_equal '1.23 m', 1.23.to_s(:human, :units => distance)
- assert_equal '1.23 dam', 12.3.to_s(:human, :units => distance)
- assert_equal '1.23 hm', 123.to_s(:human, :units => distance)
- assert_equal '1.23 km', 1230.to_s(:human, :units => distance)
- assert_equal '1.23 km', 1230.to_s(:human, :units => distance)
- assert_equal '1.23 km', 1230.to_s(:human, :units => distance)
- assert_equal '12.3 km', 12300.to_s(:human, :units => distance)
-
- #The quantifiers don't need to be a continuous sequence
- gangster = {:hundred => "hundred bucks", :million => "thousand quids"}
- assert_equal '1 hundred bucks', 100.to_s(:human, :units => gangster)
- assert_equal '25 hundred bucks', 2500.to_s(:human, :units => gangster)
- assert_equal '25 thousand quids', 25000000.to_s(:human, :units => gangster)
- assert_equal '12300 thousand quids', 12345000000.to_s(:human, :units => gangster)
-
- #Spaces are stripped from the resulting string
- assert_equal '4', 4.to_s(:human, :units => {:unit => "", :ten => 'tens '})
- assert_equal '4.5 tens', 45.to_s(:human, :units => {:unit => "", :ten => ' tens '})
+ # Only integers
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
+ assert_equal "123 lt", 123456.to_s(:human, units: volume)
+ assert_equal "12 ml", 12.to_s(:human, units: volume)
+ assert_equal "1.23 m3", 1234567.to_s(:human, units: volume)
+
+ # Including fractionals
+ distance = { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
+ assert_equal "1.23 mm", 0.00123.to_s(:human, units: distance)
+ assert_equal "1.23 cm", 0.0123.to_s(:human, units: distance)
+ assert_equal "1.23 dm", 0.123.to_s(:human, units: distance)
+ assert_equal "1.23 m", 1.23.to_s(:human, units: distance)
+ assert_equal "1.23 dam", 12.3.to_s(:human, units: distance)
+ assert_equal "1.23 hm", 123.to_s(:human, units: distance)
+ assert_equal "1.23 km", 1230.to_s(:human, units: distance)
+ assert_equal "1.23 km", 1230.to_s(:human, units: distance)
+ assert_equal "1.23 km", 1230.to_s(:human, units: distance)
+ assert_equal "12.3 km", 12300.to_s(:human, units: distance)
+
+ # The quantifiers don't need to be a continuous sequence
+ gangster = { hundred: "hundred bucks", million: "thousand quids" }
+ assert_equal "1 hundred bucks", 100.to_s(:human, units: gangster)
+ assert_equal "25 hundred bucks", 2500.to_s(:human, units: gangster)
+ assert_equal "25 thousand quids", 25000000.to_s(:human, units: gangster)
+ assert_equal "12300 thousand quids", 12345000000.to_s(:human, units: gangster)
+
+ # Spaces are stripped from the resulting string
+ assert_equal "4", 4.to_s(:human, units: { unit: "", ten: "tens " })
+ assert_equal "4.5 tens", 45.to_s(:human, units: { unit: "", ten: " tens " })
end
def test_number_to_human_with_custom_format
- assert_equal '123 times Thousand', 123456.to_s(:human, :format => "%n times %u")
- volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
- assert_equal '123.lt', 123456.to_s(:human, :units => volume, :format => "%n.%u")
+ assert_equal "123 times Thousand", 123456.to_s(:human, format: "%n times %u")
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
+ assert_equal "123.lt", 123456.to_s(:human, units: volume, format: "%n.%u")
end
def test_to_s__injected_on_proper_types
- assert_equal Fixnum, 1230.class
- assert_equal '1.23 Thousand', 1230.to_s(:human)
-
- assert_equal Float, Float(1230).class
- assert_equal '1.23 Thousand', Float(1230).to_s(:human)
-
- assert_equal Bignum, (100**10).class
- assert_equal '100000 Quadrillion', (100**10).to_s(:human)
-
- assert_equal BigDecimal, BigDecimal("1000010").class
- assert_equal '1 Million', BigDecimal("1000010").to_s(:human)
- end
-
- def test_to_formatted_s_is_deprecated
- assert_deprecated do
- 5551234.to_formatted_s(:phone)
- end
+ assert_equal "1.23 Thousand", 1230.to_s(:human)
+ assert_equal "1.23 Thousand", Float(1230).to_s(:human)
+ assert_equal "100000 Quadrillion", (100**10).to_s(:human)
+ assert_equal "1 Million", BigDecimal("1000010").to_s(:human)
end
def test_to_s_with_invalid_formatter
- assert_equal '123', 123.to_s(:invalid)
- assert_equal '2.5', 2.5.to_s(:invalid)
- assert_equal '100000000000000000000', (100**10).to_s(:invalid)
- assert_equal '1000010.0', BigDecimal("1000010").to_s(:invalid)
+ assert_equal "123", 123.to_s(:invalid)
+ assert_equal "2.5", 2.5.to_s(:invalid)
+ assert_equal "100000000000000000000", (100**10).to_s(:invalid)
+ assert_equal "1000010.0", BigDecimal("1000010").to_s(:invalid)
end
def test_default_to_s
- assert_equal '123', 123.to_s
- assert_equal '1111011', 123.to_s(2)
+ assert_equal "123", 123.to_s
+ assert_equal "1111011", 123.to_s(2)
+
+ assert_equal "2.5", 2.5.to_s
- assert_equal '2.5', 2.5.to_s
+ assert_equal "100000000000000000000", (100**10).to_s
+ assert_equal "1010110101111000111010111100010110101100011000100000000000000000000", (100**10).to_s(2)
- assert_equal '100000000000000000000', (100**10).to_s
- assert_equal '1010110101111000111010111100010110101100011000100000000000000000000', (100**10).to_s(2)
+ assert_equal "1000010.0", BigDecimal("1000010").to_s
+ assert_equal "10000 10.0", BigDecimal("1000010").to_s("5F")
- assert_equal '1000010.0', BigDecimal("1000010").to_s
- assert_equal '10000 10.0', BigDecimal("1000010").to_s('5F')
+ assert_raises TypeError do
+ 1.to_s({})
+ end
end
def test_in_milliseconds
@@ -432,7 +408,6 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
# TODO: Remove positive and negative tests when we drop support to ruby < 2.3
b = 2**64
- b *= b until Bignum === b
T_ZERO = b.coerce(0).first
T_ONE = b.coerce(1).first
@@ -462,8 +437,8 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
end.new
assert_not_predicate(a, :positive?)
- assert_predicate(1/2r, :positive?)
- assert_not_predicate(-1/2r, :positive?)
+ assert_predicate(1 / 2r, :positive?)
+ assert_not_predicate(-1 / 2r, :positive?)
assert_predicate(T_ONE, :positive?)
assert_not_predicate(T_MONE, :positive?)
@@ -500,8 +475,8 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
end.new
assert_not_predicate(a, :negative?)
- assert_predicate(-1/2r, :negative?)
- assert_not_predicate(1/2r, :negative?)
+ assert_predicate(-1 / 2r, :negative?)
+ assert_not_predicate(1 / 2r, :negative?)
assert_not_predicate(T_ONE, :negative?)
assert_predicate(T_MONE, :negative?)
diff --git a/activesupport/test/core_ext/object/acts_like_test.rb b/activesupport/test/core_ext/object/acts_like_test.rb
index e68b1d23cb..9f7b81f7fc 100644
--- a/activesupport/test/core_ext/object/acts_like_test.rb
+++ b/activesupport/test/core_ext/object/acts_like_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object"
class ObjectTests < ActiveSupport::TestCase
class DuckTime
diff --git a/activesupport/test/core_ext/object/blank_test.rb b/activesupport/test/core_ext/object/blank_test.rb
index a142096993..954f415383 100644
--- a/activesupport/test/core_ext/object/blank_test.rb
+++ b/activesupport/test/core_ext/object/blank_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object/blank'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object/blank"
class BlankTest < ActiveSupport::TestCase
class EmptyTrue
@@ -14,8 +16,8 @@ class BlankTest < ActiveSupport::TestCase
end
end
- BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", ' ', "\u00a0", [], {} ]
- NOT = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]
+ BLANK = [ EmptyTrue.new, nil, false, "", " ", " \n\t \r ", " ", "\u00a0", [], {}, " ".encode("UTF-16LE") ]
+ NOT = [ EmptyFalse.new, Object.new, true, 0, 1, "a", [nil], { nil => 0 }, Time.now, "my value".encode("UTF-16LE") ]
def test_blank
BLANK.each { |v| assert_equal true, v.blank?, "#{v.inspect} should be blank" }
@@ -28,7 +30,7 @@ class BlankTest < ActiveSupport::TestCase
end
def test_presence
- BLANK.each { |v| assert_equal nil, v.presence, "#{v.inspect}.presence should return nil" }
+ BLANK.each { |v| assert_nil v.presence, "#{v.inspect}.presence should return nil" }
NOT.each { |v| assert_equal v, v.presence, "#{v.inspect}.presence should return self" }
end
end
diff --git a/activesupport/test/core_ext/object/deep_dup_test.rb b/activesupport/test/core_ext/object/deep_dup_test.rb
index 791b5e7172..2486592441 100644
--- a/activesupport/test/core_ext/object/deep_dup_test.rb
+++ b/activesupport/test/core_ext/object/deep_dup_test.rb
@@ -1,43 +1,44 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object'
+# frozen_string_literal: true
-class DeepDupTest < ActiveSupport::TestCase
+require "abstract_unit"
+require "active_support/core_ext/object"
+class DeepDupTest < ActiveSupport::TestCase
def test_array_deep_dup
array = [1, [2, 3]]
dup = array.deep_dup
dup[1][2] = 4
- assert_equal nil, array[1][2]
+ assert_nil array[1][2]
assert_equal 4, dup[1][2]
end
def test_hash_deep_dup
- hash = { :a => { :b => 'b' } }
+ hash = { a: { b: "b" } }
dup = hash.deep_dup
- dup[:a][:c] = 'c'
- assert_equal nil, hash[:a][:c]
- assert_equal 'c', dup[:a][:c]
+ dup[:a][:c] = "c"
+ assert_nil hash[:a][:c]
+ assert_equal "c", dup[:a][:c]
end
def test_array_deep_dup_with_hash_inside
- array = [1, { :a => 2, :b => 3 } ]
+ array = [1, { a: 2, b: 3 } ]
dup = array.deep_dup
dup[1][:c] = 4
- assert_equal nil, array[1][:c]
+ assert_nil array[1][:c]
assert_equal 4, dup[1][:c]
end
def test_hash_deep_dup_with_array_inside
- hash = { :a => [1, 2] }
+ hash = { a: [1, 2] }
dup = hash.deep_dup
- dup[:a][2] = 'c'
- assert_equal nil, hash[:a][2]
- assert_equal 'c', dup[:a][2]
+ dup[:a][2] = "c"
+ assert_nil hash[:a][2]
+ assert_equal "c", dup[:a][2]
end
def test_deep_dup_initialize
zero_hash = Hash.new 0
- hash = { :a => zero_hash }
+ hash = { a: zero_hash }
dup = hash.deep_dup
assert_equal 0, dup[:a][44]
end
@@ -51,9 +52,8 @@ class DeepDupTest < ActiveSupport::TestCase
end
def test_deep_dup_with_hash_class_key
- hash = { Fixnum => 1 }
+ hash = { Integer => 1 }
dup = hash.deep_dup
assert_equal 1, dup.keys.length
end
-
end
diff --git a/activesupport/test/core_ext/object/duplicable_test.rb b/activesupport/test/core_ext/object/duplicable_test.rb
index 042f5cfb34..b984becce3 100644
--- a/activesupport/test/core_ext/object/duplicable_test.rb
+++ b/activesupport/test/core_ext/object/duplicable_test.rb
@@ -1,19 +1,31 @@
-require 'abstract_unit'
-require 'bigdecimal'
-require 'active_support/core_ext/object/duplicable'
-require 'active_support/core_ext/numeric/time'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "bigdecimal"
+require "active_support/core_ext/object/duplicable"
+require "active_support/core_ext/numeric/time"
class DuplicableTest < ActiveSupport::TestCase
- RAISE_DUP = [nil, false, true, :symbol, 1, 2.3, method(:puts)]
- ALLOW_DUP = ['1', Object.new, /foo/, [], {}, Time.now, Class.new, Module.new]
- ALLOW_DUP << BigDecimal.new('4.56')
+ if RUBY_VERSION >= "2.5.0"
+ RAISE_DUP = [method(:puts)]
+ ALLOW_DUP = ["1", "symbol_from_string".to_sym, Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal("4.56"), nil, false, true, 1, 2.3, Complex(1), Rational(1)]
+ elsif RUBY_VERSION >= "2.4.1"
+ RAISE_DUP = [method(:puts), Complex(1), Rational(1)]
+ ALLOW_DUP = ["1", "symbol_from_string".to_sym, Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal("4.56"), nil, false, true, 1, 2.3]
+ elsif RUBY_VERSION >= "2.4.0" # Due to 2.4.0 bug. This elsif cannot be removed unless we drop 2.4.0 support...
+ RAISE_DUP = [method(:puts), Complex(1), Rational(1), "symbol_from_string".to_sym]
+ ALLOW_DUP = ["1", Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal("4.56"), nil, false, true, 1, 2.3]
+ else
+ RAISE_DUP = [nil, false, true, :symbol, 1, 2.3, method(:puts), Complex(1), Rational(1)]
+ ALLOW_DUP = ["1", Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal("4.56")]
+ end
def test_duplicable
rubinius_skip "* Method#dup is allowed at the moment on Rubinius\n" \
"* https://github.com/rubinius/rubinius/issues/3089"
RAISE_DUP.each do |v|
- assert !v.duplicable?
+ assert !v.duplicable?, "#{ v.inspect } should not be duplicable"
assert_raises(TypeError, v.class.name) { v.dup }
end
diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb
index 32d512eca3..52c21f2e8e 100644
--- a/activesupport/test/core_ext/object/inclusion_test.rb
+++ b/activesupport/test/core_ext/object/inclusion_test.rb
@@ -1,10 +1,12 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object/inclusion'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object/inclusion"
class InTest < ActiveSupport::TestCase
def test_in_array
- assert 1.in?([1,2])
- assert !3.in?([1,2])
+ assert 1.in?([1, 2])
+ assert !3.in?([1, 2])
end
def test_in_hash
@@ -25,7 +27,7 @@ class InTest < ActiveSupport::TestCase
end
def test_in_set
- s = Set.new([1,2])
+ s = Set.new([1, 2])
assert 1.in?(s)
assert !3.in?(s)
end
@@ -46,11 +48,11 @@ class InTest < ActiveSupport::TestCase
assert !A.in?(A)
assert !A.in?(D)
end
-
+
def test_no_method_catching
assert_raise(ArgumentError) { 1.in?(1) }
end
-
+
def test_presence_in
assert_equal "stuff", "stuff".presence_in(%w( lots of stuff ))
assert_nil "stuff".presence_in(%w( lots of crap ))
diff --git a/activesupport/test/core_ext/object/instance_variables_test.rb b/activesupport/test/core_ext/object/instance_variables_test.rb
index 9f4c5dc4f1..a3d8daab5b 100644
--- a/activesupport/test/core_ext/object/instance_variables_test.rb
+++ b/activesupport/test/core_ext/object/instance_variables_test.rb
@@ -1,11 +1,13 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object"
class ObjectInstanceVariableTest < ActiveSupport::TestCase
def setup
@source, @dest = Object.new, Object.new
- @source.instance_variable_set(:@bar, 'bar')
- @source.instance_variable_set(:@baz, 'baz')
+ @source.instance_variable_set(:@bar, "bar")
+ @source.instance_variable_set(:@baz, "baz")
end
def test_instance_variable_names
@@ -13,19 +15,19 @@ class ObjectInstanceVariableTest < ActiveSupport::TestCase
end
def test_instance_values
- assert_equal({'bar' => 'bar', 'baz' => 'baz'}, @source.instance_values)
+ assert_equal({ "bar" => "bar", "baz" => "baz" }, @source.instance_values)
end
def test_instance_exec_passes_arguments_to_block
- assert_equal %w(hello goodbye), 'hello'.instance_exec('goodbye') { |v| [self, v] }
+ assert_equal %w(hello goodbye), "hello".dup.instance_exec("goodbye") { |v| [self, v] }
end
def test_instance_exec_with_frozen_obj
- assert_equal %w(olleh goodbye), 'hello'.freeze.instance_exec('goodbye') { |v| [reverse, v] }
+ assert_equal %w(olleh goodbye), "hello".freeze.instance_exec("goodbye") { |v| [reverse, v] }
end
def test_instance_exec_nested
- assert_equal %w(goodbye olleh bar), 'hello'.instance_exec('goodbye') { |arg|
- [arg] + instance_exec('bar') { |v| [reverse, v] } }
+ assert_equal %w(goodbye olleh bar), "hello".dup.instance_exec("goodbye") { |arg|
+ [arg] + instance_exec("bar") { |v| [reverse, v] } }
end
end
diff --git a/activesupport/test/core_ext/object/json_cherry_pick_test.rb b/activesupport/test/core_ext/object/json_cherry_pick_test.rb
index 2f7ea3a497..22659a4050 100644
--- a/activesupport/test/core_ext/object/json_cherry_pick_test.rb
+++ b/activesupport/test/core_ext/object/json_cherry_pick_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
# These test cases were added to test that cherry-picking the json extensions
# works correctly, primarily for dependencies problems reported in #16131. They
@@ -9,7 +11,7 @@ class JsonCherryPickTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def test_time_as_json
- require_or_skip 'active_support/core_ext/object/json'
+ require_or_skip "active_support/core_ext/object/json"
expected = Time.new(2004, 7, 25)
actual = Time.parse(expected.as_json)
@@ -18,7 +20,7 @@ class JsonCherryPickTest < ActiveSupport::TestCase
end
def test_date_as_json
- require_or_skip 'active_support/core_ext/object/json'
+ require_or_skip "active_support/core_ext/object/json"
expected = Date.new(2004, 7, 25)
actual = Date.parse(expected.as_json)
@@ -27,7 +29,7 @@ class JsonCherryPickTest < ActiveSupport::TestCase
end
def test_datetime_as_json
- require_or_skip 'active_support/core_ext/object/json'
+ require_or_skip "active_support/core_ext/object/json"
expected = DateTime.new(2004, 7, 25)
actual = DateTime.parse(expected.as_json)
diff --git a/activesupport/test/core_ext/object/json_gem_encoding_test.rb b/activesupport/test/core_ext/object/json_gem_encoding_test.rb
index 2cbb1d590f..4cdb6ed09f 100644
--- a/activesupport/test/core_ext/object/json_gem_encoding_test.rb
+++ b/activesupport/test/core_ext/object/json_gem_encoding_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'json'
-require 'json/encoding_test_cases'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "json"
+require "json/encoding_test_cases"
# These test cases were added to test that we do not interfere with json gem's
# output when the AS encoder is loaded, primarily for problems reported in
@@ -13,7 +15,7 @@ require 'json/encoding_test_cases'
# we need to require this upfront to ensure we don't get a false failure, but
# ideally we should just fix the BigDecimal core_ext to not change to_s without
# arguments.
-require 'active_support/core_ext/big_decimal'
+require "active_support/core_ext/big_decimal"
class JsonGemEncodingTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
@@ -48,7 +50,7 @@ class JsonGemEncodingTest < ActiveSupport::TestCase
exception = e
end
- require_or_skip 'active_support/core_ext/object/json'
+ require_or_skip "active_support/core_ext/object/json"
if exception
assert_raises_with_message JSON::GeneratorError, e.message do
diff --git a/activesupport/test/core_ext/object/to_param_test.rb b/activesupport/test/core_ext/object/to_param_test.rb
index 30a7557dc2..612156bd99 100644
--- a/activesupport/test/core_ext/object/to_param_test.rb
+++ b/activesupport/test/core_ext/object/to_param_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object/to_param'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object/to_param"
class ToParamTest < ActiveSupport::TestCase
class CustomString < String
@@ -10,8 +12,8 @@ class ToParamTest < ActiveSupport::TestCase
def test_object
foo = Object.new
- def foo.to_s; 'foo' end
- assert_equal 'foo', foo.to_param
+ def foo.to_s; "foo" end
+ assert_equal "foo", foo.to_param
end
def test_nil
@@ -25,13 +27,13 @@ class ToParamTest < ActiveSupport::TestCase
def test_array
# Empty Array
- assert_equal '', [].to_param
+ assert_equal "", [].to_param
array = [1, 2, 3, 4]
assert_equal "1/2/3/4", array.to_param
# Array of different objects
- array = [1, '3', { a: 1, b: 2 }, nil, true, false, CustomString.new('object')]
+ array = [1, "3", { a: 1, b: 2 }, nil, true, false, CustomString.new("object")]
assert_equal "1/3/a=1&b=2//true/false/custom-object", array.to_param
end
end
diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb
index 09cab3ed35..7593bcfa4d 100644
--- a/activesupport/test/core_ext/object/to_query_test.rb
+++ b/activesupport/test/core_ext/object/to_query_test.rb
@@ -1,82 +1,84 @@
-require 'abstract_unit'
-require 'active_support/ordered_hash'
-require 'active_support/core_ext/object/to_query'
-require 'active_support/core_ext/string/output_safety'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/ordered_hash"
+require "active_support/core_ext/object/to_query"
+require "active_support/core_ext/string/output_safety"
class ToQueryTest < ActiveSupport::TestCase
def test_simple_conversion
- assert_query_equal 'a=10', :a => 10
+ assert_query_equal "a=10", a: 10
end
def test_cgi_escaping
- assert_query_equal 'a%3Ab=c+d', 'a:b' => 'c d'
+ assert_query_equal "a%3Ab=c+d", "a:b" => "c d"
end
def test_html_safe_parameter_key
- assert_query_equal 'a%3Ab=c+d', 'a:b'.html_safe => 'c d'
+ assert_query_equal "a%3Ab=c+d", "a:b".html_safe => "c d"
end
def test_html_safe_parameter_value
- assert_query_equal 'a=%5B10%5D', 'a' => '[10]'.html_safe
+ assert_query_equal "a=%5B10%5D", "a" => "[10]".html_safe
end
def test_nil_parameter_value
empty = Object.new
def empty.to_param; nil end
- assert_query_equal 'a=', 'a' => empty
+ assert_query_equal "a=", "a" => empty
end
def test_nested_conversion
- assert_query_equal 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas',
- :person => Hash[:login, 'seckar', :name, 'Nicholas']
+ assert_query_equal "person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas",
+ person: Hash[:login, "seckar", :name, "Nicholas"]
end
def test_multiple_nested
- assert_query_equal 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10',
- Hash[:account, {:person => {:id => 20}}, :person, {:id => 10}]
+ assert_query_equal "account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10",
+ Hash[:account, { person: { id: 20 } }, :person, { id: 10 }]
end
def test_array_values
- assert_query_equal 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20',
- :person => {:id => [10, 20]}
+ assert_query_equal "person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20",
+ person: { id: [10, 20] }
end
def test_array_values_are_not_sorted
- assert_query_equal 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10',
- :person => {:id => [20, 10]}
+ assert_query_equal "person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10",
+ person: { id: [20, 10] }
end
def test_empty_array
- assert_equal "person%5B%5D=", [].to_query('person')
+ assert_equal "person%5B%5D=", [].to_query("person")
end
def test_nested_empty_hash
- assert_equal '',
+ assert_equal "",
{}.to_query
- assert_query_equal 'a=1&b%5Bc%5D=3',
- { a: 1, b: { c: 3, d: {} } }
- assert_query_equal '',
- { a: {b: {c: {}}} }
- assert_query_equal 'b%5Bc%5D=false&b%5Be%5D=&b%5Bf%5D=&p=12',
- { p: 12, b: { c: false, e: nil, f: '' } }
- assert_query_equal 'b%5Bc%5D=3&b%5Bf%5D=',
- { b: { c: 3, k: {}, f: '' } }
- assert_query_equal 'b=3',
- {a: [], b: 3}
+ assert_query_equal "a=1&b%5Bc%5D=3",
+ a: 1, b: { c: 3, d: {} }
+ assert_query_equal "",
+ a: { b: { c: {} } }
+ assert_query_equal "b%5Bc%5D=false&b%5Be%5D=&b%5Bf%5D=&p=12",
+ p: 12, b: { c: false, e: nil, f: "" }
+ assert_query_equal "b%5Bc%5D=3&b%5Bf%5D=",
+ b: { c: 3, k: {}, f: "" }
+ assert_query_equal "b=3",
+ a: [], b: 3
end
def test_hash_with_namespace
- hash = { name: 'Nakshay', nationality: 'Indian' }
- assert_equal "user%5Bname%5D=Nakshay&user%5Bnationality%5D=Indian", hash.to_query('user')
+ hash = { name: "Nakshay", nationality: "Indian" }
+ assert_equal "user%5Bname%5D=Nakshay&user%5Bnationality%5D=Indian", hash.to_query("user")
end
def test_hash_sorted_lexicographically
- hash = { type: 'human', name: 'Nakshay' }
+ hash = { type: "human", name: "Nakshay" }
assert_equal "name=Nakshay&type=human", hash.to_query
end
private
def assert_query_equal(expected, actual)
- assert_equal expected.split('&'), actual.to_query.split('&')
+ assert_equal expected.split("&"), actual.to_query.split("&")
end
end
diff --git a/activesupport/test/core_ext/object/try_test.rb b/activesupport/test/core_ext/object/try_test.rb
index 25bf0207b8..fe68b24bf5 100644
--- a/activesupport/test/core_ext/object/try_test.rb
+++ b/activesupport/test/core_ext/object/try_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object"
class ObjectTryTest < ActiveSupport::TestCase
def setup
@@ -15,7 +17,7 @@ class ObjectTryTest < ActiveSupport::TestCase
def test_nonexisting_method_with_arguments
method = :undefined_method
assert !@string.respond_to?(method)
- assert_nil @string.try(method, 'llo', 'y')
+ assert_nil @string.try(method, "llo", "y")
end
def test_nonexisting_method_bang
@@ -27,7 +29,7 @@ class ObjectTryTest < ActiveSupport::TestCase
def test_nonexisting_method_with_arguments_bang
method = :undefined_method
assert !@string.respond_to?(method)
- assert_raise(NoMethodError) { @string.try!(method, 'llo', 'y') }
+ assert_raise(NoMethodError) { @string.try!(method, "llo", "y") }
end
def test_valid_method
@@ -35,11 +37,11 @@ class ObjectTryTest < ActiveSupport::TestCase
end
def test_argument_forwarding
- assert_equal 'Hey', @string.try(:sub, 'llo', 'y')
+ assert_equal "Hey", @string.try(:sub, "llo", "y")
end
def test_block_forwarding
- assert_equal 'Hey', @string.try(:sub, 'llo') { |match| 'y' }
+ assert_equal "Hey", @string.try(:sub, "llo") { |match| "y" }
end
def test_nil_to_type
@@ -48,7 +50,7 @@ class ObjectTryTest < ActiveSupport::TestCase
end
def test_false_try
- assert_equal 'false', false.try(:to_s)
+ assert_equal "false", false.try(:to_s)
end
def test_try_only_block
@@ -78,7 +80,7 @@ class ObjectTryTest < ActiveSupport::TestCase
private
def private_method
- 'private method'
+ "private method"
end
end
@@ -90,7 +92,7 @@ class ObjectTryTest < ActiveSupport::TestCase
private
def private_method
- 'private method'
+ "private method"
end
end
@@ -99,22 +101,22 @@ class ObjectTryTest < ActiveSupport::TestCase
class Decorator < SimpleDelegator
def delegator_method
- 'delegator method'
+ "delegator method"
end
def reverse
- 'overridden reverse'
+ "overridden reverse"
end
private
def private_delegator_method
- 'private delegator method'
+ "private delegator method"
end
end
def test_try_with_method_on_delegator
- assert_equal 'delegator method', Decorator.new(@string).try(:delegator_method)
+ assert_equal "delegator method", Decorator.new(@string).try(:delegator_method)
end
def test_try_with_method_on_delegator_target
@@ -122,7 +124,7 @@ class ObjectTryTest < ActiveSupport::TestCase
end
def test_try_with_overridden_method_on_delegator
- assert_equal 'overridden reverse', Decorator.new(@string).reverse
+ assert_equal "overridden reverse", Decorator.new(@string).reverse
end
def test_try_with_private_method_on_delegator
@@ -140,7 +142,7 @@ class ObjectTryTest < ActiveSupport::TestCase
private
def private_method
- 'private method'
+ "private method"
end
end
@@ -152,7 +154,7 @@ class ObjectTryTest < ActiveSupport::TestCase
private
def private_method
- 'private method'
+ "private method"
end
end
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index f28cebda3d..903c173e59 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -1,7 +1,9 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'active_support/core_ext/numeric'
-require 'active_support/core_ext/range'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "active_support/core_ext/numeric"
+require "active_support/core_ext/range"
class RangeTest < ActiveSupport::TestCase
def test_to_s_from_dates
@@ -14,6 +16,11 @@ class RangeTest < ActiveSupport::TestCase
assert_equal "BETWEEN '2005-12-10 15:30:00' AND '2005-12-10 17:30:00'", date_range.to_s(:db)
end
+ def test_to_s_with_alphabets
+ alphabet_range = ("a".."z")
+ assert_equal "BETWEEN 'a' AND 'z'", alphabet_range.to_s(:db)
+ end
+
def test_to_s_with_numeric
number_range = (1..100)
assert_equal "BETWEEN '1' AND '100'", number_range.to_s(:db)
@@ -66,15 +73,15 @@ class RangeTest < ActiveSupport::TestCase
end
def test_exclusive_end_should_not_include_identical_with_inclusive_end
- assert !(1...10).include?(1..10)
+ assert_not_includes (1...10), 1..10
end
def test_should_not_include_overlapping_first
- assert !(2..8).include?(1..3)
+ assert_not_includes (2..8), 1..3
end
def test_should_not_include_overlapping_last
- assert !(2..8).include?(5..9)
+ assert_not_includes (2..8), 5..9
end
def test_should_include_identical_exclusive_with_floats
@@ -99,24 +106,27 @@ class RangeTest < ActiveSupport::TestCase
end
def test_each_on_time_with_zone
- twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
assert_raises TypeError do
((twz - 1.hour)..twz).each {}
end
end
def test_step_on_time_with_zone
- twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
assert_raises TypeError do
((twz - 1.hour)..twz).step(1) {}
end
end
def test_include_on_time_with_zone
- twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
- assert_raises TypeError do
- ((twz - 1.hour)..twz).include?(twz)
- end
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
+ assert ((twz - 1.hour)..twz).include?(twz)
+ end
+
+ def test_case_equals_on_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
+ assert ((twz - 1.hour)..twz) === twz
end
def test_date_time_with_each
diff --git a/activesupport/test/core_ext/regexp_ext_test.rb b/activesupport/test/core_ext/regexp_ext_test.rb
index c2398d31bd..5737bdafda 100644
--- a/activesupport/test/core_ext/regexp_ext_test.rb
+++ b/activesupport/test/core_ext/regexp_ext_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/regexp'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/regexp"
class RegexpExtAccessTests < ActiveSupport::TestCase
def test_multiline
@@ -7,4 +9,28 @@ class RegexpExtAccessTests < ActiveSupport::TestCase
assert_equal false, //.multiline?
assert_equal false, /(?m:)/.multiline?
end
+
+ # Based on https://github.com/ruby/ruby/blob/trunk/test/ruby/test_regexp.rb.
+ def test_match_p
+ /back(...)/ =~ "backref"
+ # must match here, but not in a separate method, e.g., assert_send,
+ # to check if $~ is affected or not.
+ assert_equal false, //.match?(nil)
+ assert_equal true, //.match?("")
+ assert_equal true, /.../.match?(:abc)
+ assert_raise(TypeError) { /.../.match?(Object.new) }
+ assert_equal true, /b/.match?("abc")
+ assert_equal true, /b/.match?("abc", 1)
+ assert_equal true, /../.match?("abc", 1)
+ assert_equal true, /../.match?("abc", -2)
+ assert_equal false, /../.match?("abc", -4)
+ assert_equal false, /../.match?("abc", 4)
+ assert_equal true, /\z/.match?("")
+ assert_equal true, /\z/.match?("abc")
+ assert_equal true, /R.../.match?("Ruby")
+ assert_equal false, /R.../.match?("Ruby", 1)
+ assert_equal false, /P.../.match?("Ruby")
+ assert_equal "backref", $&
+ assert_equal "ref", $1
+ end
end
diff --git a/activesupport/test/core_ext/secure_random_test.rb b/activesupport/test/core_ext/secure_random_test.rb
index dfacb7fe9f..7067fb524c 100644
--- a/activesupport/test/core_ext/secure_random_test.rb
+++ b/activesupport/test/core_ext/secure_random_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/securerandom'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/securerandom"
class SecureRandomTest < ActiveSupport::TestCase
def test_base58
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index f38b225b38..5c5abe9fd1 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -1,15 +1,19 @@
-require 'date'
-require 'abstract_unit'
-require 'inflector_test_cases'
-require 'constantize_test_cases'
-
-require 'active_support/inflector'
-require 'active_support/core_ext/string'
-require 'active_support/time'
-require 'active_support/core_ext/string/strip'
-require 'active_support/core_ext/string/output_safety'
-require 'active_support/core_ext/string/indent'
-require 'time_zone_test_helpers'
+# frozen_string_literal: true
+
+require "date"
+require "abstract_unit"
+require "timeout"
+require "inflector_test_cases"
+require "constantize_test_cases"
+
+require "active_support/inflector"
+require "active_support/core_ext/string"
+require "active_support/time"
+require "active_support/core_ext/string/strip"
+require "active_support/core_ext/string/output_safety"
+require "active_support/core_ext/string/indent"
+require "time_zone_test_helpers"
+require "yaml"
class StringInflectionsTest < ActiveSupport::TestCase
include InflectorTestCases
@@ -17,12 +21,12 @@ class StringInflectionsTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
def test_strip_heredoc_on_an_empty_string
- assert_equal '', ''.strip_heredoc
+ assert_equal "", "".strip_heredoc
end
def test_strip_heredoc_on_a_string_with_no_lines
- assert_equal 'x', 'x'.strip_heredoc
- assert_equal 'x', ' x'.strip_heredoc
+ assert_equal "x", "x".strip_heredoc
+ assert_equal "x", " x".strip_heredoc
end
def test_strip_heredoc_on_a_heredoc_with_no_margin
@@ -59,7 +63,7 @@ class StringInflectionsTest < ActiveSupport::TestCase
assert_equal("blargles", "blargle".pluralize(2))
end
- test 'pluralize with count = 1 still returns new string' do
+ test "pluralize with count = 1 still returns new string" do
name = "Kuldeep"
assert_not_same name.pluralize(1), name
end
@@ -76,6 +80,12 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
end
+ def test_titleize_with_keep_id_suffix
+ MixtureToTitleCaseWithKeepIdSuffix.each do |before, titleized|
+ assert_equal(titleized, before.titleize(keep_id_suffix: true))
+ end
+ end
+
def test_upcase_first
assert_equal "What a Lovely Day", "what a Lovely Day".upcase_first
end
@@ -95,7 +105,14 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
def test_camelize_lower
- assert_equal('capital', 'Capital'.camelize(:lower))
+ assert_equal("capital", "Capital".camelize(:lower))
+ end
+
+ def test_camelize_invalid_option
+ e = assert_raise ArgumentError do
+ "Capital".camelize(nil)
+ end
+ assert_equal("Invalid option, use either :upper or :lower.", e.message)
end
def test_dasherize
@@ -151,53 +168,37 @@ class StringInflectionsTest < ActiveSupport::TestCase
def test_string_parameterized_normal
StringToParameterized.each do |normal, slugged|
- assert_equal(normal.parameterize, slugged)
+ assert_equal(slugged, normal.parameterize)
end
end
def test_string_parameterized_normal_preserve_case
StringToParameterizedPreserveCase.each do |normal, slugged|
- assert_equal(normal.parameterize(preserve_case: true), slugged)
+ assert_equal(slugged, normal.parameterize(preserve_case: true))
end
end
def test_string_parameterized_no_separator
StringToParameterizeWithNoSeparator.each do |normal, slugged|
- assert_equal(normal.parameterize(separator: ''), slugged)
- end
- end
-
- def test_string_parameterized_no_separator_deprecated
- StringToParameterizeWithNoSeparator.each do |normal, slugged|
- assert_deprecated(/Passing the separator argument as a positional parameter is deprecated and will soon be removed. Use `separator: ''` instead./i) do
- assert_equal(normal.parameterize(''), slugged)
- end
+ assert_equal(slugged, normal.parameterize(separator: ""))
end
end
def test_string_parameterized_no_separator_preserve_case
StringToParameterizePreserveCaseWithNoSeparator.each do |normal, slugged|
- assert_equal(normal.parameterize(separator: '', preserve_case: true), slugged)
+ assert_equal(slugged, normal.parameterize(separator: "", preserve_case: true))
end
end
def test_string_parameterized_underscore
StringToParameterizeWithUnderscore.each do |normal, slugged|
- assert_equal(normal.parameterize(separator: '_'), slugged)
- end
- end
-
- def test_string_parameterized_underscore_deprecated
- StringToParameterizeWithUnderscore.each do |normal, slugged|
- assert_deprecated(/Passing the separator argument as a positional parameter is deprecated and will soon be removed. Use `separator: '_'` instead./i) do
- assert_equal(normal.parameterize('_'), slugged)
- end
+ assert_equal(slugged, normal.parameterize(separator: "_"))
end
end
def test_string_parameterized_underscore_preserve_case
- StringToParameterizePreserceCaseWithUnderscore.each do |normal, slugged|
- assert_equal(normal.parameterize(separator: '_', preserve_case: true), slugged)
+ StringToParameterizePreserveCaseWithUnderscore.each do |normal, slugged|
+ assert_equal(slugged, normal.parameterize(separator: "_", preserve_case: true))
end
end
@@ -213,31 +214,37 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
end
+ def test_humanize_with_keep_id_suffix
+ UnderscoreToHumanWithKeepIdSuffix.each do |underscore, human|
+ assert_equal(human, underscore.humanize(keep_id_suffix: true))
+ end
+ end
+
def test_humanize_with_html_escape
- assert_equal 'Hello', ERB::Util.html_escape("hello").humanize
+ assert_equal "Hello", ERB::Util.html_escape("hello").humanize
end
def test_ord
- assert_equal 97, 'a'.ord
- assert_equal 97, 'abc'.ord
+ assert_equal 97, "a".ord
+ assert_equal 97, "abc".ord
end
def test_starts_ends_with_alias
s = "hello"
- assert s.starts_with?('h')
- assert s.starts_with?('hel')
- assert !s.starts_with?('el')
+ assert s.starts_with?("h")
+ assert s.starts_with?("hel")
+ assert !s.starts_with?("el")
- assert s.ends_with?('o')
- assert s.ends_with?('lo')
- assert !s.ends_with?('el')
+ assert s.ends_with?("o")
+ assert s.ends_with?("lo")
+ assert !s.ends_with?("el")
end
def test_string_squish
original = %{\u205f\u3000 A string surrounded by various unicode spaces,
- with tabs(\t\t), newlines(\n\n), unicode nextlines(\u0085\u0085) and many spaces( ). \u00a0\u2007}
+ with tabs(\t\t), newlines(\n\n), unicode nextlines(\u0085\u0085) and many spaces( ). \u00a0\u2007}.dup
- expected = "A string surrounded by various unicode spaces, " +
+ expected = "A string surrounded by various unicode spaces, " \
"with tabs( ), newlines( ), unicode nextlines( ) and many spaces( )."
# Make sure squish returns what we expect:
@@ -262,16 +269,16 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
def test_truncate_with_omission_and_separator
- assert_equal "Hello[...]", "Hello World!".truncate(10, :omission => "[...]")
- assert_equal "Hello[...]", "Hello Big World!".truncate(13, :omission => "[...]", :separator => ' ')
- assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, :omission => "[...]", :separator => ' ')
- assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => ' ')
+ assert_equal "Hello[...]", "Hello World!".truncate(10, omission: "[...]")
+ assert_equal "Hello[...]", "Hello Big World!".truncate(13, omission: "[...]", separator: " ")
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, omission: "[...]", separator: " ")
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, omission: "[...]", separator: " ")
end
def test_truncate_with_omission_and_regexp_separator
- assert_equal "Hello[...]", "Hello Big World!".truncate(13, :omission => "[...]", :separator => /\s/)
- assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, :omission => "[...]", :separator => /\s/)
- assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => /\s/)
+ assert_equal "Hello[...]", "Hello Big World!".truncate(13, omission: "[...]", separator: /\s/)
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, omission: "[...]", separator: /\s/)
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, omission: "[...]", separator: /\s/)
end
def test_truncate_words
@@ -280,33 +287,33 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
def test_truncate_words_with_omission
- assert_equal "Hello Big World!", "Hello Big World!".truncate_words(3, :omission => "[...]")
- assert_equal "Hello Big[...]", "Hello Big World!".truncate_words(2, :omission => "[...]")
+ assert_equal "Hello Big World!", "Hello Big World!".truncate_words(3, omission: "[...]")
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate_words(2, omission: "[...]")
end
def test_truncate_words_with_separator
- assert_equal "Hello<br>Big<br>World!...", "Hello<br>Big<br>World!<br>".truncate_words(3, :separator => '<br>')
- assert_equal "Hello<br>Big<br>World!", "Hello<br>Big<br>World!".truncate_words(3, :separator => '<br>')
- assert_equal "Hello\n<br>Big...", "Hello\n<br>Big<br>Wide<br>World!".truncate_words(2, :separator => '<br>')
+ assert_equal "Hello<br>Big<br>World!...", "Hello<br>Big<br>World!<br>".truncate_words(3, separator: "<br>")
+ assert_equal "Hello<br>Big<br>World!", "Hello<br>Big<br>World!".truncate_words(3, separator: "<br>")
+ assert_equal "Hello\n<br>Big...", "Hello\n<br>Big<br>Wide<br>World!".truncate_words(2, separator: "<br>")
end
def test_truncate_words_with_separator_and_omission
- assert_equal "Hello<br>Big<br>World![...]", "Hello<br>Big<br>World!<br>".truncate_words(3, :omission => "[...]", :separator => '<br>')
- assert_equal "Hello<br>Big<br>World!", "Hello<br>Big<br>World!".truncate_words(3, :omission => "[...]", :separator => '<br>')
+ assert_equal "Hello<br>Big<br>World![...]", "Hello<br>Big<br>World!<br>".truncate_words(3, omission: "[...]", separator: "<br>")
+ assert_equal "Hello<br>Big<br>World!", "Hello<br>Big<br>World!".truncate_words(3, omission: "[...]", separator: "<br>")
end
def test_truncate_words_with_complex_string
Timeout.timeout(10) do
complex_string = "aa aa aaa aa aaa aaa aaa aa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaaa aaaaa aaaaa aaaaaa aa aa aa aaa aa aaa aa aa aa aa a aaa aaa \n a aaa <<s"
- assert_equal complex_string.truncate_words(80), complex_string
+ assert_equal complex_string, complex_string.truncate_words(80)
end
rescue Timeout::Error
assert false
end
def test_truncate_multibyte
- assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8),
- "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8).truncate(10)
+ assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".dup.force_encoding(Encoding::UTF_8),
+ "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".dup.force_encoding(Encoding::UTF_8).truncate(10)
end
def test_truncate_should_not_be_html_safe
@@ -327,7 +334,7 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
def test_remove!
- original = "This is a very good day to die"
+ original = "This is a very good day to die".dup
assert_equal "This is a good day to die", original.remove!(" very")
assert_equal "This is a good day to die", original
assert_equal "This is a good day", original.remove!(" to ", /die/)
@@ -344,7 +351,7 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
class StringAccessTest < ActiveSupport::TestCase
- test "#at with Fixnum, returns a substring of one character at that position" do
+ test "#at with Integer, returns a substring of one character at that position" do
assert_equal "h", "hello".at(0)
end
@@ -354,22 +361,22 @@ class StringAccessTest < ActiveSupport::TestCase
test "#at with Regex, returns the matching portion of the string" do
assert_equal "lo", "hello".at(/lo/)
- assert_equal nil, "hello".at(/nonexisting/)
+ assert_nil "hello".at(/nonexisting/)
end
- test "#from with positive Fixnum, returns substring from the given position to the end" do
+ test "#from with positive Integer, returns substring from the given position to the end" do
assert_equal "llo", "hello".from(2)
end
- test "#from with negative Fixnum, position is counted from the end" do
+ test "#from with negative Integer, position is counted from the end" do
assert_equal "lo", "hello".from(-2)
end
- test "#to with positive Fixnum, substring from the beginning to the given position" do
+ test "#to with positive Integer, substring from the beginning to the given position" do
assert_equal "hel", "hello".to(2)
end
- test "#to with negative Fixnum, position is counted from the end" do
+ test "#to with negative Integer, position is counted from the end" do
assert_equal "hell", "hello".to(-2)
end
@@ -380,17 +387,17 @@ class StringAccessTest < ActiveSupport::TestCase
test "#first returns the first character" do
assert_equal "h", "hello".first
- assert_equal 'x', 'x'.first
+ assert_equal "x", "x".first
end
- test "#first with Fixnum, returns a substring from the beginning to position" do
+ test "#first with Integer, returns a substring from the beginning to position" do
assert_equal "he", "hello".first(2)
assert_equal "", "hello".first(0)
assert_equal "hello", "hello".first(10)
- assert_equal 'x', 'x'.first(4)
+ assert_equal "x", "x".first(4)
end
- test "#first with Fixnum >= string length still returns a new string" do
+ test "#first with Integer >= string length still returns a new string" do
string = "hello"
different_string = string.first(5)
assert_not_same different_string, string
@@ -398,17 +405,17 @@ class StringAccessTest < ActiveSupport::TestCase
test "#last returns the last character" do
assert_equal "o", "hello".last
- assert_equal 'x', 'x'.last
+ assert_equal "x", "x".last
end
- test "#last with Fixnum, returns a substring from the end to position" do
+ test "#last with Integer, returns a substring from the end to position" do
assert_equal "llo", "hello".last(3)
assert_equal "hello", "hello".last(10)
assert_equal "", "hello".last(0)
- assert_equal 'x', 'x'.last(4)
+ assert_equal "x", "x".last(4)
end
- test "#last with Fixnum >= string length still returns a new string" do
+ test "#last with Integer >= string length still returns a new string" do
string = "hello"
different_string = string.last(5)
assert_not_same different_string, string
@@ -463,10 +470,17 @@ class StringConversionsTest < ActiveSupport::TestCase
def test_string_to_time_utc_offset
with_env_tz "US/Eastern" do
- assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
- assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
- assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
- assert_equal(-18000, "2005-02-27 22:50 -0100".to_time.utc_offset)
+ if ActiveSupport.to_time_preserves_timezone
+ assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
+ assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
+ assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
+ assert_equal(-3600, "2005-02-27 22:50 -0100".to_time.utc_offset)
+ else
+ assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
+ assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
+ assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
+ assert_equal(-18000, "2005-02-27 22:50 -0100".to_time.utc_offset)
+ end
end
end
@@ -625,14 +639,14 @@ end
class StringBehaviourTest < ActiveSupport::TestCase
def test_acts_like_string
- assert 'Bambi'.acts_like_string?
+ assert "Bambi".acts_like_string?
end
end
class CoreExtStringMultibyteTest < ActiveSupport::TestCase
- UTF8_STRING = 'こにちわ'
- ASCII_STRING = 'ohayo'.encode('US-ASCII')
- EUC_JP_STRING = 'さよなら'.encode('EUC-JP')
+ UTF8_STRING = "こにちわ"
+ ASCII_STRING = "ohayo".encode("US-ASCII")
+ EUC_JP_STRING = "さよなら".encode("EUC-JP")
INVALID_UTF8_STRING = "\270\236\010\210\245"
def test_core_ext_adds_mb_chars
@@ -653,7 +667,7 @@ end
class OutputSafetyTest < ActiveSupport::TestCase
def setup
- @string = "hello"
+ @string = "hello".dup
@object = Class.new(Object) do
def to_s
"other"
@@ -674,7 +688,7 @@ class OutputSafetyTest < ActiveSupport::TestCase
assert_equal @string, @string.html_safe
end
- test "A fixnum is safe by default" do
+ test "An integer is safe by default" do
assert 5.html_safe?
end
@@ -718,18 +732,18 @@ class OutputSafetyTest < ActiveSupport::TestCase
test "Prepending safe onto unsafe yields unsafe" do
@string.prepend "other".html_safe
assert !@string.html_safe?
- assert_equal @string, "otherhello"
+ assert_equal "otherhello", @string
end
test "Prepending unsafe onto safe yields escaped safe" do
other = "other".html_safe
other.prepend "<foo>"
assert other.html_safe?
- assert_equal other, "&lt;foo&gt;other"
+ assert_equal "&lt;foo&gt;other", other
end
test "Concatting safe onto unsafe yields unsafe" do
- @other_string = "other"
+ @other_string = "other".dup
string = @string.html_safe
@other_string.concat(string)
@@ -752,7 +766,7 @@ class OutputSafetyTest < ActiveSupport::TestCase
end
test "Concatting safe onto unsafe with << yields unsafe" do
- @other_string = "other"
+ @other_string = "other".dup
string = @string.html_safe
@other_string << string
@@ -805,15 +819,15 @@ class OutputSafetyTest < ActiveSupport::TestCase
assert_equal ["<p>", "<b>", "<h1>"], @other_string
end
- test "Concatting a fixnum to safe always yields safe" do
+ test "Concatting an integer to safe always yields safe" do
string = @string.html_safe
string = string.concat(13)
- assert_equal "hello".concat(13), string
+ assert_equal "hello".dup.concat(13), string
assert string.html_safe?
end
- test 'emits normal string yaml' do
- assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1)
+ test "emits normal string yaml" do
+ assert_equal "foo".to_yaml, "foo".html_safe.to_yaml(foo: 1)
end
test "call to_param returns a normal string" do
@@ -824,7 +838,7 @@ class OutputSafetyTest < ActiveSupport::TestCase
test "ERB::Util.html_escape should escape unsafe characters" do
string = '<>&"\''
- expected = '&lt;&gt;&amp;&quot;&#39;'
+ expected = "&lt;&gt;&amp;&quot;&#39;"
assert_equal expected, ERB::Util.html_escape(string)
end
@@ -840,7 +854,7 @@ class OutputSafetyTest < ActiveSupport::TestCase
end
test "ERB::Util.html_escape_once only escapes once" do
- string = '1 < 2 &amp; 3'
+ string = "1 < 2 &amp; 3"
escaped_string = "1 &lt; 2 &amp; 3"
assert_equal escaped_string, ERB::Util.html_escape_once(string)
@@ -855,15 +869,16 @@ class OutputSafetyTest < ActiveSupport::TestCase
end
class StringExcludeTest < ActiveSupport::TestCase
- test 'inverse of #include' do
- assert_equal false, 'foo'.exclude?('o')
- assert_equal true, 'foo'.exclude?('p')
+ test "inverse of #include" do
+ assert_equal false, "foo".exclude?("o")
+ assert_equal true, "foo".exclude?("p")
end
end
class StringIndentTest < ActiveSupport::TestCase
- test 'does not indent strings that only contain newlines (edge cases)' do
- ['', "\n", "\n" * 7].each do |str|
+ test "does not indent strings that only contain newlines (edge cases)" do
+ ["", "\n", "\n" * 7].each do |string|
+ str = string.dup
assert_nil str.indent!(8)
assert_equal str, str.indent(8)
assert_equal str, str.indent(1, "\t")
@@ -885,8 +900,8 @@ class StringIndentTest < ActiveSupport::TestCase
# Nothing is said about existing indentation that mixes spaces and tabs, so
# there is nothing to test.
- test 'uses the indent char if passed' do
- assert_equal <<EXPECTED, <<ACTUAL.indent(4, '.')
+ test "uses the indent char if passed" do
+ assert_equal <<EXPECTED, <<ACTUAL.indent(4, ".")
.... def some_method(x, y)
.... some_code
.... end
@@ -896,7 +911,7 @@ EXPECTED
end
ACTUAL
- assert_equal <<EXPECTED, <<ACTUAL.indent(2, '&nbsp;')
+ assert_equal <<EXPECTED, <<ACTUAL.indent(2, "&nbsp;")
&nbsp;&nbsp;&nbsp;&nbsp;def some_method(x, y)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;some_code
&nbsp;&nbsp;&nbsp;&nbsp;end
@@ -911,7 +926,7 @@ ACTUAL
assert_equal " foo\n\n bar", "foo\n\nbar".indent(1)
end
- test 'indents blank lines if told so' do
+ test "indents blank lines if told so" do
assert_equal " foo\n \n bar", "foo\n\nbar".indent(1, nil, true)
end
end
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index 1205797fac..01cf1938be 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -1,541 +1,546 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'core_ext/date_and_time_behavior'
-require 'time_zone_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "core_ext/date_and_time_behavior"
+require "time_zone_test_helpers"
class TimeExtCalculationsTest < ActiveSupport::TestCase
- def date_time_init(year,month,day,hour,minute,second,usec=0)
- Time.local(year,month,day,hour,minute,second,usec)
+ def date_time_init(year, month, day, hour, minute, second, usec = 0)
+ Time.local(year, month, day, hour, minute, second, usec)
end
include DateAndTimeBehavior
include TimeZoneTestHelpers
def test_seconds_since_midnight
- assert_equal 1,Time.local(2005,1,1,0,0,1).seconds_since_midnight
- assert_equal 60,Time.local(2005,1,1,0,1,0).seconds_since_midnight
- assert_equal 3660,Time.local(2005,1,1,1,1,0).seconds_since_midnight
- assert_equal 86399,Time.local(2005,1,1,23,59,59).seconds_since_midnight
- assert_equal 60.00001,Time.local(2005,1,1,0,1,0,10).seconds_since_midnight
+ assert_equal 1, Time.local(2005, 1, 1, 0, 0, 1).seconds_since_midnight
+ assert_equal 60, Time.local(2005, 1, 1, 0, 1, 0).seconds_since_midnight
+ assert_equal 3660, Time.local(2005, 1, 1, 1, 1, 0).seconds_since_midnight
+ assert_equal 86399, Time.local(2005, 1, 1, 23, 59, 59).seconds_since_midnight
+ assert_equal 60.00001, Time.local(2005, 1, 1, 0, 1, 0, 10).seconds_since_midnight
end
def test_seconds_since_midnight_at_daylight_savings_time_start
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 April 3rd 2:00am ST => April 3rd 3:00am DT
- assert_equal 2*3600-1, Time.local(2005,4,3,1,59,59).seconds_since_midnight, 'just before DST start'
- assert_equal 2*3600+1, Time.local(2005,4,3,3, 0, 1).seconds_since_midnight, 'just after DST start'
+ assert_equal 2 * 3600 - 1, Time.local(2005, 4, 3, 1, 59, 59).seconds_since_midnight, "just before DST start"
+ assert_equal 2 * 3600 + 1, Time.local(2005, 4, 3, 3, 0, 1).seconds_since_midnight, "just after DST start"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 October 1st 2:00am ST => October 1st 3:00am DT
- assert_equal 2*3600-1, Time.local(2006,10,1,1,59,59).seconds_since_midnight, 'just before DST start'
- assert_equal 2*3600+1, Time.local(2006,10,1,3, 0, 1).seconds_since_midnight, 'just after DST start'
+ assert_equal 2 * 3600 - 1, Time.local(2006, 10, 1, 1, 59, 59).seconds_since_midnight, "just before DST start"
+ assert_equal 2 * 3600 + 1, Time.local(2006, 10, 1, 3, 0, 1).seconds_since_midnight, "just after DST start"
end
end
def test_seconds_since_midnight_at_daylight_savings_time_end
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 October 30th 2:00am DT => October 30th 1:00am ST
# avoid setting a time between 1:00 and 2:00 since that requires specifying whether DST is active
- assert_equal 1*3600-1, Time.local(2005,10,30,0,59,59).seconds_since_midnight, 'just before DST end'
- assert_equal 3*3600+1, Time.local(2005,10,30,2, 0, 1).seconds_since_midnight, 'just after DST end'
+ assert_equal 1 * 3600 - 1, Time.local(2005, 10, 30, 0, 59, 59).seconds_since_midnight, "just before DST end"
+ assert_equal 3 * 3600 + 1, Time.local(2005, 10, 30, 2, 0, 1).seconds_since_midnight, "just after DST end"
# now set a time between 1:00 and 2:00 by specifying whether DST is active
# uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
- assert_equal 1*3600+30*60, Time.local(0,30,1,30,10,2005,0,0,true,ENV['TZ']).seconds_since_midnight, 'before DST end'
- assert_equal 2*3600+30*60, Time.local(0,30,1,30,10,2005,0,0,false,ENV['TZ']).seconds_since_midnight, 'after DST end'
+ assert_equal 1 * 3600 + 30 * 60, Time.local(0, 30, 1, 30, 10, 2005, 0, 0, true, ENV["TZ"]).seconds_since_midnight, "before DST end"
+ assert_equal 2 * 3600 + 30 * 60, Time.local(0, 30, 1, 30, 10, 2005, 0, 0, false, ENV["TZ"]).seconds_since_midnight, "after DST end"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 March 19th 3:00am DT => March 19th 2:00am ST
# avoid setting a time between 2:00 and 3:00 since that requires specifying whether DST is active
- assert_equal 2*3600-1, Time.local(2006,3,19,1,59,59).seconds_since_midnight, 'just before DST end'
- assert_equal 4*3600+1, Time.local(2006,3,19,3, 0, 1).seconds_since_midnight, 'just after DST end'
+ assert_equal 2 * 3600 - 1, Time.local(2006, 3, 19, 1, 59, 59).seconds_since_midnight, "just before DST end"
+ assert_equal 4 * 3600 + 1, Time.local(2006, 3, 19, 3, 0, 1).seconds_since_midnight, "just after DST end"
# now set a time between 2:00 and 3:00 by specifying whether DST is active
# uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
- assert_equal 2*3600+30*60, Time.local(0,30,2,19,3,2006,0,0,true, ENV['TZ']).seconds_since_midnight, 'before DST end'
- assert_equal 3*3600+30*60, Time.local(0,30,2,19,3,2006,0,0,false,ENV['TZ']).seconds_since_midnight, 'after DST end'
+ assert_equal 2 * 3600 + 30 * 60, Time.local(0, 30, 2, 19, 3, 2006, 0, 0, true, ENV["TZ"]).seconds_since_midnight, "before DST end"
+ assert_equal 3 * 3600 + 30 * 60, Time.local(0, 30, 2, 19, 3, 2006, 0, 0, false, ENV["TZ"]).seconds_since_midnight, "after DST end"
end
end
def test_seconds_until_end_of_day
- assert_equal 0, Time.local(2005,1,1,23,59,59).seconds_until_end_of_day
- assert_equal 1, Time.local(2005,1,1,23,59,58).seconds_until_end_of_day
- assert_equal 60, Time.local(2005,1,1,23,58,59).seconds_until_end_of_day
- assert_equal 3660, Time.local(2005,1,1,22,58,59).seconds_until_end_of_day
- assert_equal 86399, Time.local(2005,1,1,0,0,0).seconds_until_end_of_day
+ assert_equal 0, Time.local(2005, 1, 1, 23, 59, 59).seconds_until_end_of_day
+ assert_equal 1, Time.local(2005, 1, 1, 23, 59, 58).seconds_until_end_of_day
+ assert_equal 60, Time.local(2005, 1, 1, 23, 58, 59).seconds_until_end_of_day
+ assert_equal 3660, Time.local(2005, 1, 1, 22, 58, 59).seconds_until_end_of_day
+ assert_equal 86399, Time.local(2005, 1, 1, 0, 0, 0).seconds_until_end_of_day
end
def test_seconds_until_end_of_day_at_daylight_savings_time_start
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 April 3rd 2:00am ST => April 3rd 3:00am DT
- assert_equal 21*3600, Time.local(2005,4,3,1,59,59).seconds_until_end_of_day, 'just before DST start'
- assert_equal 21*3600-2, Time.local(2005,4,3,3,0,1).seconds_until_end_of_day, 'just after DST start'
+ assert_equal 21 * 3600, Time.local(2005, 4, 3, 1, 59, 59).seconds_until_end_of_day, "just before DST start"
+ assert_equal 21 * 3600 - 2, Time.local(2005, 4, 3, 3, 0, 1).seconds_until_end_of_day, "just after DST start"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 October 1st 2:00am ST => October 1st 3:00am DT
- assert_equal 21*3600, Time.local(2006,10,1,1,59,59).seconds_until_end_of_day, 'just before DST start'
- assert_equal 21*3600-2, Time.local(2006,10,1,3,0,1).seconds_until_end_of_day, 'just after DST start'
+ assert_equal 21 * 3600, Time.local(2006, 10, 1, 1, 59, 59).seconds_until_end_of_day, "just before DST start"
+ assert_equal 21 * 3600 - 2, Time.local(2006, 10, 1, 3, 0, 1).seconds_until_end_of_day, "just after DST start"
end
end
def test_seconds_until_end_of_day_at_daylight_savings_time_end
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 October 30th 2:00am DT => October 30th 1:00am ST
# avoid setting a time between 1:00 and 2:00 since that requires specifying whether DST is active
- assert_equal 24*3600, Time.local(2005,10,30,0,59,59).seconds_until_end_of_day, 'just before DST end'
- assert_equal 22*3600-2, Time.local(2005,10,30,2,0,1).seconds_until_end_of_day, 'just after DST end'
+ assert_equal 24 * 3600, Time.local(2005, 10, 30, 0, 59, 59).seconds_until_end_of_day, "just before DST end"
+ assert_equal 22 * 3600 - 2, Time.local(2005, 10, 30, 2, 0, 1).seconds_until_end_of_day, "just after DST end"
# now set a time between 1:00 and 2:00 by specifying whether DST is active
# uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
- assert_equal 24*3600-30*60-1, Time.local(0,30,1,30,10,2005,0,0,true,ENV['TZ']).seconds_until_end_of_day, 'before DST end'
- assert_equal 23*3600-30*60-1, Time.local(0,30,1,30,10,2005,0,0,false,ENV['TZ']).seconds_until_end_of_day, 'after DST end'
+ assert_equal 24 * 3600 - 30 * 60 - 1, Time.local(0, 30, 1, 30, 10, 2005, 0, 0, true, ENV["TZ"]).seconds_until_end_of_day, "before DST end"
+ assert_equal 23 * 3600 - 30 * 60 - 1, Time.local(0, 30, 1, 30, 10, 2005, 0, 0, false, ENV["TZ"]).seconds_until_end_of_day, "after DST end"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 March 19th 3:00am DT => March 19th 2:00am ST
# avoid setting a time between 2:00 and 3:00 since that requires specifying whether DST is active
- assert_equal 23*3600, Time.local(2006,3,19,1,59,59).seconds_until_end_of_day, 'just before DST end'
- assert_equal 21*3600-2, Time.local(2006,3,19,3,0,1).seconds_until_end_of_day, 'just after DST end'
+ assert_equal 23 * 3600, Time.local(2006, 3, 19, 1, 59, 59).seconds_until_end_of_day, "just before DST end"
+ assert_equal 21 * 3600 - 2, Time.local(2006, 3, 19, 3, 0, 1).seconds_until_end_of_day, "just after DST end"
# now set a time between 2:00 and 3:00 by specifying whether DST is active
# uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
- assert_equal 23*3600-30*60-1, Time.local(0,30,2,19,3,2006,0,0,true, ENV['TZ']).seconds_until_end_of_day, 'before DST end'
- assert_equal 22*3600-30*60-1, Time.local(0,30,2,19,3,2006,0,0,false,ENV['TZ']).seconds_until_end_of_day, 'after DST end'
+ assert_equal 23 * 3600 - 30 * 60 - 1, Time.local(0, 30, 2, 19, 3, 2006, 0, 0, true, ENV["TZ"]).seconds_until_end_of_day, "before DST end"
+ assert_equal 22 * 3600 - 30 * 60 - 1, Time.local(0, 30, 2, 19, 3, 2006, 0, 0, false, ENV["TZ"]).seconds_until_end_of_day, "after DST end"
end
end
def test_sec_fraction
- time = Time.utc(2016, 4, 23, 0, 0, Rational(1,10000000000))
- assert_equal Rational(1,10000000000), time.sec_fraction
+ time = Time.utc(2016, 4, 23, 0, 0, Rational(1, 10000000000))
+ assert_equal Rational(1, 10000000000), time.sec_fraction
time = Time.utc(2016, 4, 23, 0, 0, 0.0000000001)
assert_equal 0.0000000001.to_r, time.sec_fraction
- time = Time.utc(2016, 4, 23, 0, 0, 0, Rational(1,10000))
- assert_equal Rational(1,10000000000), time.sec_fraction
+ time = Time.utc(2016, 4, 23, 0, 0, 0, Rational(1, 10000))
+ assert_equal Rational(1, 10000000000), time.sec_fraction
time = Time.utc(2016, 4, 23, 0, 0, 0, 0.0001)
assert_equal 0.0001.to_r / 1000000, time.sec_fraction
end
def test_beginning_of_day
- assert_equal Time.local(2005,2,4,0,0,0), Time.local(2005,2,4,10,10,10).beginning_of_day
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2006,4,2,0,0,0), Time.local(2006,4,2,10,10,10).beginning_of_day, 'start DST'
- assert_equal Time.local(2006,10,29,0,0,0), Time.local(2006,10,29,10,10,10).beginning_of_day, 'ends DST'
+ assert_equal Time.local(2005, 2, 4, 0, 0, 0), Time.local(2005, 2, 4, 10, 10, 10).beginning_of_day
+ with_env_tz "US/Eastern" do
+ assert_equal Time.local(2006, 4, 2, 0, 0, 0), Time.local(2006, 4, 2, 10, 10, 10).beginning_of_day, "start DST"
+ assert_equal Time.local(2006, 10, 29, 0, 0, 0), Time.local(2006, 10, 29, 10, 10, 10).beginning_of_day, "ends DST"
end
- with_env_tz 'NZ' do
- assert_equal Time.local(2006,3,19,0,0,0), Time.local(2006,3,19,10,10,10).beginning_of_day, 'ends DST'
- assert_equal Time.local(2006,10,1,0,0,0), Time.local(2006,10,1,10,10,10).beginning_of_day, 'start DST'
+ with_env_tz "NZ" do
+ assert_equal Time.local(2006, 3, 19, 0, 0, 0), Time.local(2006, 3, 19, 10, 10, 10).beginning_of_day, "ends DST"
+ assert_equal Time.local(2006, 10, 1, 0, 0, 0), Time.local(2006, 10, 1, 10, 10, 10).beginning_of_day, "start DST"
end
end
def test_middle_of_day
- assert_equal Time.local(2005,2,4,12,0,0), Time.local(2005,2,4,10,10,10).middle_of_day
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2006,4,2,12,0,0), Time.local(2006,4,2,10,10,10).middle_of_day, 'start DST'
- assert_equal Time.local(2006,10,29,12,0,0), Time.local(2006,10,29,10,10,10).middle_of_day, 'ends DST'
+ assert_equal Time.local(2005, 2, 4, 12, 0, 0), Time.local(2005, 2, 4, 10, 10, 10).middle_of_day
+ with_env_tz "US/Eastern" do
+ assert_equal Time.local(2006, 4, 2, 12, 0, 0), Time.local(2006, 4, 2, 10, 10, 10).middle_of_day, "start DST"
+ assert_equal Time.local(2006, 10, 29, 12, 0, 0), Time.local(2006, 10, 29, 10, 10, 10).middle_of_day, "ends DST"
end
- with_env_tz 'NZ' do
- assert_equal Time.local(2006,3,19,12,0,0), Time.local(2006,3,19,10,10,10).middle_of_day, 'ends DST'
- assert_equal Time.local(2006,10,1,12,0,0), Time.local(2006,10,1,10,10,10).middle_of_day, 'start DST'
+ with_env_tz "NZ" do
+ assert_equal Time.local(2006, 3, 19, 12, 0, 0), Time.local(2006, 3, 19, 10, 10, 10).middle_of_day, "ends DST"
+ assert_equal Time.local(2006, 10, 1, 12, 0, 0), Time.local(2006, 10, 1, 10, 10, 10).middle_of_day, "start DST"
end
end
def test_beginning_of_hour
- assert_equal Time.local(2005,2,4,19,0,0), Time.local(2005,2,4,19,30,10).beginning_of_hour
+ assert_equal Time.local(2005, 2, 4, 19, 0, 0), Time.local(2005, 2, 4, 19, 30, 10).beginning_of_hour
end
def test_beginning_of_minute
- assert_equal Time.local(2005,2,4,19,30,0), Time.local(2005,2,4,19,30,10).beginning_of_minute
+ assert_equal Time.local(2005, 2, 4, 19, 30, 0), Time.local(2005, 2, 4, 19, 30, 10).beginning_of_minute
end
def test_end_of_day
- assert_equal Time.local(2007,8,12,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,12,10,10,10).end_of_day
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2007,4,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,4,2,10,10,10).end_of_day, 'start DST'
- assert_equal Time.local(2007,10,29,23,59,59,Rational(999999999, 1000)), Time.local(2007,10,29,10,10,10).end_of_day, 'ends DST'
+ assert_equal Time.local(2007, 8, 12, 23, 59, 59, Rational(999999999, 1000)), Time.local(2007, 8, 12, 10, 10, 10).end_of_day
+ with_env_tz "US/Eastern" do
+ assert_equal Time.local(2007, 4, 2, 23, 59, 59, Rational(999999999, 1000)), Time.local(2007, 4, 2, 10, 10, 10).end_of_day, "start DST"
+ assert_equal Time.local(2007, 10, 29, 23, 59, 59, Rational(999999999, 1000)), Time.local(2007, 10, 29, 10, 10, 10).end_of_day, "ends DST"
end
- with_env_tz 'NZ' do
- assert_equal Time.local(2006,3,19,23,59,59,Rational(999999999, 1000)), Time.local(2006,3,19,10,10,10).end_of_day, 'ends DST'
- assert_equal Time.local(2006,10,1,23,59,59,Rational(999999999, 1000)), Time.local(2006,10,1,10,10,10).end_of_day, 'start DST'
+ with_env_tz "NZ" do
+ assert_equal Time.local(2006, 3, 19, 23, 59, 59, Rational(999999999, 1000)), Time.local(2006, 3, 19, 10, 10, 10).end_of_day, "ends DST"
+ assert_equal Time.local(2006, 10, 1, 23, 59, 59, Rational(999999999, 1000)), Time.local(2006, 10, 1, 10, 10, 10).end_of_day, "start DST"
end
- with_env_tz 'Asia/Yekaterinburg' do
- assert_equal Time.local(2015, 2, 8, 23, 59, 59, Rational(999999999, 1000)), Time.new(2015, 2, 8, 8, 0, 0, '+05:00').end_of_day
+ with_env_tz "Asia/Yekaterinburg" do
+ assert_equal Time.local(2015, 2, 8, 23, 59, 59, Rational(999999999, 1000)), Time.new(2015, 2, 8, 8, 0, 0, "+05:00").end_of_day
end
end
def test_end_of_hour
- assert_equal Time.local(2005,2,4,19,59,59,Rational(999999999, 1000)), Time.local(2005,2,4,19,30,10).end_of_hour
+ assert_equal Time.local(2005, 2, 4, 19, 59, 59, Rational(999999999, 1000)), Time.local(2005, 2, 4, 19, 30, 10).end_of_hour
end
def test_end_of_minute
- assert_equal Time.local(2005,2,4,19,30,59,Rational(999999999, 1000)), Time.local(2005,2,4,19,30,10).end_of_minute
- end
-
- def test_last_year
- assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).last_year
+ assert_equal Time.local(2005, 2, 4, 19, 30, 59, Rational(999999999, 1000)), Time.local(2005, 2, 4, 19, 30, 10).end_of_minute
end
def test_ago
- assert_equal Time.local(2005,2,22,10,10,9), Time.local(2005,2,22,10,10,10).ago(1)
- assert_equal Time.local(2005,2,22,9,10,10), Time.local(2005,2,22,10,10,10).ago(3600)
- assert_equal Time.local(2005,2,20,10,10,10), Time.local(2005,2,22,10,10,10).ago(86400*2)
- assert_equal Time.local(2005,2,20,9,9,45), Time.local(2005,2,22,10,10,10).ago(86400*2 + 3600 + 25)
+ assert_equal Time.local(2005, 2, 22, 10, 10, 9), Time.local(2005, 2, 22, 10, 10, 10).ago(1)
+ assert_equal Time.local(2005, 2, 22, 9, 10, 10), Time.local(2005, 2, 22, 10, 10, 10).ago(3600)
+ assert_equal Time.local(2005, 2, 20, 10, 10, 10), Time.local(2005, 2, 22, 10, 10, 10).ago(86400 * 2)
+ assert_equal Time.local(2005, 2, 20, 9, 9, 45), Time.local(2005, 2, 22, 10, 10, 10).ago(86400 * 2 + 3600 + 25)
end
def test_daylight_savings_time_crossings_backward_start
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 April 3rd 4:18am
- assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0).ago(24.hours), 'dt-24.hours=>st'
- assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0).ago(86400), 'dt-86400=>st'
- assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0).ago(86400.seconds), 'dt-86400.seconds=>st'
+ assert_equal Time.local(2005, 4, 2, 3, 18, 0), Time.local(2005, 4, 3, 4, 18, 0).ago(24.hours), "dt-24.hours=>st"
+ assert_equal Time.local(2005, 4, 2, 3, 18, 0), Time.local(2005, 4, 3, 4, 18, 0).ago(86400), "dt-86400=>st"
+ assert_equal Time.local(2005, 4, 2, 3, 18, 0), Time.local(2005, 4, 3, 4, 18, 0).ago(86400.seconds), "dt-86400.seconds=>st"
- assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(24.hours), 'st-24.hours=>st'
- assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(86400), 'st-86400=>st'
- assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(86400.seconds), 'st-86400.seconds=>st'
+ assert_equal Time.local(2005, 4, 1, 4, 18, 0), Time.local(2005, 4, 2, 4, 18, 0).ago(24.hours), "st-24.hours=>st"
+ assert_equal Time.local(2005, 4, 1, 4, 18, 0), Time.local(2005, 4, 2, 4, 18, 0).ago(86400), "st-86400=>st"
+ assert_equal Time.local(2005, 4, 1, 4, 18, 0), Time.local(2005, 4, 2, 4, 18, 0).ago(86400.seconds), "st-86400.seconds=>st"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 October 1st 4:18am
- assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0).ago(24.hours), 'dt-24.hours=>st'
- assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0).ago(86400), 'dt-86400=>st'
- assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0).ago(86400.seconds), 'dt-86400.seconds=>st'
+ assert_equal Time.local(2006, 9, 30, 3, 18, 0), Time.local(2006, 10, 1, 4, 18, 0).ago(24.hours), "dt-24.hours=>st"
+ assert_equal Time.local(2006, 9, 30, 3, 18, 0), Time.local(2006, 10, 1, 4, 18, 0).ago(86400), "dt-86400=>st"
+ assert_equal Time.local(2006, 9, 30, 3, 18, 0), Time.local(2006, 10, 1, 4, 18, 0).ago(86400.seconds), "dt-86400.seconds=>st"
- assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(24.hours), 'st-24.hours=>st'
- assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(86400), 'st-86400=>st'
- assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(86400.seconds), 'st-86400.seconds=>st'
+ assert_equal Time.local(2006, 9, 29, 4, 18, 0), Time.local(2006, 9, 30, 4, 18, 0).ago(24.hours), "st-24.hours=>st"
+ assert_equal Time.local(2006, 9, 29, 4, 18, 0), Time.local(2006, 9, 30, 4, 18, 0).ago(86400), "st-86400=>st"
+ assert_equal Time.local(2006, 9, 29, 4, 18, 0), Time.local(2006, 9, 30, 4, 18, 0).ago(86400.seconds), "st-86400.seconds=>st"
end
end
def test_daylight_savings_time_crossings_backward_end
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 October 30th 4:03am
- assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0).ago(24.hours), 'st-24.hours=>dt'
- assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0).ago(86400), 'st-86400=>dt'
- assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0).ago(86400.seconds), 'st-86400.seconds=>dt'
+ assert_equal Time.local(2005, 10, 29, 5, 3), Time.local(2005, 10, 30, 4, 3, 0).ago(24.hours), "st-24.hours=>dt"
+ assert_equal Time.local(2005, 10, 29, 5, 3), Time.local(2005, 10, 30, 4, 3, 0).ago(86400), "st-86400=>dt"
+ assert_equal Time.local(2005, 10, 29, 5, 3), Time.local(2005, 10, 30, 4, 3, 0).ago(86400.seconds), "st-86400.seconds=>dt"
- assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(24.hours), 'dt-24.hours=>dt'
- assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(86400), 'dt-86400=>dt'
- assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(86400.seconds), 'dt-86400.seconds=>dt'
+ assert_equal Time.local(2005, 10, 28, 4, 3), Time.local(2005, 10, 29, 4, 3, 0).ago(24.hours), "dt-24.hours=>dt"
+ assert_equal Time.local(2005, 10, 28, 4, 3), Time.local(2005, 10, 29, 4, 3, 0).ago(86400), "dt-86400=>dt"
+ assert_equal Time.local(2005, 10, 28, 4, 3), Time.local(2005, 10, 29, 4, 3, 0).ago(86400.seconds), "dt-86400.seconds=>dt"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 March 19th 4:03am
- assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0).ago(24.hours), 'st-24.hours=>dt'
- assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0).ago(86400), 'st-86400=>dt'
- assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0).ago(86400.seconds), 'st-86400.seconds=>dt'
+ assert_equal Time.local(2006, 3, 18, 5, 3), Time.local(2006, 3, 19, 4, 3, 0).ago(24.hours), "st-24.hours=>dt"
+ assert_equal Time.local(2006, 3, 18, 5, 3), Time.local(2006, 3, 19, 4, 3, 0).ago(86400), "st-86400=>dt"
+ assert_equal Time.local(2006, 3, 18, 5, 3), Time.local(2006, 3, 19, 4, 3, 0).ago(86400.seconds), "st-86400.seconds=>dt"
- assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(24.hours), 'dt-24.hours=>dt'
- assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(86400), 'dt-86400=>dt'
- assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(86400.seconds), 'dt-86400.seconds=>dt'
+ assert_equal Time.local(2006, 3, 17, 4, 3), Time.local(2006, 3, 18, 4, 3, 0).ago(24.hours), "dt-24.hours=>dt"
+ assert_equal Time.local(2006, 3, 17, 4, 3), Time.local(2006, 3, 18, 4, 3, 0).ago(86400), "dt-86400=>dt"
+ assert_equal Time.local(2006, 3, 17, 4, 3), Time.local(2006, 3, 18, 4, 3, 0).ago(86400.seconds), "dt-86400.seconds=>dt"
end
end
def test_daylight_savings_time_crossings_backward_start_1day
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 April 3rd 4:18am
- assert_equal Time.local(2005,4,2,4,18,0), Time.local(2005,4,3,4,18,0).ago(1.day), 'dt-1.day=>st'
- assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(1.day), 'st-1.day=>st'
+ assert_equal Time.local(2005, 4, 2, 4, 18, 0), Time.local(2005, 4, 3, 4, 18, 0).ago(1.day), "dt-1.day=>st"
+ assert_equal Time.local(2005, 4, 1, 4, 18, 0), Time.local(2005, 4, 2, 4, 18, 0).ago(1.day), "st-1.day=>st"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 October 1st 4:18am
- assert_equal Time.local(2006,9,30,4,18,0), Time.local(2006,10,1,4,18,0).ago(1.day), 'dt-1.day=>st'
- assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(1.day), 'st-1.day=>st'
+ assert_equal Time.local(2006, 9, 30, 4, 18, 0), Time.local(2006, 10, 1, 4, 18, 0).ago(1.day), "dt-1.day=>st"
+ assert_equal Time.local(2006, 9, 29, 4, 18, 0), Time.local(2006, 9, 30, 4, 18, 0).ago(1.day), "st-1.day=>st"
end
end
def test_daylight_savings_time_crossings_backward_end_1day
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 October 30th 4:03am
- assert_equal Time.local(2005,10,29,4,3), Time.local(2005,10,30,4,3,0).ago(1.day), 'st-1.day=>dt'
- assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(1.day), 'dt-1.day=>dt'
+ assert_equal Time.local(2005, 10, 29, 4, 3), Time.local(2005, 10, 30, 4, 3, 0).ago(1.day), "st-1.day=>dt"
+ assert_equal Time.local(2005, 10, 28, 4, 3), Time.local(2005, 10, 29, 4, 3, 0).ago(1.day), "dt-1.day=>dt"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 March 19th 4:03am
- assert_equal Time.local(2006,3,18,4,3), Time.local(2006,3,19,4,3,0).ago(1.day), 'st-1.day=>dt'
- assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(1.day), 'dt-1.day=>dt'
+ assert_equal Time.local(2006, 3, 18, 4, 3), Time.local(2006, 3, 19, 4, 3, 0).ago(1.day), "st-1.day=>dt"
+ assert_equal Time.local(2006, 3, 17, 4, 3), Time.local(2006, 3, 18, 4, 3, 0).ago(1.day), "dt-1.day=>dt"
end
end
def test_since
- assert_equal Time.local(2005,2,22,10,10,11), Time.local(2005,2,22,10,10,10).since(1)
- assert_equal Time.local(2005,2,22,11,10,10), Time.local(2005,2,22,10,10,10).since(3600)
- assert_equal Time.local(2005,2,24,10,10,10), Time.local(2005,2,22,10,10,10).since(86400*2)
- assert_equal Time.local(2005,2,24,11,10,35), Time.local(2005,2,22,10,10,10).since(86400*2 + 3600 + 25)
+ assert_equal Time.local(2005, 2, 22, 10, 10, 11), Time.local(2005, 2, 22, 10, 10, 10).since(1)
+ assert_equal Time.local(2005, 2, 22, 11, 10, 10), Time.local(2005, 2, 22, 10, 10, 10).since(3600)
+ assert_equal Time.local(2005, 2, 24, 10, 10, 10), Time.local(2005, 2, 22, 10, 10, 10).since(86400 * 2)
+ assert_equal Time.local(2005, 2, 24, 11, 10, 35), Time.local(2005, 2, 22, 10, 10, 10).since(86400 * 2 + 3600 + 25)
# when out of range of Time, returns a DateTime
- assert_equal DateTime.civil(2038,1,20,11,59,59), Time.utc(2038,1,18,11,59,59).since(86400*2)
+ assert_equal DateTime.civil(2038, 1, 20, 11, 59, 59), Time.utc(2038, 1, 18, 11, 59, 59).since(86400 * 2)
end
def test_daylight_savings_time_crossings_forward_start
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 April 2nd 7:27pm
- assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0).since(24.hours), 'st+24.hours=>dt'
- assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0).since(86400), 'st+86400=>dt'
- assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0).since(86400.seconds), 'st+86400.seconds=>dt'
+ assert_equal Time.local(2005, 4, 3, 20, 27, 0), Time.local(2005, 4, 2, 19, 27, 0).since(24.hours), "st+24.hours=>dt"
+ assert_equal Time.local(2005, 4, 3, 20, 27, 0), Time.local(2005, 4, 2, 19, 27, 0).since(86400), "st+86400=>dt"
+ assert_equal Time.local(2005, 4, 3, 20, 27, 0), Time.local(2005, 4, 2, 19, 27, 0).since(86400.seconds), "st+86400.seconds=>dt"
- assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(24.hours), 'dt+24.hours=>dt'
- assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(86400), 'dt+86400=>dt'
- assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(86400.seconds), 'dt+86400.seconds=>dt'
+ assert_equal Time.local(2005, 4, 4, 19, 27, 0), Time.local(2005, 4, 3, 19, 27, 0).since(24.hours), "dt+24.hours=>dt"
+ assert_equal Time.local(2005, 4, 4, 19, 27, 0), Time.local(2005, 4, 3, 19, 27, 0).since(86400), "dt+86400=>dt"
+ assert_equal Time.local(2005, 4, 4, 19, 27, 0), Time.local(2005, 4, 3, 19, 27, 0).since(86400.seconds), "dt+86400.seconds=>dt"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 September 30th 7:27pm
- assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0).since(24.hours), 'st+24.hours=>dt'
- assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0).since(86400), 'st+86400=>dt'
- assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0).since(86400.seconds), 'st+86400.seconds=>dt'
+ assert_equal Time.local(2006, 10, 1, 20, 27, 0), Time.local(2006, 9, 30, 19, 27, 0).since(24.hours), "st+24.hours=>dt"
+ assert_equal Time.local(2006, 10, 1, 20, 27, 0), Time.local(2006, 9, 30, 19, 27, 0).since(86400), "st+86400=>dt"
+ assert_equal Time.local(2006, 10, 1, 20, 27, 0), Time.local(2006, 9, 30, 19, 27, 0).since(86400.seconds), "st+86400.seconds=>dt"
- assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(24.hours), 'dt+24.hours=>dt'
- assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(86400), 'dt+86400=>dt'
- assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(86400.seconds), 'dt+86400.seconds=>dt'
+ assert_equal Time.local(2006, 10, 2, 19, 27, 0), Time.local(2006, 10, 1, 19, 27, 0).since(24.hours), "dt+24.hours=>dt"
+ assert_equal Time.local(2006, 10, 2, 19, 27, 0), Time.local(2006, 10, 1, 19, 27, 0).since(86400), "dt+86400=>dt"
+ assert_equal Time.local(2006, 10, 2, 19, 27, 0), Time.local(2006, 10, 1, 19, 27, 0).since(86400.seconds), "dt+86400.seconds=>dt"
end
end
def test_daylight_savings_time_crossings_forward_start_1day
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 April 2nd 7:27pm
- assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,2,19,27,0).since(1.day), 'st+1.day=>dt'
- assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(1.day), 'dt+1.day=>dt'
+ assert_equal Time.local(2005, 4, 3, 19, 27, 0), Time.local(2005, 4, 2, 19, 27, 0).since(1.day), "st+1.day=>dt"
+ assert_equal Time.local(2005, 4, 4, 19, 27, 0), Time.local(2005, 4, 3, 19, 27, 0).since(1.day), "dt+1.day=>dt"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 September 30th 7:27pm
- assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,9,30,19,27,0).since(1.day), 'st+1.day=>dt'
- assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(1.day), 'dt+1.day=>dt'
+ assert_equal Time.local(2006, 10, 1, 19, 27, 0), Time.local(2006, 9, 30, 19, 27, 0).since(1.day), "st+1.day=>dt"
+ assert_equal Time.local(2006, 10, 2, 19, 27, 0), Time.local(2006, 10, 1, 19, 27, 0).since(1.day), "dt+1.day=>dt"
end
end
def test_daylight_savings_time_crossings_forward_start_tomorrow
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 April 2nd 7:27pm
- assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,2,19,27,0).tomorrow, 'st+1.day=>dt'
- assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).tomorrow, 'dt+1.day=>dt'
+ assert_equal Time.local(2005, 4, 3, 19, 27, 0), Time.local(2005, 4, 2, 19, 27, 0).tomorrow, "st+1.day=>dt"
+ assert_equal Time.local(2005, 4, 4, 19, 27, 0), Time.local(2005, 4, 3, 19, 27, 0).tomorrow, "dt+1.day=>dt"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 September 30th 7:27pm
- assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,9,30,19,27,0).tomorrow, 'st+1.day=>dt'
- assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).tomorrow, 'dt+1.day=>dt'
+ assert_equal Time.local(2006, 10, 1, 19, 27, 0), Time.local(2006, 9, 30, 19, 27, 0).tomorrow, "st+1.day=>dt"
+ assert_equal Time.local(2006, 10, 2, 19, 27, 0), Time.local(2006, 10, 1, 19, 27, 0).tomorrow, "dt+1.day=>dt"
end
end
def test_daylight_savings_time_crossings_backward_start_yesterday
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# st: US: 2005 April 2nd 7:27pm
- assert_equal Time.local(2005,4,2,19,27,0), Time.local(2005,4,3,19,27,0).yesterday, 'dt-1.day=>st'
- assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,4,19,27,0).yesterday, 'dt-1.day=>dt'
+ assert_equal Time.local(2005, 4, 2, 19, 27, 0), Time.local(2005, 4, 3, 19, 27, 0).yesterday, "dt-1.day=>st"
+ assert_equal Time.local(2005, 4, 3, 19, 27, 0), Time.local(2005, 4, 4, 19, 27, 0).yesterday, "dt-1.day=>dt"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# st: New Zealand: 2006 September 30th 7:27pm
- assert_equal Time.local(2006,9,30,19,27,0), Time.local(2006,10,1,19,27,0).yesterday, 'dt-1.day=>st'
- assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,10,2,19,27,0).yesterday, 'dt-1.day=>dt'
+ assert_equal Time.local(2006, 9, 30, 19, 27, 0), Time.local(2006, 10, 1, 19, 27, 0).yesterday, "dt-1.day=>st"
+ assert_equal Time.local(2006, 10, 1, 19, 27, 0), Time.local(2006, 10, 2, 19, 27, 0).yesterday, "dt-1.day=>dt"
end
end
def test_daylight_savings_time_crossings_forward_end
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 October 30th 12:45am
- assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0).since(24.hours), 'dt+24.hours=>st'
- assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0).since(86400), 'dt+86400=>st'
- assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0).since(86400.seconds), 'dt+86400.seconds=>st'
+ assert_equal Time.local(2005, 10, 30, 23, 45, 0), Time.local(2005, 10, 30, 0, 45, 0).since(24.hours), "dt+24.hours=>st"
+ assert_equal Time.local(2005, 10, 30, 23, 45, 0), Time.local(2005, 10, 30, 0, 45, 0).since(86400), "dt+86400=>st"
+ assert_equal Time.local(2005, 10, 30, 23, 45, 0), Time.local(2005, 10, 30, 0, 45, 0).since(86400.seconds), "dt+86400.seconds=>st"
- assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(24.hours), 'st+24.hours=>st'
- assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(86400), 'st+86400=>st'
- assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(86400.seconds), 'st+86400.seconds=>st'
+ assert_equal Time.local(2005, 11, 1, 0, 45, 0), Time.local(2005, 10, 31, 0, 45, 0).since(24.hours), "st+24.hours=>st"
+ assert_equal Time.local(2005, 11, 1, 0, 45, 0), Time.local(2005, 10, 31, 0, 45, 0).since(86400), "st+86400=>st"
+ assert_equal Time.local(2005, 11, 1, 0, 45, 0), Time.local(2005, 10, 31, 0, 45, 0).since(86400.seconds), "st+86400.seconds=>st"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 March 19th 1:45am
- assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0).since(24.hours), 'dt+24.hours=>st'
- assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0).since(86400), 'dt+86400=>st'
- assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0).since(86400.seconds), 'dt+86400.seconds=>st'
+ assert_equal Time.local(2006, 3, 20, 0, 45, 0), Time.local(2006, 3, 19, 1, 45, 0).since(24.hours), "dt+24.hours=>st"
+ assert_equal Time.local(2006, 3, 20, 0, 45, 0), Time.local(2006, 3, 19, 1, 45, 0).since(86400), "dt+86400=>st"
+ assert_equal Time.local(2006, 3, 20, 0, 45, 0), Time.local(2006, 3, 19, 1, 45, 0).since(86400.seconds), "dt+86400.seconds=>st"
- assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(24.hours), 'st+24.hours=>st'
- assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(86400), 'st+86400=>st'
- assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(86400.seconds), 'st+86400.seconds=>st'
+ assert_equal Time.local(2006, 3, 21, 1, 45, 0), Time.local(2006, 3, 20, 1, 45, 0).since(24.hours), "st+24.hours=>st"
+ assert_equal Time.local(2006, 3, 21, 1, 45, 0), Time.local(2006, 3, 20, 1, 45, 0).since(86400), "st+86400=>st"
+ assert_equal Time.local(2006, 3, 21, 1, 45, 0), Time.local(2006, 3, 20, 1, 45, 0).since(86400.seconds), "st+86400.seconds=>st"
end
end
def test_daylight_savings_time_crossings_forward_end_1day
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 October 30th 12:45am
- assert_equal Time.local(2005,10,31,0,45,0), Time.local(2005,10,30,0,45,0).since(1.day), 'dt+1.day=>st'
- assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(1.day), 'st+1.day=>st'
+ assert_equal Time.local(2005, 10, 31, 0, 45, 0), Time.local(2005, 10, 30, 0, 45, 0).since(1.day), "dt+1.day=>st"
+ assert_equal Time.local(2005, 11, 1, 0, 45, 0), Time.local(2005, 10, 31, 0, 45, 0).since(1.day), "st+1.day=>st"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 March 19th 1:45am
- assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,19,1,45,0).since(1.day), 'dt+1.day=>st'
- assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(1.day), 'st+1.day=>st'
+ assert_equal Time.local(2006, 3, 20, 1, 45, 0), Time.local(2006, 3, 19, 1, 45, 0).since(1.day), "dt+1.day=>st"
+ assert_equal Time.local(2006, 3, 21, 1, 45, 0), Time.local(2006, 3, 20, 1, 45, 0).since(1.day), "st+1.day=>st"
end
end
def test_daylight_savings_time_crossings_forward_end_tomorrow
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 October 30th 12:45am
- assert_equal Time.local(2005,10,31,0,45,0), Time.local(2005,10,30,0,45,0).tomorrow, 'dt+1.day=>st'
- assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).tomorrow, 'st+1.day=>st'
+ assert_equal Time.local(2005, 10, 31, 0, 45, 0), Time.local(2005, 10, 30, 0, 45, 0).tomorrow, "dt+1.day=>st"
+ assert_equal Time.local(2005, 11, 1, 0, 45, 0), Time.local(2005, 10, 31, 0, 45, 0).tomorrow, "st+1.day=>st"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 March 19th 1:45am
- assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,19,1,45,0).tomorrow, 'dt+1.day=>st'
- assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).tomorrow, 'st+1.day=>st'
+ assert_equal Time.local(2006, 3, 20, 1, 45, 0), Time.local(2006, 3, 19, 1, 45, 0).tomorrow, "dt+1.day=>st"
+ assert_equal Time.local(2006, 3, 21, 1, 45, 0), Time.local(2006, 3, 20, 1, 45, 0).tomorrow, "st+1.day=>st"
end
end
def test_daylight_savings_time_crossings_backward_end_yesterday
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# dt: US: 2005 October 30th 12:45am
- assert_equal Time.local(2005,10,30,0,45,0), Time.local(2005,10,31,0,45,0).yesterday, 'st-1.day=>dt'
- assert_equal Time.local(2005,10, 31,0,45,0), Time.local(2005,11,1,0,45,0).yesterday, 'st-1.day=>st'
+ assert_equal Time.local(2005, 10, 30, 0, 45, 0), Time.local(2005, 10, 31, 0, 45, 0).yesterday, "st-1.day=>dt"
+ assert_equal Time.local(2005, 10, 31, 0, 45, 0), Time.local(2005, 11, 1, 0, 45, 0).yesterday, "st-1.day=>st"
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
# dt: New Zealand: 2006 March 19th 1:45am
- assert_equal Time.local(2006,3,19,1,45,0), Time.local(2006,3,20,1,45,0).yesterday, 'st-1.day=>dt'
- assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,21,1,45,0).yesterday, 'st-1.day=>st'
+ assert_equal Time.local(2006, 3, 19, 1, 45, 0), Time.local(2006, 3, 20, 1, 45, 0).yesterday, "st-1.day=>dt"
+ assert_equal Time.local(2006, 3, 20, 1, 45, 0), Time.local(2006, 3, 21, 1, 45, 0).yesterday, "st-1.day=>st"
end
end
def test_change
- assert_equal Time.local(2006,2,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:year => 2006)
- assert_equal Time.local(2005,6,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:month => 6)
- assert_equal Time.local(2012,9,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:year => 2012, :month => 9)
- assert_equal Time.local(2005,2,22,16), Time.local(2005,2,22,15,15,10).change(:hour => 16)
- assert_equal Time.local(2005,2,22,16,45), Time.local(2005,2,22,15,15,10).change(:hour => 16, :min => 45)
- assert_equal Time.local(2005,2,22,15,45), Time.local(2005,2,22,15,15,10).change(:min => 45)
-
- assert_equal Time.local(2005,1,2, 5, 0, 0, 0), Time.local(2005,1,2,11,22,33,44).change(:hour => 5)
- assert_equal Time.local(2005,1,2,11, 6, 0, 0), Time.local(2005,1,2,11,22,33,44).change(:min => 6)
- assert_equal Time.local(2005,1,2,11,22, 7, 0), Time.local(2005,1,2,11,22,33,44).change(:sec => 7)
- assert_equal Time.local(2005,1,2,11,22,33, 8), Time.local(2005,1,2,11,22,33,44).change(:usec => 8)
- assert_equal Time.local(2005,1,2,11,22,33, 8), Time.local(2005,1,2,11,22,33,2).change(:nsec => 8000)
- assert_raise(ArgumentError) { Time.local(2005,1,2,11,22,33, 8).change(:usec => 1, :nsec => 1) }
- assert_nothing_raised { Time.new(2015, 5, 9, 10, 00, 00, '+03:00').change(nsec: 999999999) }
+ assert_equal Time.local(2006, 2, 22, 15, 15, 10), Time.local(2005, 2, 22, 15, 15, 10).change(year: 2006)
+ assert_equal Time.local(2005, 6, 22, 15, 15, 10), Time.local(2005, 2, 22, 15, 15, 10).change(month: 6)
+ assert_equal Time.local(2012, 9, 22, 15, 15, 10), Time.local(2005, 2, 22, 15, 15, 10).change(year: 2012, month: 9)
+ assert_equal Time.local(2005, 2, 22, 16), Time.local(2005, 2, 22, 15, 15, 10).change(hour: 16)
+ assert_equal Time.local(2005, 2, 22, 16, 45), Time.local(2005, 2, 22, 15, 15, 10).change(hour: 16, min: 45)
+ assert_equal Time.local(2005, 2, 22, 15, 45), Time.local(2005, 2, 22, 15, 15, 10).change(min: 45)
+
+ assert_equal Time.local(2005, 1, 2, 5, 0, 0, 0), Time.local(2005, 1, 2, 11, 22, 33, 44).change(hour: 5)
+ assert_equal Time.local(2005, 1, 2, 11, 6, 0, 0), Time.local(2005, 1, 2, 11, 22, 33, 44).change(min: 6)
+ assert_equal Time.local(2005, 1, 2, 11, 22, 7, 0), Time.local(2005, 1, 2, 11, 22, 33, 44).change(sec: 7)
+ assert_equal Time.local(2005, 1, 2, 11, 22, 33, 8), Time.local(2005, 1, 2, 11, 22, 33, 44).change(usec: 8)
+ assert_equal Time.local(2005, 1, 2, 11, 22, 33, 8), Time.local(2005, 1, 2, 11, 22, 33, 2).change(nsec: 8000)
+ assert_raise(ArgumentError) { Time.local(2005, 1, 2, 11, 22, 33, 8).change(usec: 1, nsec: 1) }
+ assert_nothing_raised { Time.new(2015, 5, 9, 10, 00, 00, "+03:00").change(nsec: 999999999) }
end
def test_utc_change
- assert_equal Time.utc(2006,2,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:year => 2006)
- assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:month => 6)
- assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:year => 2012, :month => 9)
- assert_equal Time.utc(2005,2,22,16), Time.utc(2005,2,22,15,15,10).change(:hour => 16)
- assert_equal Time.utc(2005,2,22,16,45), Time.utc(2005,2,22,15,15,10).change(:hour => 16, :min => 45)
- assert_equal Time.utc(2005,2,22,15,45), Time.utc(2005,2,22,15,15,10).change(:min => 45)
- assert_equal Time.utc(2005,1,2,11,22,33,8), Time.utc(2005,1,2,11,22,33,2).change(:nsec => 8000)
+ assert_equal Time.utc(2006, 2, 22, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).change(year: 2006)
+ assert_equal Time.utc(2005, 6, 22, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).change(month: 6)
+ assert_equal Time.utc(2012, 9, 22, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).change(year: 2012, month: 9)
+ assert_equal Time.utc(2005, 2, 22, 16), Time.utc(2005, 2, 22, 15, 15, 10).change(hour: 16)
+ assert_equal Time.utc(2005, 2, 22, 16, 45), Time.utc(2005, 2, 22, 15, 15, 10).change(hour: 16, min: 45)
+ assert_equal Time.utc(2005, 2, 22, 15, 45), Time.utc(2005, 2, 22, 15, 15, 10).change(min: 45)
+ assert_equal Time.utc(2005, 1, 2, 11, 22, 33, 8), Time.utc(2005, 1, 2, 11, 22, 33, 2).change(nsec: 8000)
end
def test_offset_change
- assert_equal Time.new(2006,2,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:year => 2006)
- assert_equal Time.new(2005,6,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:month => 6)
- assert_equal Time.new(2012,9,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:year => 2012, :month => 9)
- assert_equal Time.new(2005,2,22,16,0,0,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:hour => 16)
- assert_equal Time.new(2005,2,22,16,45,0,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:hour => 16, :min => 45)
- assert_equal Time.new(2005,2,22,15,45,0,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:min => 45)
- assert_equal Time.new(2005,2,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,0,"-08:00").change(:sec => 10)
- assert_equal 10, Time.new(2005,2,22,15,15,0,"-08:00").change(:usec => 10).usec
- assert_equal 10, Time.new(2005,2,22,15,15,0,"-08:00").change(:nsec => 10).nsec
- assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "-08:00").change(:usec => 1000000) }
- assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "-08:00").change(:nsec => 1000000000) }
+ assert_equal Time.new(2006, 2, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").change(year: 2006)
+ assert_equal Time.new(2005, 6, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").change(month: 6)
+ assert_equal Time.new(2012, 9, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").change(year: 2012, month: 9)
+ assert_equal Time.new(2005, 2, 22, 16, 0, 0, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").change(hour: 16)
+ assert_equal Time.new(2005, 2, 22, 16, 45, 0, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").change(hour: 16, min: 45)
+ assert_equal Time.new(2005, 2, 22, 15, 45, 0, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").change(min: 45)
+ assert_equal Time.new(2005, 2, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 0, "-08:00").change(sec: 10)
+ assert_equal 10, Time.new(2005, 2, 22, 15, 15, 0, "-08:00").change(usec: 10).usec
+ assert_equal 10, Time.new(2005, 2, 22, 15, 15, 0, "-08:00").change(nsec: 10).nsec
+ assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "-08:00").change(usec: 1000000) }
+ assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "-08:00").change(nsec: 1000000000) }
+ end
+
+ def test_change_offset
+ assert_equal Time.new(2006, 2, 22, 15, 15, 10, "-08:00"), Time.new(2006, 2, 22, 15, 15, 10, "+01:00").change(offset: "-08:00")
+ assert_equal Time.new(2006, 2, 22, 15, 15, 10, -28800), Time.new(2006, 2, 22, 15, 15, 10, 3600).change(offset: -28800)
+ assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "+01:00").change(usec: 1000000, offset: "-08:00") }
+ assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "+01:00").change(nsec: 1000000000, offset: -28800) }
end
def test_advance
- assert_equal Time.local(2006,2,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 1)
- assert_equal Time.local(2005,6,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:months => 4)
- assert_equal Time.local(2005,3,21,15,15,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3)
- assert_equal Time.local(2005,3,25,3,15,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.5)
- assert_in_delta Time.local(2005,3,26,12,51,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.7), 1
- assert_equal Time.local(2005,3,5,15,15,10), Time.local(2005,2,28,15,15,10).advance(:days => 5)
- assert_equal Time.local(2005,3,6,3,15,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.5)
- assert_in_delta Time.local(2005,3,6,8,3,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.7), 1
- assert_equal Time.local(2012,9,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 7)
- assert_equal Time.local(2013,10,3,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5)
- assert_equal Time.local(2013,10,17,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
- assert_equal Time.local(2001,12,27,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
- assert_equal Time.local(2005,2,28,15,15,10), Time.local(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
- assert_equal Time.local(2005,2,28,20,15,10), Time.local(2005,2,28,15,15,10).advance(:hours => 5)
- assert_equal Time.local(2005,2,28,15,22,10), Time.local(2005,2,28,15,15,10).advance(:minutes => 7)
- assert_equal Time.local(2005,2,28,15,15,19), Time.local(2005,2,28,15,15,10).advance(:seconds => 9)
- assert_equal Time.local(2005,2,28,20,22,19), Time.local(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
- assert_equal Time.local(2005,2,28,10,8,1), Time.local(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
- assert_equal Time.local(2013,10,17,20,22,19), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal Time.local(2006, 2, 28, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(years: 1)
+ assert_equal Time.local(2005, 6, 28, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(months: 4)
+ assert_equal Time.local(2005, 3, 21, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(weeks: 3)
+ assert_equal Time.local(2005, 3, 25, 3, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(weeks: 3.5)
+ assert_in_delta Time.local(2005, 3, 26, 12, 51, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(weeks: 3.7), 1
+ assert_equal Time.local(2005, 3, 5, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(days: 5)
+ assert_equal Time.local(2005, 3, 6, 3, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(days: 5.5)
+ assert_in_delta Time.local(2005, 3, 6, 8, 3, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(days: 5.7), 1
+ assert_equal Time.local(2012, 9, 28, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 7)
+ assert_equal Time.local(2013, 10, 3, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, days: 5)
+ assert_equal Time.local(2013, 10, 17, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, weeks: 2, days: 5)
+ assert_equal Time.local(2001, 12, 27, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(years: -3, months: -2, days: -1)
+ assert_equal Time.local(2005, 2, 28, 15, 15, 10), Time.local(2004, 2, 29, 15, 15, 10).advance(years: 1) # leap day plus one year
+ assert_equal Time.local(2005, 2, 28, 20, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(hours: 5)
+ assert_equal Time.local(2005, 2, 28, 15, 22, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(minutes: 7)
+ assert_equal Time.local(2005, 2, 28, 15, 15, 19), Time.local(2005, 2, 28, 15, 15, 10).advance(seconds: 9)
+ assert_equal Time.local(2005, 2, 28, 20, 22, 19), Time.local(2005, 2, 28, 15, 15, 10).advance(hours: 5, minutes: 7, seconds: 9)
+ assert_equal Time.local(2005, 2, 28, 10, 8, 1), Time.local(2005, 2, 28, 15, 15, 10).advance(hours: -5, minutes: -7, seconds: -9)
+ assert_equal Time.local(2013, 10, 17, 20, 22, 19), Time.local(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, weeks: 2, days: 5, hours: 5, minutes: 7, seconds: 9)
end
def test_utc_advance
- assert_equal Time.utc(2006,2,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 1)
- assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:months => 4)
- assert_equal Time.utc(2005,3,21,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3)
- assert_equal Time.utc(2005,3,25,3,15,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.5)
- assert_in_delta Time.utc(2005,3,26,12,51,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.7), 1
- assert_equal Time.utc(2005,3,5,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5)
- assert_equal Time.utc(2005,3,6,3,15,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.5)
- assert_in_delta Time.utc(2005,3,6,8,3,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.7), 1
- assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 7, :months => 7)
- assert_equal Time.utc(2013,10,3,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 7, :months => 19, :days => 11)
- assert_equal Time.utc(2013,10,17,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
- assert_equal Time.utc(2001,12,27,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
- assert_equal Time.utc(2005,2,28,15,15,10), Time.utc(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
- assert_equal Time.utc(2005,2,28,20,15,10), Time.utc(2005,2,28,15,15,10).advance(:hours => 5)
- assert_equal Time.utc(2005,2,28,15,22,10), Time.utc(2005,2,28,15,15,10).advance(:minutes => 7)
- assert_equal Time.utc(2005,2,28,15,15,19), Time.utc(2005,2,28,15,15,10).advance(:seconds => 9)
- assert_equal Time.utc(2005,2,28,20,22,19), Time.utc(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
- assert_equal Time.utc(2005,2,28,10,8,1), Time.utc(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
- assert_equal Time.utc(2013,10,17,20,22,19), Time.utc(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal Time.utc(2006, 2, 22, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).advance(years: 1)
+ assert_equal Time.utc(2005, 6, 22, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).advance(months: 4)
+ assert_equal Time.utc(2005, 3, 21, 15, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(weeks: 3)
+ assert_equal Time.utc(2005, 3, 25, 3, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(weeks: 3.5)
+ assert_in_delta Time.utc(2005, 3, 26, 12, 51, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(weeks: 3.7), 1
+ assert_equal Time.utc(2005, 3, 5, 15, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(days: 5)
+ assert_equal Time.utc(2005, 3, 6, 3, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(days: 5.5)
+ assert_in_delta Time.utc(2005, 3, 6, 8, 3, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(days: 5.7), 1
+ assert_equal Time.utc(2012, 9, 22, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).advance(years: 7, months: 7)
+ assert_equal Time.utc(2013, 10, 3, 15, 15, 10), Time.utc(2005, 2, 22, 15, 15, 10).advance(years: 7, months: 19, days: 11)
+ assert_equal Time.utc(2013, 10, 17, 15, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, weeks: 2, days: 5)
+ assert_equal Time.utc(2001, 12, 27, 15, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(years: -3, months: -2, days: -1)
+ assert_equal Time.utc(2005, 2, 28, 15, 15, 10), Time.utc(2004, 2, 29, 15, 15, 10).advance(years: 1) # leap day plus one year
+ assert_equal Time.utc(2005, 2, 28, 20, 15, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(hours: 5)
+ assert_equal Time.utc(2005, 2, 28, 15, 22, 10), Time.utc(2005, 2, 28, 15, 15, 10).advance(minutes: 7)
+ assert_equal Time.utc(2005, 2, 28, 15, 15, 19), Time.utc(2005, 2, 28, 15, 15, 10).advance(seconds: 9)
+ assert_equal Time.utc(2005, 2, 28, 20, 22, 19), Time.utc(2005, 2, 28, 15, 15, 10).advance(hours: 5, minutes: 7, seconds: 9)
+ assert_equal Time.utc(2005, 2, 28, 10, 8, 1), Time.utc(2005, 2, 28, 15, 15, 10).advance(hours: -5, minutes: -7, seconds: -9)
+ assert_equal Time.utc(2013, 10, 17, 20, 22, 19), Time.utc(2005, 2, 28, 15, 15, 10).advance(years: 7, months: 19, weeks: 2, days: 5, hours: 5, minutes: 7, seconds: 9)
end
def test_offset_advance
- assert_equal Time.new(2006,2,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:years => 1)
- assert_equal Time.new(2005,6,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:months => 4)
- assert_equal Time.new(2005,3,21,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:weeks => 3)
- assert_equal Time.new(2005,3,25,3,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:weeks => 3.5)
- assert_in_delta Time.new(2005,3,26,12,51,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:weeks => 3.7), 1
- assert_equal Time.new(2005,3,5,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:days => 5)
- assert_equal Time.new(2005,3,6,3,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:days => 5.5)
- assert_in_delta Time.new(2005,3,6,8,3,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:days => 5.7), 1
- assert_equal Time.new(2012,9,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:years => 7, :months => 7)
- assert_equal Time.new(2013,10,3,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:years => 7, :months => 19, :days => 11)
- assert_equal Time.new(2013,10,17,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
- assert_equal Time.new(2001,12,27,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:years => -3, :months => -2, :days => -1)
- assert_equal Time.new(2005,2,28,15,15,10,'-08:00'), Time.new(2004,2,29,15,15,10,'-08:00').advance(:years => 1) #leap day plus one year
- assert_equal Time.new(2005,2,28,20,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:hours => 5)
- assert_equal Time.new(2005,2,28,15,22,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:minutes => 7)
- assert_equal Time.new(2005,2,28,15,15,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:seconds => 9)
- assert_equal Time.new(2005,2,28,20,22,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:hours => 5, :minutes => 7, :seconds => 9)
- assert_equal Time.new(2005,2,28,10,8,1,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:hours => -5, :minutes => -7, :seconds => -9)
- assert_equal Time.new(2013,10,17,20,22,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal Time.new(2006, 2, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").advance(years: 1)
+ assert_equal Time.new(2005, 6, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").advance(months: 4)
+ assert_equal Time.new(2005, 3, 21, 15, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(weeks: 3)
+ assert_equal Time.new(2005, 3, 25, 3, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(weeks: 3.5)
+ assert_in_delta Time.new(2005, 3, 26, 12, 51, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(weeks: 3.7), 1
+ assert_equal Time.new(2005, 3, 5, 15, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(days: 5)
+ assert_equal Time.new(2005, 3, 6, 3, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(days: 5.5)
+ assert_in_delta Time.new(2005, 3, 6, 8, 3, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(days: 5.7), 1
+ assert_equal Time.new(2012, 9, 22, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").advance(years: 7, months: 7)
+ assert_equal Time.new(2013, 10, 3, 15, 15, 10, "-08:00"), Time.new(2005, 2, 22, 15, 15, 10, "-08:00").advance(years: 7, months: 19, days: 11)
+ assert_equal Time.new(2013, 10, 17, 15, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(years: 7, months: 19, weeks: 2, days: 5)
+ assert_equal Time.new(2001, 12, 27, 15, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(years: -3, months: -2, days: -1)
+ assert_equal Time.new(2005, 2, 28, 15, 15, 10, "-08:00"), Time.new(2004, 2, 29, 15, 15, 10, "-08:00").advance(years: 1) # leap day plus one year
+ assert_equal Time.new(2005, 2, 28, 20, 15, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(hours: 5)
+ assert_equal Time.new(2005, 2, 28, 15, 22, 10, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(minutes: 7)
+ assert_equal Time.new(2005, 2, 28, 15, 15, 19, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(seconds: 9)
+ assert_equal Time.new(2005, 2, 28, 20, 22, 19, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(hours: 5, minutes: 7, seconds: 9)
+ assert_equal Time.new(2005, 2, 28, 10, 8, 1, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(hours: -5, minutes: -7, seconds: -9)
+ assert_equal Time.new(2013, 10, 17, 20, 22, 19, "-08:00"), Time.new(2005, 2, 28, 15, 15, 10, "-08:00").advance(years: 7, months: 19, weeks: 2, days: 5, hours: 5, minutes: 7, seconds: 9)
end
def test_advance_with_nsec
t = Time.at(0, Rational(108635108, 1000))
- assert_equal t, t.advance(:months => 0)
+ assert_equal t, t.advance(months: 0)
end
def test_advance_gregorian_proleptic
- assert_equal Time.local(1582,10,14,15,15,10), Time.local(1582,10,15,15,15,10).advance(:days => -1)
- assert_equal Time.local(1582,10,15,15,15,10), Time.local(1582,10,14,15,15,10).advance(:days => 1)
- assert_equal Time.local(1582,10,5,15,15,10), Time.local(1582,10,4,15,15,10).advance(:days => 1)
- assert_equal Time.local(1582,10,4,15,15,10), Time.local(1582,10,5,15,15,10).advance(:days => -1)
+ assert_equal Time.local(1582, 10, 14, 15, 15, 10), Time.local(1582, 10, 15, 15, 15, 10).advance(days: -1)
+ assert_equal Time.local(1582, 10, 15, 15, 15, 10), Time.local(1582, 10, 14, 15, 15, 10).advance(days: 1)
+ assert_equal Time.local(1582, 10, 5, 15, 15, 10), Time.local(1582, 10, 4, 15, 15, 10).advance(days: 1)
+ assert_equal Time.local(1582, 10, 4, 15, 15, 10), Time.local(1582, 10, 5, 15, 15, 10).advance(days: -1)
end
def test_last_week
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2005,2,21), Time.local(2005,3,1,15,15,10).last_week
- assert_equal Time.local(2005,2,22), Time.local(2005,3,1,15,15,10).last_week(:tuesday)
- assert_equal Time.local(2005,2,25), Time.local(2005,3,1,15,15,10).last_week(:friday)
- assert_equal Time.local(2006,10,30), Time.local(2006,11,6,0,0,0).last_week
- assert_equal Time.local(2006,11,15), Time.local(2006,11,23,0,0,0).last_week(:wednesday)
+ with_env_tz "US/Eastern" do
+ assert_equal Time.local(2005, 2, 21), Time.local(2005, 3, 1, 15, 15, 10).last_week
+ assert_equal Time.local(2005, 2, 22), Time.local(2005, 3, 1, 15, 15, 10).last_week(:tuesday)
+ assert_equal Time.local(2005, 2, 25), Time.local(2005, 3, 1, 15, 15, 10).last_week(:friday)
+ assert_equal Time.local(2006, 10, 30), Time.local(2006, 11, 6, 0, 0, 0).last_week
+ assert_equal Time.local(2006, 11, 15), Time.local(2006, 11, 23, 0, 0, 0).last_week(:wednesday)
end
end
def test_next_week_near_daylight_start
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2006,4,3), Time.local(2006,4,2,23,1,0).next_week, 'just crossed standard => daylight'
+ with_env_tz "US/Eastern" do
+ assert_equal Time.local(2006, 4, 3), Time.local(2006, 4, 2, 23, 1, 0).next_week, "just crossed standard => daylight"
end
- with_env_tz 'NZ' do
- assert_equal Time.local(2006,10,2), Time.local(2006,10,1,23,1,0).next_week, 'just crossed standard => daylight'
+ with_env_tz "NZ" do
+ assert_equal Time.local(2006, 10, 2), Time.local(2006, 10, 1, 23, 1, 0).next_week, "just crossed standard => daylight"
end
end
def test_next_week_near_daylight_end
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2006,10,30), Time.local(2006,10,29,23,1,0).next_week, 'just crossed daylight => standard'
+ with_env_tz "US/Eastern" do
+ assert_equal Time.local(2006, 10, 30), Time.local(2006, 10, 29, 23, 1, 0).next_week, "just crossed daylight => standard"
end
- with_env_tz 'NZ' do
- assert_equal Time.local(2006,3,20), Time.local(2006,3,19,23,1,0).next_week, 'just crossed daylight => standard'
+ with_env_tz "NZ" do
+ assert_equal Time.local(2006, 3, 20), Time.local(2006, 3, 19, 23, 1, 0).next_week, "just crossed daylight => standard"
end
end
@@ -564,28 +569,33 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_custom_date_format
- Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
- assert_equal '20050221143000', Time.local(2005, 2, 21, 14, 30, 0).to_s(:custom)
+ Time::DATE_FORMATS[:custom] = "%Y%m%d%H%M%S"
+ assert_equal "20050221143000", Time.local(2005, 2, 21, 14, 30, 0).to_s(:custom)
Time::DATE_FORMATS.delete(:custom)
end
+ def test_rfc3339_with_fractional_seconds
+ time = Time.new(1999, 12, 31, 19, 0, Rational(1, 8), -18000)
+ assert_equal "1999-12-31T19:00:00.125-05:00", time.rfc3339(3)
+ end
+
def test_to_date
assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date
end
def test_to_datetime
assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0)
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400))
end
- with_env_tz 'NZ' do
+ with_env_tz "NZ" do
assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400))
end
assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value
end
def test_to_time
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_equal Time, Time.local(2005, 2, 21, 17, 44, 30).to_time.class
assert_equal Time.local(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30).to_time
assert_equal Time.local(2005, 2, 21, 17, 44, 30).utc_offset, Time.local(2005, 2, 21, 17, 44, 30).to_time.utc_offset
@@ -650,82 +660,78 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_last_month_on_31st
- assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
- end
-
def test_xmlschema_is_available
assert_nothing_raised { Time.now.xmlschema }
end
def test_today_with_time_local
Date.stub(:current, Date.new(2000, 1, 1)) do
- assert_equal false, Time.local(1999,12,31,23,59,59).today?
- assert_equal true, Time.local(2000,1,1,0).today?
- assert_equal true, Time.local(2000,1,1,23,59,59).today?
- assert_equal false, Time.local(2000,1,2,0).today?
+ assert_equal false, Time.local(1999, 12, 31, 23, 59, 59).today?
+ assert_equal true, Time.local(2000, 1, 1, 0).today?
+ assert_equal true, Time.local(2000, 1, 1, 23, 59, 59).today?
+ assert_equal false, Time.local(2000, 1, 2, 0).today?
end
end
def test_today_with_time_utc
Date.stub(:current, Date.new(2000, 1, 1)) do
- assert_equal false, Time.utc(1999,12,31,23,59,59).today?
- assert_equal true, Time.utc(2000,1,1,0).today?
- assert_equal true, Time.utc(2000,1,1,23,59,59).today?
- assert_equal false, Time.utc(2000,1,2,0).today?
+ assert_equal false, Time.utc(1999, 12, 31, 23, 59, 59).today?
+ assert_equal true, Time.utc(2000, 1, 1, 0).today?
+ assert_equal true, Time.utc(2000, 1, 1, 23, 59, 59).today?
+ assert_equal false, Time.utc(2000, 1, 2, 0).today?
end
end
def test_past_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stub(:current, Time.local(2005,2,10,15,30,45)) do
- assert_equal true, Time.local(2005,2,10,15,30,44).past?
- assert_equal false, Time.local(2005,2,10,15,30,45).past?
- assert_equal false, Time.local(2005,2,10,15,30,46).past?
- assert_equal true, Time.utc(2005,2,10,20,30,44).past?
- assert_equal false, Time.utc(2005,2,10,20,30,45).past?
- assert_equal false, Time.utc(2005,2,10,20,30,46).past?
+ with_env_tz "US/Eastern" do
+ Time.stub(:current, Time.local(2005, 2, 10, 15, 30, 45)) do
+ assert_equal true, Time.local(2005, 2, 10, 15, 30, 44).past?
+ assert_equal false, Time.local(2005, 2, 10, 15, 30, 45).past?
+ assert_equal false, Time.local(2005, 2, 10, 15, 30, 46).past?
+ assert_equal true, Time.utc(2005, 2, 10, 20, 30, 44).past?
+ assert_equal false, Time.utc(2005, 2, 10, 20, 30, 45).past?
+ assert_equal false, Time.utc(2005, 2, 10, 20, 30, 46).past?
end
end
end
def test_past_with_time_current_as_time_with_zone
- with_env_tz 'US/Eastern' do
- twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
+ with_env_tz "US/Eastern" do
+ twz = Time.utc(2005, 2, 10, 15, 30, 45).in_time_zone("Central Time (US & Canada)")
Time.stub(:current, twz) do
- assert_equal true, Time.local(2005,2,10,10,30,44).past?
- assert_equal false, Time.local(2005,2,10,10,30,45).past?
- assert_equal false, Time.local(2005,2,10,10,30,46).past?
- assert_equal true, Time.utc(2005,2,10,15,30,44).past?
- assert_equal false, Time.utc(2005,2,10,15,30,45).past?
- assert_equal false, Time.utc(2005,2,10,15,30,46).past?
+ assert_equal true, Time.local(2005, 2, 10, 10, 30, 44).past?
+ assert_equal false, Time.local(2005, 2, 10, 10, 30, 45).past?
+ assert_equal false, Time.local(2005, 2, 10, 10, 30, 46).past?
+ assert_equal true, Time.utc(2005, 2, 10, 15, 30, 44).past?
+ assert_equal false, Time.utc(2005, 2, 10, 15, 30, 45).past?
+ assert_equal false, Time.utc(2005, 2, 10, 15, 30, 46).past?
end
end
end
def test_future_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stub(:current, Time.local(2005,2,10,15,30,45)) do
- assert_equal false, Time.local(2005,2,10,15,30,44).future?
- assert_equal false, Time.local(2005,2,10,15,30,45).future?
- assert_equal true, Time.local(2005,2,10,15,30,46).future?
- assert_equal false, Time.utc(2005,2,10,20,30,44).future?
- assert_equal false, Time.utc(2005,2,10,20,30,45).future?
- assert_equal true, Time.utc(2005,2,10,20,30,46).future?
+ with_env_tz "US/Eastern" do
+ Time.stub(:current, Time.local(2005, 2, 10, 15, 30, 45)) do
+ assert_equal false, Time.local(2005, 2, 10, 15, 30, 44).future?
+ assert_equal false, Time.local(2005, 2, 10, 15, 30, 45).future?
+ assert_equal true, Time.local(2005, 2, 10, 15, 30, 46).future?
+ assert_equal false, Time.utc(2005, 2, 10, 20, 30, 44).future?
+ assert_equal false, Time.utc(2005, 2, 10, 20, 30, 45).future?
+ assert_equal true, Time.utc(2005, 2, 10, 20, 30, 46).future?
end
end
end
def test_future_with_time_current_as_time_with_zone
- with_env_tz 'US/Eastern' do
- twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
+ with_env_tz "US/Eastern" do
+ twz = Time.utc(2005, 2, 10, 15, 30, 45).in_time_zone("Central Time (US & Canada)")
Time.stub(:current, twz) do
- assert_equal false, Time.local(2005,2,10,10,30,44).future?
- assert_equal false, Time.local(2005,2,10,10,30,45).future?
- assert_equal true, Time.local(2005,2,10,10,30,46).future?
- assert_equal false, Time.utc(2005,2,10,15,30,44).future?
- assert_equal false, Time.utc(2005,2,10,15,30,45).future?
- assert_equal true, Time.utc(2005,2,10,15,30,46).future?
+ assert_equal false, Time.local(2005, 2, 10, 10, 30, 44).future?
+ assert_equal false, Time.local(2005, 2, 10, 10, 30, 45).future?
+ assert_equal true, Time.local(2005, 2, 10, 10, 30, 46).future?
+ assert_equal false, Time.utc(2005, 2, 10, 15, 30, 44).future?
+ assert_equal false, Time.utc(2005, 2, 10, 15, 30, 45).future?
+ assert_equal true, Time.utc(2005, 2, 10, 15, 30, 46).future?
end
end
end
@@ -735,17 +741,17 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_formatted_offset_with_utc
- assert_equal '+00:00', Time.utc(2000).formatted_offset
- assert_equal '+0000', Time.utc(2000).formatted_offset(false)
- assert_equal 'UTC', Time.utc(2000).formatted_offset(true, 'UTC')
+ assert_equal "+00:00", Time.utc(2000).formatted_offset
+ assert_equal "+0000", Time.utc(2000).formatted_offset(false)
+ assert_equal "UTC", Time.utc(2000).formatted_offset(true, "UTC")
end
def test_formatted_offset_with_local
- with_env_tz 'US/Eastern' do
- assert_equal '-05:00', Time.local(2000).formatted_offset
- assert_equal '-0500', Time.local(2000).formatted_offset(false)
- assert_equal '-04:00', Time.local(2000, 7).formatted_offset
- assert_equal '-0400', Time.local(2000, 7).formatted_offset(false)
+ with_env_tz "US/Eastern" do
+ assert_equal "-05:00", Time.local(2000).formatted_offset
+ assert_equal "-0500", Time.local(2000).formatted_offset(false)
+ assert_equal "-04:00", Time.local(2000, 7).formatted_offset
+ assert_equal "-0400", Time.local(2000, 7).formatted_offset(false)
end
end
@@ -762,16 +768,16 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_compare_with_time_with_zone
- assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
- assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
- assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
+ assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
+ assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
+ assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone["UTC"]))
end
def test_compare_with_string
assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999).to_s
assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
- assert_equal( -1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1, 0).to_s)
- assert_equal nil, Time.utc(2000) <=> 'Invalid as Time'
+ assert_equal(-1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1, 0).to_s)
+ assert_nil Time.utc(2000) <=> "Invalid as Time"
end
def test_at_with_datetime
@@ -786,42 +792,42 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_at_with_datetime_returns_local_time
- with_env_tz 'US/Eastern' do
- dt = DateTime.civil(2000, 1, 1, 0, 0, 0, '+0')
+ with_env_tz "US/Eastern" do
+ dt = DateTime.civil(2000, 1, 1, 0, 0, 0, "+0")
assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(dt)
- assert_equal 'EST', Time.at(dt).zone
+ assert_equal "EST", Time.at(dt).zone
assert_equal(-18000, Time.at(dt).utc_offset)
# Daylight savings
- dt = DateTime.civil(2000, 7, 1, 1, 0, 0, '+1')
+ dt = DateTime.civil(2000, 7, 1, 1, 0, 0, "+1")
assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(dt)
- assert_equal 'EDT', Time.at(dt).zone
+ assert_equal "EDT", Time.at(dt).zone
assert_equal(-14400, Time.at(dt).utc_offset)
end
end
def test_at_with_time_with_zone
- assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC']))
+ assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"]))
# Only test this if the underlying Time.at raises a TypeError
begin
Time.at_without_coercion(Time.now, 0)
rescue TypeError
- assert_raise(TypeError) { assert_equal(Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC']), 0)) }
+ assert_raise(TypeError) { assert_equal(Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"]), 0)) }
end
end
def test_at_with_time_with_zone_returns_local_time
- with_env_tz 'US/Eastern' do
- twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])
+ with_env_tz "US/Eastern" do
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["London"])
assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(twz)
- assert_equal 'EST', Time.at(twz).zone
+ assert_equal "EST", Time.at(twz).zone
assert_equal(-18000, Time.at(twz).utc_offset)
# Daylight savings
- twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone["London"])
assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(twz)
- assert_equal 'EDT', Time.at(twz).zone
+ assert_equal "EDT", Time.at(twz).zone
assert_equal(-14400, Time.at(twz).utc_offset)
end
end
@@ -831,33 +837,33 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_at_with_utc_time
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_equal Time.utc(2000), Time.at(Time.utc(2000))
- assert_equal 'UTC', Time.at(Time.utc(2000)).zone
+ assert_equal "UTC", Time.at(Time.utc(2000)).zone
assert_equal(0, Time.at(Time.utc(2000)).utc_offset)
end
end
def test_at_with_local_time
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
assert_equal Time.local(2000), Time.at(Time.local(2000))
- assert_equal 'EST', Time.at(Time.local(2000)).zone
+ assert_equal "EST", Time.at(Time.local(2000)).zone
assert_equal(-18000, Time.at(Time.local(2000)).utc_offset)
assert_equal Time.local(2000, 7, 1), Time.at(Time.local(2000, 7, 1))
- assert_equal 'EDT', Time.at(Time.local(2000, 7, 1)).zone
+ assert_equal "EDT", Time.at(Time.local(2000, 7, 1)).zone
assert_equal(-14400, Time.at(Time.local(2000, 7, 1)).utc_offset)
end
end
def test_eql?
- assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
- assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
- assert_equal false,Time.utc(2000, 1, 1, 0, 0, 1).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
+ assert_equal true, Time.utc(2000).eql?(ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["UTC"]))
+ assert_equal true, Time.utc(2000).eql?(ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]))
+ assert_equal false, Time.utc(2000, 1, 1, 0, 0, 1).eql?(ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["UTC"]))
end
def test_minus_with_time_with_zone
- assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] )
+ assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["UTC"])
end
def test_minus_with_datetime
@@ -865,7 +871,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
def test_time_created_with_local_constructor_cannot_represent_times_during_hour_skipped_by_dst
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
# On Apr 2 2006 at 2:00AM in US, clocks were moved forward to 3:00AM.
# Therefore, 2AM EST doesn't exist for this date; Time.local fails over to 3:00AM EDT
assert_equal Time.local(2006, 4, 2, 3), Time.local(2006, 4, 2, 2)
@@ -875,40 +881,71 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
def test_case_equality
assert Time === Time.utc(2000)
- assert Time === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC'])
+ assert Time === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["UTC"])
assert Time === Class.new(Time).utc(2000)
assert_equal false, Time === DateTime.civil(2000)
assert_equal false, Class.new(Time) === Time.utc(2000)
- assert_equal false, Class.new(Time) === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC'])
+ assert_equal false, Class.new(Time) === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["UTC"])
end
def test_all_day
- assert_equal Time.local(2011,6,7,0,0,0)..Time.local(2011,6,7,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_day
+ assert_equal Time.local(2011, 6, 7, 0, 0, 0)..Time.local(2011, 6, 7, 23, 59, 59, Rational(999999999, 1000)), Time.local(2011, 6, 7, 10, 10, 10).all_day
end
def test_all_day_with_timezone
- beginning_of_day = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], Time.local(2011,6,7,0,0,0))
- end_of_day = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], Time.local(2011,6,7,23,59,59,Rational(999999999, 1000)))
+ beginning_of_day = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], Time.local(2011, 6, 7, 0, 0, 0))
+ end_of_day = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], Time.local(2011, 6, 7, 23, 59, 59, Rational(999999999, 1000)))
- assert_equal beginning_of_day, ActiveSupport::TimeWithZone.new(Time.local(2011,6,7,10,10,10), ActiveSupport::TimeZone["Hawaii"]).all_day.begin
- assert_equal end_of_day, ActiveSupport::TimeWithZone.new(Time.local(2011,6,7,10,10,10), ActiveSupport::TimeZone["Hawaii"]).all_day.end
+ assert_equal beginning_of_day, ActiveSupport::TimeWithZone.new(Time.local(2011, 6, 7, 10, 10, 10), ActiveSupport::TimeZone["Hawaii"]).all_day.begin
+ assert_equal end_of_day, ActiveSupport::TimeWithZone.new(Time.local(2011, 6, 7, 10, 10, 10), ActiveSupport::TimeZone["Hawaii"]).all_day.end
end
def test_all_week
- assert_equal Time.local(2011,6,6,0,0,0)..Time.local(2011,6,12,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_week
- assert_equal Time.local(2011,6,5,0,0,0)..Time.local(2011,6,11,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_week(:sunday)
+ assert_equal Time.local(2011, 6, 6, 0, 0, 0)..Time.local(2011, 6, 12, 23, 59, 59, Rational(999999999, 1000)), Time.local(2011, 6, 7, 10, 10, 10).all_week
+ assert_equal Time.local(2011, 6, 5, 0, 0, 0)..Time.local(2011, 6, 11, 23, 59, 59, Rational(999999999, 1000)), Time.local(2011, 6, 7, 10, 10, 10).all_week(:sunday)
end
def test_all_month
- assert_equal Time.local(2011,6,1,0,0,0)..Time.local(2011,6,30,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_month
+ assert_equal Time.local(2011, 6, 1, 0, 0, 0)..Time.local(2011, 6, 30, 23, 59, 59, Rational(999999999, 1000)), Time.local(2011, 6, 7, 10, 10, 10).all_month
end
def test_all_quarter
- assert_equal Time.local(2011,4,1,0,0,0)..Time.local(2011,6,30,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_quarter
+ assert_equal Time.local(2011, 4, 1, 0, 0, 0)..Time.local(2011, 6, 30, 23, 59, 59, Rational(999999999, 1000)), Time.local(2011, 6, 7, 10, 10, 10).all_quarter
end
def test_all_year
- assert_equal Time.local(2011,1,1,0,0,0)..Time.local(2011,12,31,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_year
+ assert_equal Time.local(2011, 1, 1, 0, 0, 0)..Time.local(2011, 12, 31, 23, 59, 59, Rational(999999999, 1000)), Time.local(2011, 6, 7, 10, 10, 10).all_year
+ end
+
+ def test_rfc3339_parse
+ time = Time.rfc3339("1999-12-31T19:00:00.125-05:00")
+
+ assert_equal 1999, time.year
+ assert_equal 12, time.month
+ assert_equal 31, time.day
+ assert_equal 19, time.hour
+ assert_equal 0, time.min
+ assert_equal 0, time.sec
+ assert_equal 125000, time.usec
+ assert_equal(-18000, time.utc_offset)
+
+ exception = assert_raises(ArgumentError) do
+ Time.rfc3339("1999-12-31")
+ end
+
+ assert_equal "invalid date", exception.message
+
+ exception = assert_raises(ArgumentError) do
+ Time.rfc3339("1999-12-31T19:00:00")
+ end
+
+ assert_equal "invalid date", exception.message
+
+ exception = assert_raises(ArgumentError) do
+ Time.rfc3339("foobar")
+ end
+
+ assert_equal "invalid date", exception.message
end
end
@@ -942,7 +979,7 @@ class TimeExtMarshalingTest < ActiveSupport::TestCase
end
def test_marshalling_preserves_fractional_seconds
- t = Time.parse('00:00:00.500')
+ t = Time.parse("00:00:00.500")
unmarshaled = Marshal.load(Marshal.dump(t))
assert_equal t.to_f, unmarshaled.to_f
assert_equal t, unmarshaled
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index d90714acdb..b25747eadb 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -1,15 +1,17 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'time_zone_test_helpers'
-require 'active_support/core_ext/string/strip'
-require 'yaml'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "time_zone_test_helpers"
+require "active_support/core_ext/string/strip"
+require "yaml"
class TimeWithZoneTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
def setup
@utc = Time.utc(2000, 1, 1, 0)
- @time_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ @time_zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
@twz = ActiveSupport::TimeWithZone.new(@utc, @time_zone)
@dt_twz = ActiveSupport::TimeWithZone.new(@utc.to_datetime, @time_zone)
end
@@ -29,25 +31,31 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_in_time_zone
- Time.use_zone 'Alaska' do
- assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone['Alaska']), @twz.in_time_zone
+ Time.use_zone "Alaska" do
+ assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone["Alaska"]), @twz.in_time_zone
end
end
def test_in_time_zone_with_argument
- assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone['Alaska']), @twz.in_time_zone('Alaska')
+ assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone["Alaska"]), @twz.in_time_zone("Alaska")
end
def test_in_time_zone_with_new_zone_equal_to_old_zone_does_not_create_new_object
- assert_equal @twz.object_id, @twz.in_time_zone(ActiveSupport::TimeZone['Eastern Time (US & Canada)']).object_id
+ assert_equal @twz.object_id, @twz.in_time_zone(ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).object_id
end
def test_in_time_zone_with_bad_argument
- assert_raise(ArgumentError) { @twz.in_time_zone('No such timezone exists') }
+ assert_raise(ArgumentError) { @twz.in_time_zone("No such timezone exists") }
assert_raise(ArgumentError) { @twz.in_time_zone(-15.hours) }
assert_raise(ArgumentError) { @twz.in_time_zone(Object.new) }
end
+ def test_in_time_zone_with_ambiguous_time
+ with_env_tz "Europe/Moscow" do
+ assert_equal Time.utc(2014, 10, 25, 22, 0, 0), Time.local(2014, 10, 26, 1, 0, 0).in_time_zone("Moscow")
+ end
+ end
+
def test_localtime
assert_equal @twz.localtime, @twz.utc.getlocal
assert_instance_of Time, @twz.localtime
@@ -57,26 +65,26 @@ class TimeWithZoneTest < ActiveSupport::TestCase
def test_utc?
assert_equal false, @twz.utc?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']).utc?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Etc/UTC']).utc?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Universal']).utc?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UCT']).utc?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Etc/UCT']).utc?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Etc/Universal']).utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["UTC"]).utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Etc/UTC"]).utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Universal"]).utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["UCT"]).utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Etc/UCT"]).utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Etc/Universal"]).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Africa/Abidjan']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Africa/Banjul']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Africa/Freetown']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['GMT']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['GMT0']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Greenwich']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Iceland']).utc?
- assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['Africa/Monrovia']).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Africa/Abidjan"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Africa/Banjul"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Africa/Freetown"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["GMT"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["GMT0"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Greenwich"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Iceland"]).utc?
+ assert_equal false, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Africa/Monrovia"]).utc?
end
def test_formatted_offset
- assert_equal '-05:00', @twz.formatted_offset
- assert_equal '-04:00', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset #dst
+ assert_equal "-05:00", @twz.formatted_offset
+ assert_equal "-04:00", ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset # dst
end
def test_dst?
@@ -85,12 +93,12 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_zone
- assert_equal 'EST', @twz.zone
- assert_equal 'EDT', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone #dst
+ assert_equal "EST", @twz.zone
+ assert_equal "EDT", ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone # dst
end
def test_nsec
- local = Time.local(2011,6,7,23,59,59,Rational(999999999, 1000))
+ local = Time.local(2011, 6, 7, 23, 59, 59, Rational(999999999, 1000))
with_zone = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], local)
assert_equal local.nsec, with_zone.nsec
@@ -98,28 +106,28 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_strftime
- assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z')
+ assert_equal "1999-12-31 19:00:00 EST -0500", @twz.strftime("%Y-%m-%d %H:%M:%S %Z %z")
end
def test_strftime_with_escaping
- assert_equal '%Z %z', @twz.strftime('%%Z %%z')
- assert_equal '%EST %-0500', @twz.strftime('%%%Z %%%z')
+ assert_equal "%Z %z", @twz.strftime("%%Z %%z")
+ assert_equal "%EST %-0500", @twz.strftime("%%%Z %%%z")
end
def test_inspect
- assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
end
def test_to_s
- assert_equal '1999-12-31 19:00:00 -0500', @twz.to_s
+ assert_equal "1999-12-31 19:00:00 -0500", @twz.to_s
end
def test_to_formatted_s
- assert_equal '1999-12-31 19:00:00 -0500', @twz.to_formatted_s
+ assert_equal "1999-12-31 19:00:00 -0500", @twz.to_formatted_s
end
def test_to_s_db
- assert_equal '2000-01-01 00:00:00', @twz.to_s(:db)
+ assert_equal "2000-01-01 00:00:00", @twz.to_s(:db)
end
def test_xmlschema
@@ -144,6 +152,16 @@ class TimeWithZoneTest < ActiveSupport::TestCase
assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema(nil)
end
+ def test_iso8601_with_fractional_seconds
+ @twz += Rational(1, 8)
+ assert_equal "1999-12-31T19:00:00.125-05:00", @twz.iso8601(3)
+ end
+
+ def test_rfc3339_with_fractional_seconds
+ @twz += Rational(1, 8)
+ assert_equal "1999-12-31T19:00:00.125-05:00", @twz.rfc3339(3)
+ end
+
def test_to_yaml
yaml = <<-EOF.strip_heredoc
--- !ruby/object:ActiveSupport::TimeWithZone
@@ -166,7 +184,7 @@ class TimeWithZoneTest < ActiveSupport::TestCase
time: 1999-12-31 19:00:00.000000000 Z
EOF
- assert_equal(yaml, { 'twz' => @twz }.to_yaml)
+ assert_equal(yaml, { "twz" => @twz }.to_yaml)
end
def test_yaml_load
@@ -191,11 +209,11 @@ class TimeWithZoneTest < ActiveSupport::TestCase
time: 1999-12-31 19:00:00.000000000 Z
EOF
- assert_equal({ 'twz' => @twz }, YAML.load(yaml))
+ assert_equal({ "twz" => @twz }, YAML.load(yaml))
end
def test_httpdate
- assert_equal 'Sat, 01 Jan 2000 00:00:00 GMT', @twz.httpdate
+ assert_equal "Sat, 01 Jan 2000 00:00:00 GMT", @twz.httpdate
end
def test_rfc2822
@@ -215,69 +233,69 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_compare_with_time_with_zone
- assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
- assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
- assert_equal(-1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
+ assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
+ assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
+ assert_equal(-1, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone["UTC"]))
end
def test_between?
- assert @twz.between?(Time.utc(1999,12,31,23,59,59), Time.utc(2000,1,1,0,0,1))
- assert_equal false, @twz.between?(Time.utc(2000,1,1,0,0,1), Time.utc(2000,1,1,0,0,2))
+ assert @twz.between?(Time.utc(1999, 12, 31, 23, 59, 59), Time.utc(2000, 1, 1, 0, 0, 1))
+ assert_equal false, @twz.between?(Time.utc(2000, 1, 1, 0, 0, 1), Time.utc(2000, 1, 1, 0, 0, 2))
end
def test_today
Date.stub(:current, Date.new(2000, 1, 1)) do
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(1999,12,31,23,59,59) ).today?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,0) ).today?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,23,59,59) ).today?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,2,0) ).today?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 23, 59, 59)).today?
+ assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 1, 0)).today?
+ assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 1, 23, 59, 59)).today?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 2, 0)).today?
end
end
def test_past_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stub(:current, Time.local(2005,2,10,15,30,45)) do
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
+ with_env_tz "US/Eastern" do
+ Time.stub(:current, Time.local(2005, 2, 10, 15, 30, 45)) do
+ assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 44)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 45)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 46)).past?
end
end
end
def test_past_with_time_current_as_time_with_zone
- twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 45))
Time.stub(:current, twz) do
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
+ assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 44)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 45)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 46)).past?
end
end
def test_future_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stub(:current, Time.local(2005,2,10,15,30,45)) do
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
+ with_env_tz "US/Eastern" do
+ Time.stub(:current, Time.local(2005, 2, 10, 15, 30, 45)) do
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 44)).future?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 45)).future?
+ assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 46)).future?
end
end
end
def test_future_with_time_current_as_time_with_zone
- twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 45))
Time.stub(:current, twz) do
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 44)).future?
+ assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 45)).future?
+ assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.local(2005, 2, 10, 15, 30, 46)).future?
end
end
def test_eql?
assert_equal true, @twz.eql?(@twz.dup)
assert_equal true, @twz.eql?(Time.utc(2000))
- assert_equal true, @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
- assert_equal false, @twz.eql?( Time.utc(2000, 1, 1, 0, 0, 1) )
- assert_equal false, @twz.eql?( DateTime.civil(1999, 12, 31, 23, 59, 59) )
+ assert_equal true, @twz.eql?(ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]))
+ assert_equal false, @twz.eql?(Time.utc(2000, 1, 1, 0, 0, 1))
+ assert_equal false, @twz.eql?(DateTime.civil(1999, 12, 31, 23, 59, 59))
other_twz = ActiveSupport::TimeWithZone.new(DateTime.now.utc, @time_zone)
assert_equal true, other_twz.eql?(other_twz.dup)
@@ -289,117 +307,117 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_plus_with_integer
- assert_equal Time.utc(1999, 12, 31, 19, 0 ,5), (@twz + 5).time
+ assert_equal Time.utc(1999, 12, 31, 19, 0, 5), (@twz + 5).time
end
def test_plus_with_integer_when_self_wraps_datetime
datetime = DateTime.civil(2000, 1, 1, 0)
twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
- assert_equal DateTime.civil(1999, 12, 31, 19, 0 ,5), (twz + 5).time
+ assert_equal DateTime.civil(1999, 12, 31, 19, 0, 5), (twz + 5).time
end
def test_plus_when_crossing_time_class_limit
twz = ActiveSupport::TimeWithZone.new(Time.utc(2038, 1, 19), @time_zone)
- assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0,6]
+ assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0, 6]
end
def test_plus_with_duration
- assert_equal Time.utc(2000, 1, 5, 19, 0 ,0), (@twz + 5.days).time
+ assert_equal Time.utc(2000, 1, 5, 19, 0, 0), (@twz + 5.days).time
end
def test_minus_with_integer
- assert_equal Time.utc(1999, 12, 31, 18, 59 ,55), (@twz - 5).time
+ assert_equal Time.utc(1999, 12, 31, 18, 59, 55), (@twz - 5).time
end
def test_minus_with_integer_when_self_wraps_datetime
datetime = DateTime.civil(2000, 1, 1, 0)
twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
- assert_equal DateTime.civil(1999, 12, 31, 18, 59 ,55), (twz - 5).time
+ assert_equal DateTime.civil(1999, 12, 31, 18, 59, 55), (twz - 5).time
end
def test_minus_with_duration
- assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time
+ assert_equal Time.utc(1999, 12, 26, 19, 0, 0), (@twz - 5.days).time
end
def test_minus_with_time
- assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
- assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['Hawaii'] ) - Time.utc(2000, 1, 1)
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 1)
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["Hawaii"]) - Time.utc(2000, 1, 1)
end
def test_minus_with_time_precision
- assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
- assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone['Hawaii'] ) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
+ assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
+ assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["Hawaii"]) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
end
def test_minus_with_time_with_zone
- twz1 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] )
- twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] )
- assert_equal 86_400.0, twz2 - twz1
+ twz1 = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["UTC"])
+ twz2 = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["UTC"])
+ assert_equal 86_400.0, twz2 - twz1
end
def test_minus_with_time_with_zone_precision
- twz1 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0, Rational(1, 1000)), ActiveSupport::TimeZone['UTC'] )
- twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone['UTC'] )
+ twz1 = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0, Rational(1, 1000)), ActiveSupport::TimeZone["UTC"])
+ twz2 = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"])
assert_equal 86_399.999999998, 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)
+ 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_datetime_precision
- assert_equal 86_399.999999999, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1)
+ assert_equal 86_399.999999999, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), 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)
+ 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
- utc = Time.utc(2006,4,2,6,59,59) # == Apr 2 2006 01:59:59 EST; i.e., 1 second before daylight savings start
+ utc = Time.utc(2006, 4, 2, 6, 59, 59) # == Apr 2 2006 01:59:59 EST; i.e., 1 second before daylight savings start
twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
- assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal Time.utc(2006, 4, 2, 1, 59, 59), twz.time
assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
+ assert_equal "EST", twz.zone
twz = twz + 1
- assert_equal Time.utc(2006,4,2,3), twz.time # adding 1 sec springs forward to 3:00AM EDT
+ assert_equal Time.utc(2006, 4, 2, 3), twz.time # adding 1 sec springs forward to 3:00AM EDT
assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
+ assert_equal "EDT", twz.zone
twz = twz - 1 # subtracting 1 second takes goes back to 1:59:59AM EST
- assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal Time.utc(2006, 4, 2, 1, 59, 59), twz.time
assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
+ assert_equal "EST", twz.zone
end
def test_plus_and_minus_enforce_fall_dst_rules
- utc = Time.utc(2006,10,29,5,59,59) # == Oct 29 2006 01:59:59 EST; i.e., 1 second before daylight savings end
+ utc = Time.utc(2006, 10, 29, 5, 59, 59) # == Oct 29 2006 01:59:59 EST; i.e., 1 second before daylight savings end
twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
- assert_equal Time.utc(2006,10,29,1,59,59), twz.time
+ assert_equal Time.utc(2006, 10, 29, 1, 59, 59), twz.time
assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
+ assert_equal "EDT", twz.zone
twz = twz + 1
- assert_equal Time.utc(2006,10,29,1), twz.time # adding 1 sec falls back from 1:59:59 EDT to 1:00AM EST
+ assert_equal Time.utc(2006, 10, 29, 1), twz.time # adding 1 sec falls back from 1:59:59 EDT to 1:00AM EST
assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
+ assert_equal "EST", twz.zone
twz = twz - 1
- assert_equal Time.utc(2006,10,29,1,59,59), twz.time # subtracting 1 sec goes back to 1:59:59AM EDT
+ assert_equal Time.utc(2006, 10, 29, 1, 59, 59), twz.time # subtracting 1 sec goes back to 1:59:59AM EDT
assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
+ assert_equal "EDT", twz.zone
end
def test_to_a
- assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new( Time.utc(2000, 2, 1, 15, 30, 45), ActiveSupport::TimeZone['Hawaii'] ).to_a
+ assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new(Time.utc(2000, 2, 1, 15, 30, 45), ActiveSupport::TimeZone["Hawaii"]).to_a
end
def test_to_f
- result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'] ).to_f
+ result = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["Hawaii"]).to_f
assert_equal 946684800.0, result
assert_kind_of Float, result
end
def test_to_i
- result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'] ).to_i
+ result = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["Hawaii"]).to_i
assert_equal 946684800, result
assert_kind_of Integer, result
end
@@ -411,33 +429,51 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_to_r
- result = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii']).to_r
+ result = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["Hawaii"]).to_r
assert_equal Rational(946684800, 1), result
assert_kind_of Rational, result
end
def test_time_at
- time = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'])
+ time = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["Hawaii"])
assert_equal time, Time.at(time)
end
- def test_to_time
- with_env_tz 'US/Eastern' do
- assert_equal Time, @twz.to_time.class
- assert_equal Time.local(1999, 12, 31, 19), @twz.to_time
- assert_equal Time.local(1999, 12, 31, 19).utc_offset, @twz.to_time.utc_offset
+ def test_to_time_with_preserve_timezone
+ with_preserve_timezone(true) do
+ with_env_tz "US/Eastern" do
+ time = @twz.to_time
+
+ assert_equal Time, time.class
+ assert_equal time.object_id, @twz.to_time.object_id
+ assert_equal Time.local(1999, 12, 31, 19), time
+ assert_equal Time.local(1999, 12, 31, 19).utc_offset, time.utc_offset
+ end
+ end
+ end
+
+ def test_to_time_without_preserve_timezone
+ with_preserve_timezone(false) do
+ with_env_tz "US/Eastern" do
+ time = @twz.to_time
+
+ assert_equal Time, time.class
+ assert_equal time.object_id, @twz.to_time.object_id
+ assert_equal Time.local(1999, 12, 31, 19), time
+ assert_equal Time.local(1999, 12, 31, 19).utc_offset, time.utc_offset
+ end
end
end
def test_to_date
# 1 sec before midnight Jan 1 EST
- assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 4, 59, 59), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).to_date
# midnight Jan 1 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 5, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).to_date
# 1 sec before midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 4, 59, 59), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).to_date
# midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 5, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).to_date
end
def test_to_datetime
@@ -455,6 +491,10 @@ class TimeWithZoneTest < ActiveSupport::TestCase
assert_equal false, ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone).acts_like?(:date)
end
+ def test_blank?
+ assert_not @twz.blank?
+ end
+
def test_is_a
assert_kind_of Time, @twz
assert_kind_of Time, @twz
@@ -462,12 +502,12 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_class_name
- assert_equal 'Time', ActiveSupport::TimeWithZone.name
+ assert_equal "Time", ActiveSupport::TimeWithZone.name
end
def test_method_missing_with_time_return_value
assert_instance_of ActiveSupport::TimeWithZone, @twz.months_since(1)
- assert_equal Time.utc(2000, 1, 31, 19, 0 ,0), @twz.months_since(1).time
+ assert_equal Time.utc(2000, 1, 31, 19, 0, 0), @twz.months_since(1).time
end
def test_marshal_dump_and_load
@@ -475,19 +515,19 @@ class TimeWithZoneTest < ActiveSupport::TestCase
mtime = Marshal.load(marshal_str)
assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
assert mtime.utc.utc?
- assert_equal ActiveSupport::TimeZone['Eastern Time (US & Canada)'], mtime.time_zone
+ assert_equal ActiveSupport::TimeZone["Eastern Time (US & Canada)"], mtime.time_zone
assert_equal Time.utc(1999, 12, 31, 19), mtime.time
assert mtime.time.utc?
assert_equal @twz.inspect, mtime.inspect
end
def test_marshal_dump_and_load_with_tzinfo_identifier
- twz = ActiveSupport::TimeWithZone.new(@utc, TZInfo::Timezone.get('America/New_York'))
+ twz = ActiveSupport::TimeWithZone.new(@utc, TZInfo::Timezone.get("America/New_York"))
marshal_str = Marshal.dump(twz)
mtime = Marshal.load(marshal_str)
assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
assert mtime.utc.utc?
- assert_equal 'America/New_York', mtime.time_zone.name
+ assert_equal "America/New_York", mtime.time_zone.name
assert_equal Time.utc(1999, 12, 31, 19), mtime.time
assert mtime.time.utc?
assert_equal @twz.inspect, mtime.inspect
@@ -503,17 +543,19 @@ class TimeWithZoneTest < ActiveSupport::TestCase
assert_nothing_raised do
@twz.period
@twz.time
+ @twz.to_datetime
+ @twz.to_time
end
end
def test_method_missing_with_non_time_return_value
time = @twz.time
- def time.foo; 'bar'; end
- assert_equal 'bar', @twz.foo
+ def time.foo; "bar"; end
+ assert_equal "bar", @twz.foo
end
def test_date_part_value_methods
- twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 19, 18, 17, 500), @time_zone)
assert_not_called(twz, :method_missing) do
assert_equal 1999, twz.year
assert_equal 12, twz.month
@@ -533,19 +575,19 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_usec_returns_sec_fraction_when_datetime_is_wrapped
- twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone)
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1, 2)), @time_zone)
assert_equal 500000, twz.usec
end
def test_nsec_returns_sec_fraction_when_datetime_is_wrapped
- twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone)
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1, 2)), @time_zone)
assert_equal 500000000, twz.nsec
end
def test_utc_to_local_conversion_saves_period_in_instance_variable
- assert_nil @twz.instance_variable_get('@period')
+ assert_nil @twz.instance_variable_get("@period")
@twz.time
- assert_kind_of TZInfo::TimezonePeriod, @twz.instance_variable_get('@period')
+ assert_kind_of TZInfo::TimezonePeriod, @twz.instance_variable_get("@period")
end
def test_instance_created_with_local_time_returns_correct_utc_time
@@ -554,17 +596,17 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_instance_created_with_local_time_enforces_spring_dst_rules
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,2)) # first second of DST
- assert_equal Time.utc(2006,4,2,3), twz.time # springs forward to 3AM
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 2, 2)) # first second of DST
+ assert_equal Time.utc(2006, 4, 2, 3), twz.time # springs forward to 3AM
assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
+ assert_equal "EDT", twz.zone
end
def test_instance_created_with_local_time_enforces_fall_dst_rules
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,1)) # 1AM can be either DST or non-DST; we'll pick DST
- assert_equal Time.utc(2006,10,29,1), twz.time
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 29, 1)) # 1AM can be either DST or non-DST; we'll pick DST
+ assert_equal Time.utc(2006, 10, 29, 1), twz.time
assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
+ assert_equal "EDT", twz.zone
end
def test_ruby_19_weekday_name_query_methods
@@ -575,42 +617,48 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_utc_to_local_conversion_with_far_future_datetime
- assert_equal [0,0,19,31,12,2049], ActiveSupport::TimeWithZone.new(DateTime.civil(2050), @time_zone).to_a[0,6]
+ assert_equal [0, 0, 19, 31, 12, 2049], ActiveSupport::TimeWithZone.new(DateTime.civil(2050), @time_zone).to_a[0, 6]
end
def test_local_to_utc_conversion_with_far_future_datetime
- assert_equal DateTime.civil(2050).to_f, ActiveSupport::TimeWithZone.new(nil, @time_zone, DateTime.civil(2049,12,31,19)).to_f
+ assert_equal DateTime.civil(2050).to_f, ActiveSupport::TimeWithZone.new(nil, @time_zone, DateTime.civil(2049, 12, 31, 19)).to_f
end
def test_change
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
- assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.change(:year => 2001).inspect
- assert_equal "Wed, 31 Mar 1999 19:00:00 EST -05:00", @twz.change(:month => 3).inspect
- assert_equal "Wed, 03 Mar 1999 19:00:00 EST -05:00", @twz.change(:month => 2).inspect
- assert_equal "Wed, 15 Dec 1999 19:00:00 EST -05:00", @twz.change(:day => 15).inspect
- assert_equal "Fri, 31 Dec 1999 06:00:00 EST -05:00", @twz.change(:hour => 6).inspect
- assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.change(:min => 15).inspect
- assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.change(:sec => 30).inspect
+ assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.change(year: 2001).inspect
+ assert_equal "Wed, 31 Mar 1999 19:00:00 EST -05:00", @twz.change(month: 3).inspect
+ assert_equal "Wed, 03 Mar 1999 19:00:00 EST -05:00", @twz.change(month: 2).inspect
+ assert_equal "Wed, 15 Dec 1999 19:00:00 EST -05:00", @twz.change(day: 15).inspect
+ assert_equal "Fri, 31 Dec 1999 06:00:00 EST -05:00", @twz.change(hour: 6).inspect
+ assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.change(min: 15).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.change(sec: 30).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(offset: "-10:00").inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(offset: -36000).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: "Hawaii").inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: -10).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: -36000).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: "Pacific/Honolulu").inspect
end
def test_change_at_dst_boundary
- twz = ActiveSupport::TimeWithZone.new(Time.at(1319936400).getutc, ActiveSupport::TimeZone['Madrid'])
- assert_equal twz, twz.change(:min => 0)
+ twz = ActiveSupport::TimeWithZone.new(Time.at(1319936400).getutc, ActiveSupport::TimeZone["Madrid"])
+ assert_equal twz, twz.change(min: 0)
end
def test_round_at_dst_boundary
- twz = ActiveSupport::TimeWithZone.new(Time.at(1319936400).getutc, ActiveSupport::TimeZone['Madrid'])
+ twz = ActiveSupport::TimeWithZone.new(Time.at(1319936400).getutc, ActiveSupport::TimeZone["Madrid"])
assert_equal twz, twz.round
end
def test_advance
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
- assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.advance(:years => 2).inspect
- assert_equal "Fri, 31 Mar 2000 19:00:00 EST -05:00", @twz.advance(:months => 3).inspect
- assert_equal "Tue, 04 Jan 2000 19:00:00 EST -05:00", @twz.advance(:days => 4).inspect
- assert_equal "Sat, 01 Jan 2000 01:00:00 EST -05:00", @twz.advance(:hours => 6).inspect
- assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.advance(:minutes => 15).inspect
- assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.advance(:seconds => 30).inspect
+ assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.advance(years: 2).inspect
+ assert_equal "Fri, 31 Mar 2000 19:00:00 EST -05:00", @twz.advance(months: 3).inspect
+ assert_equal "Tue, 04 Jan 2000 19:00:00 EST -05:00", @twz.advance(days: 4).inspect
+ assert_equal "Sat, 01 Jan 2000 01:00:00 EST -05:00", @twz.advance(hours: 6).inspect
+ assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.advance(minutes: 15).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.advance(seconds: 30).inspect
end
def test_beginning_of_year
@@ -675,6 +723,10 @@ class TimeWithZoneTest < ActiveSupport::TestCase
assert_equal "Fri, 31 Dec 1999 19:00:01 EST -05:00", @twz.since(1).inspect
end
+ def test_in
+ assert_equal "Fri, 31 Dec 1999 19:00:01 EST -05:00", @twz.in(1).inspect
+ end
+
def test_ago
assert_equal "Fri, 31 Dec 1999 18:59:59 EST -05:00", @twz.ago(1).inspect
end
@@ -684,204 +736,262 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_advance_1_year_from_leap_day
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2004,2,29))
- assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(:years => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2004, 2, 29))
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(years: 1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.years_since(1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.since(1.year).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.in(1.year).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", (twz + 1.year).inspect
end
def test_advance_1_month_from_last_day_of_january
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2005,1,31))
- assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(:months => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2005, 1, 31))
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(months: 1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.months_since(1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.since(1.month).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.in(1.month).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", (twz + 1.month).inspect
end
def test_advance_1_month_from_last_day_of_january_during_leap_year
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000,1,31))
- assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.advance(:months => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 31))
+ assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.advance(months: 1).inspect
assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.months_since(1).inspect
assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.since(1.month).inspect
+ assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.in(1.month).inspect
assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", (twz + 1.month).inspect
end
def test_advance_1_month_into_spring_dst_gap
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,3,2,2))
- assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(:months => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 3, 2, 2))
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(months: 1).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.months_since(1).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.since(1.month).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.in(1.month).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1.month).inspect
end
def test_advance_1_second_into_spring_dst_gap
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,1,59,59))
- assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(:seconds => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 2, 1, 59, 59))
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(seconds: 1).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1.second).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.since(1).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.since(1.second).inspect
- assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1.second).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.in(1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.in(1.second).inspect
end
def test_advance_1_day_across_spring_dst_transition
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 1, 10, 30))
# In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
# When we advance 1 day, we want to end up at the same time on the next day
- assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", twz.advance(:days => 1).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", twz.advance(days: 1).inspect
assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", twz.since(1.days).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", twz.in(1.days).inspect
assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", (twz + 1.days).inspect
assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", twz.since(1.days + 1.second).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", twz.in(1.days + 1.second).inspect
assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", (twz + 1.days + 1.second).inspect
end
def test_advance_1_day_across_spring_dst_transition_backwards
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 2, 10, 30))
# In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
# When we advance back 1 day, we want to end up at the same time on the previous day
- assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:days => -1).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(days: -1).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1.days).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1.days).inspect
assert_equal "Sat, 01 Apr 2006 10:30:01 EST -05:00", twz.ago(1.days - 1.second).inspect
end
def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_spring_dst_transition
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 1, 10, 30))
# In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
# When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 86400).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 86400.seconds).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(86400).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(86400.seconds).inspect
- assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:seconds => 86400).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.in(86400).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.in(86400.seconds).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(seconds: 86400).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 1440.minutes).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(1440.minutes).inspect
- assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:minutes => 1440).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.in(1440.minutes).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(minutes: 1440).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 24.hours).inspect
assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(24.hours).inspect
- assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:hours => 24).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.in(24.hours).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(hours: 24).inspect
end
def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_spring_dst_transition_backwards
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,11,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 2, 11, 30))
# In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
# When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 86400).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 86400.seconds).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(86400).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(86400.seconds).inspect
- assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:seconds => -86400).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(seconds: -86400).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1440.minutes).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1440.minutes).inspect
- assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:minutes => -1440).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(minutes: -1440).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 24.hours).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(24.hours).inspect
- assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:hours => -24).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(hours: -24).inspect
end
def test_advance_1_day_across_fall_dst_transition
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 28, 10, 30))
# In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
# When we advance 1 day, we want to end up at the same time on the next day
- assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", twz.advance(:days => 1).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", twz.advance(days: 1).inspect
assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", twz.since(1.days).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", twz.in(1.days).inspect
assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", (twz + 1.days).inspect
assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", twz.since(1.days + 1.second).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", twz.in(1.days + 1.second).inspect
assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", (twz + 1.days + 1.second).inspect
end
def test_advance_1_day_across_fall_dst_transition_backwards
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 29, 10, 30))
# In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
# When we advance backwards 1 day, we want to end up at the same time on the previous day
- assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:days => -1).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(days: -1).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1.days).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.days).inspect
assert_equal "Sat, 28 Oct 2006 10:30:01 EDT -04:00", twz.ago(1.days - 1.second).inspect
end
def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_fall_dst_transition
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 28, 10, 30))
# In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
# When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 86400).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 86400.seconds).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(86400).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(86400.seconds).inspect
- assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:seconds => 86400).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.in(86400).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.in(86400.seconds).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(seconds: 86400).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 1440.minutes).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(1440.minutes).inspect
- assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:minutes => 1440).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.in(1440.minutes).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(minutes: 1440).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 24.hours).inspect
assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(24.hours).inspect
- assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:hours => 24).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.in(24.hours).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(hours: 24).inspect
end
def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_fall_dst_transition_backwards
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,9,30))
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 29, 9, 30))
# In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
# When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 86400).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 86400.seconds).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(86400).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(86400.seconds).inspect
- assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:seconds => -86400).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(seconds: -86400).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1440.minutes).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1440.minutes).inspect
- assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:minutes => -1440).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(minutes: -1440).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 24.hours).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(24.hours).inspect
- assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:hours => -24).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(hours: -24).inspect
+ end
+
+ def test_advance_1_week_across_spring_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 1, 10, 30))
+ assert_equal "Sat, 08 Apr 2006 10:30:00 EDT -04:00", twz.advance(weeks: 1).inspect
+ assert_equal "Sat, 08 Apr 2006 10:30:00 EDT -04:00", twz.weeks_since(1).inspect
+ assert_equal "Sat, 08 Apr 2006 10:30:00 EDT -04:00", twz.since(1.week).inspect
+ assert_equal "Sat, 08 Apr 2006 10:30:00 EDT -04:00", twz.in(1.week).inspect
+ assert_equal "Sat, 08 Apr 2006 10:30:00 EDT -04:00", (twz + 1.week).inspect
+ end
+
+ def test_advance_1_week_across_spring_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 8, 10, 30))
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(weeks: -1).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.weeks_ago(1).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1.week).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1.week).inspect
+ end
+
+ def test_advance_1_week_across_fall_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 28, 10, 30))
+ assert_equal "Sat, 04 Nov 2006 10:30:00 EST -05:00", twz.advance(weeks: 1).inspect
+ assert_equal "Sat, 04 Nov 2006 10:30:00 EST -05:00", twz.weeks_since(1).inspect
+ assert_equal "Sat, 04 Nov 2006 10:30:00 EST -05:00", twz.since(1.week).inspect
+ assert_equal "Sat, 04 Nov 2006 10:30:00 EST -05:00", twz.in(1.week).inspect
+ assert_equal "Sat, 04 Nov 2006 10:30:00 EST -05:00", (twz + 1.week).inspect
+ end
+
+ def test_advance_1_week_across_fall_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 11, 4, 10, 30))
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(weeks: -1).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.weeks_ago(1).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1.week).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.week).inspect
end
def test_advance_1_month_across_spring_dst_transition
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30))
- assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.advance(:months => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 4, 1, 10, 30))
+ assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.advance(months: 1).inspect
assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.months_since(1).inspect
assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.since(1.month).inspect
+ assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.in(1.month).inspect
assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", (twz + 1.month).inspect
end
def test_advance_1_month_across_spring_dst_transition_backwards
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,5,1,10,30))
- assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:months => -1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 5, 1, 10, 30))
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(months: -1).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.months_ago(1).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1.month).inspect
assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1.month).inspect
end
def test_advance_1_month_across_fall_dst_transition
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30))
- assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.advance(:months => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 10, 28, 10, 30))
+ assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.advance(months: 1).inspect
assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.months_since(1).inspect
assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.since(1.month).inspect
+ assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.in(1.month).inspect
assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", (twz + 1.month).inspect
end
def test_advance_1_month_across_fall_dst_transition_backwards
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,11,28,10,30))
- assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:months => -1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006, 11, 28, 10, 30))
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(months: -1).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.months_ago(1).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1.month).inspect
assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.month).inspect
end
def test_advance_1_year
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008,2,15,10,30))
- assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.advance(:years => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008, 2, 15, 10, 30))
+ assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.advance(years: 1).inspect
assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.years_since(1).inspect
+ assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.since(1.year).inspect
+ assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.in(1.year).inspect
assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", (twz + 1.year).inspect
- assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", twz.advance(:years => -1).inspect
+ assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", twz.advance(years: -1).inspect
assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", twz.years_ago(1).inspect
assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", (twz - 1.year).inspect
end
def test_advance_1_year_during_dst
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008,7,15,10,30))
- assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.advance(:years => 1).inspect
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008, 7, 15, 10, 30))
+ assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.advance(years: 1).inspect
assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.years_since(1).inspect
+ assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.since(1.year).inspect
+ assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.in(1.year).inspect
assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", (twz + 1.year).inspect
- assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", twz.advance(:years => -1).inspect
+ assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", twz.advance(years: -1).inspect
assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", twz.years_ago(1).inspect
assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", (twz - 1.year).inspect
end
@@ -909,13 +1019,13 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
end
def test_in_time_zone
- Time.use_zone 'Alaska' do
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone.inspect
+ Time.use_zone "Alaska" do
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @t.in_time_zone.inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @dt.in_time_zone.inspect
end
- Time.use_zone 'Hawaii' do
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone.inspect
+ Time.use_zone "Hawaii" do
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @t.in_time_zone.inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @dt.in_time_zone.inspect
end
Time.use_zone nil do
assert_equal @t, @t.in_time_zone
@@ -925,20 +1035,20 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
def test_nil_time_zone
Time.use_zone nil do
- assert !@t.in_time_zone.respond_to?(:period), 'no period method'
- assert !@dt.in_time_zone.respond_to?(:period), 'no period method'
+ assert !@t.in_time_zone.respond_to?(:period), "no period method"
+ assert !@dt.in_time_zone.respond_to?(:period), "no period method"
end
end
def test_in_time_zone_with_argument
- Time.use_zone 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone('Alaska').inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone('Alaska').inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone('Hawaii').inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone('Hawaii').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @t.in_time_zone('UTC').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @dt.in_time_zone('UTC').inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone(-9.hours).inspect
+ Time.use_zone "Eastern Time (US & Canada)" do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @t.in_time_zone("Alaska").inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @dt.in_time_zone("Alaska").inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @t.in_time_zone("Hawaii").inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @dt.in_time_zone("Hawaii").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 UTC +00:00", @t.in_time_zone("UTC").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 UTC +00:00", @dt.in_time_zone("UTC").inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @t.in_time_zone(-9.hours).inspect
end
end
@@ -952,119 +1062,119 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
end
def test_in_time_zone_with_time_local_instance
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
time = Time.local(1999, 12, 31, 19) # == Time.utc(2000)
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', time.in_time_zone('Alaska').inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", time.in_time_zone("Alaska").inspect
end
end
def test_localtime
- Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ Time.zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
assert_equal @dt.in_time_zone.localtime, @dt.in_time_zone.utc.to_time.getlocal
end
def test_use_zone
- Time.zone = 'Alaska'
- Time.use_zone 'Hawaii' do
- assert_equal ActiveSupport::TimeZone['Hawaii'], Time.zone
+ Time.zone = "Alaska"
+ Time.use_zone "Hawaii" do
+ assert_equal ActiveSupport::TimeZone["Hawaii"], Time.zone
end
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
end
def test_use_zone_with_exception_raised
- Time.zone = 'Alaska'
+ Time.zone = "Alaska"
assert_raise RuntimeError do
- Time.use_zone('Hawaii') { raise RuntimeError }
+ Time.use_zone("Hawaii") { raise RuntimeError }
end
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
end
def test_use_zone_raises_on_invalid_timezone
- Time.zone = 'Alaska'
+ Time.zone = "Alaska"
assert_raise ArgumentError do
- Time.use_zone("No such timezone exists") { }
+ Time.use_zone("No such timezone exists") {}
end
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
end
def test_time_zone_getter_and_setter
- Time.zone = ActiveSupport::TimeZone['Alaska']
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
- Time.zone = 'Alaska'
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ Time.zone = ActiveSupport::TimeZone["Alaska"]
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
+ Time.zone = "Alaska"
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
Time.zone = -9.hours
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
Time.zone = nil
- assert_equal nil, Time.zone
+ assert_nil Time.zone
end
def test_time_zone_getter_and_setter_with_zone_default_set
old_zone_default = Time.zone_default
- Time.zone_default = ActiveSupport::TimeZone['Alaska']
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
- Time.zone = ActiveSupport::TimeZone['Hawaii']
- assert_equal ActiveSupport::TimeZone['Hawaii'], Time.zone
+ Time.zone_default = ActiveSupport::TimeZone["Alaska"]
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
+ Time.zone = ActiveSupport::TimeZone["Hawaii"]
+ assert_equal ActiveSupport::TimeZone["Hawaii"], Time.zone
Time.zone = nil
- assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
ensure
Time.zone_default = old_zone_default
end
def test_time_zone_setter_is_thread_safe
- Time.use_zone 'Paris' do
- t1 = Thread.new { Time.zone = 'Alaska' }.join
- t2 = Thread.new { Time.zone = 'Hawaii' }.join
+ Time.use_zone "Paris" do
+ t1 = Thread.new { Time.zone = "Alaska" }.join
+ t2 = Thread.new { Time.zone = "Hawaii" }.join
assert t1.stop?, "Thread 1 did not finish running"
assert t2.stop?, "Thread 2 did not finish running"
- assert_equal ActiveSupport::TimeZone['Paris'], Time.zone
- assert_equal ActiveSupport::TimeZone['Alaska'], t1[:time_zone]
- assert_equal ActiveSupport::TimeZone['Hawaii'], t2[:time_zone]
+ assert_equal ActiveSupport::TimeZone["Paris"], Time.zone
+ assert_equal ActiveSupport::TimeZone["Alaska"], t1[:time_zone]
+ assert_equal ActiveSupport::TimeZone["Hawaii"], t2[:time_zone]
end
end
def test_time_zone_setter_with_tzinfo_timezone_object_wraps_in_rails_time_zone
- tzinfo = TZInfo::Timezone.get('America/New_York')
+ tzinfo = TZInfo::Timezone.get("America/New_York")
Time.zone = tzinfo
assert_kind_of ActiveSupport::TimeZone, Time.zone
assert_equal tzinfo, Time.zone.tzinfo
- assert_equal 'America/New_York', Time.zone.name
+ assert_equal "America/New_York", Time.zone.name
assert_equal(-18_000, Time.zone.utc_offset)
end
def test_time_zone_setter_with_tzinfo_timezone_identifier_does_lookup_and_wraps_in_rails_time_zone
- Time.zone = 'America/New_York'
+ Time.zone = "America/New_York"
assert_kind_of ActiveSupport::TimeZone, Time.zone
- assert_equal 'America/New_York', Time.zone.tzinfo.name
- assert_equal 'America/New_York', Time.zone.name
+ assert_equal "America/New_York", Time.zone.tzinfo.name
+ assert_equal "America/New_York", Time.zone.name
assert_equal(-18_000, Time.zone.utc_offset)
end
def test_time_zone_setter_with_invalid_zone
- assert_raise(ArgumentError){ Time.zone = "No such timezone exists" }
- assert_raise(ArgumentError){ Time.zone = -15.hours }
- assert_raise(ArgumentError){ Time.zone = Object.new }
+ assert_raise(ArgumentError) { Time.zone = "No such timezone exists" }
+ assert_raise(ArgumentError) { Time.zone = -15.hours }
+ assert_raise(ArgumentError) { Time.zone = Object.new }
end
def test_find_zone_without_bang_returns_nil_if_time_zone_can_not_be_found
- assert_nil Time.find_zone('No such timezone exists')
+ assert_nil Time.find_zone("No such timezone exists")
assert_nil Time.find_zone(-15.hours)
assert_nil Time.find_zone(Object.new)
end
def test_find_zone_with_bang_raises_if_time_zone_can_not_be_found
- assert_raise(ArgumentError) { Time.find_zone!('No such timezone exists') }
+ assert_raise(ArgumentError) { Time.find_zone!("No such timezone exists") }
assert_raise(ArgumentError) { Time.find_zone!(-15.hours) }
assert_raise(ArgumentError) { Time.find_zone!(Object.new) }
end
def test_time_zone_setter_with_find_zone_without_bang
- assert_nil Time.zone = Time.find_zone('No such timezone exists')
+ assert_nil Time.zone = Time.find_zone("No such timezone exists")
assert_nil Time.zone = Time.find_zone(-15.hours)
assert_nil Time.zone = Time.find_zone(Object.new)
end
def test_current_returns_time_now_when_zone_not_set
- with_env_tz 'US/Eastern' do
+ with_env_tz "US/Eastern" do
Time.stub(:now, Time.local(2000)) do
assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone)
assert_equal Time.local(2000), Time.current
@@ -1073,22 +1183,22 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
end
def test_current_returns_time_zone_now_when_zone_set
- Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
+ Time.zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ with_env_tz "US/Eastern" do
Time.stub(:now, Time.local(2000)) do
assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
- assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name
+ assert_equal "Eastern Time (US & Canada)", Time.current.time_zone.name
assert_equal Time.utc(2000), Time.current.time
end
end
end
def test_time_in_time_zone_doesnt_affect_receiver
- with_env_tz 'Europe/London' do
+ with_env_tz "Europe/London" do
time = Time.local(2000, 7, 1)
- time_with_zone = time.in_time_zone('Eastern Time (US & Canada)')
+ time_with_zone = time.in_time_zone("Eastern Time (US & Canada)")
assert_equal Time.utc(2000, 6, 30, 23, 0, 0), time_with_zone
- assert_not time.utc?, 'time expected to be local, but is UTC'
+ assert_not time.utc?, "time expected to be local, but is UTC"
end
end
end
@@ -1101,11 +1211,11 @@ class TimeWithZoneMethodsForDate < ActiveSupport::TestCase
end
def test_in_time_zone
- with_tz_default 'Alaska' do
- assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone.inspect
+ with_tz_default "Alaska" do
+ assert_equal "Sat, 01 Jan 2000 00:00:00 AKST -09:00", @d.in_time_zone.inspect
end
- with_tz_default 'Hawaii' do
- assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @d.in_time_zone.inspect
+ with_tz_default "Hawaii" do
+ assert_equal "Sat, 01 Jan 2000 00:00:00 HST -10:00", @d.in_time_zone.inspect
end
with_tz_default nil do
assert_equal @d.to_time, @d.in_time_zone
@@ -1114,16 +1224,16 @@ class TimeWithZoneMethodsForDate < ActiveSupport::TestCase
def test_nil_time_zone
with_tz_default nil do
- assert !@d.in_time_zone.respond_to?(:period), 'no period method'
+ assert !@d.in_time_zone.respond_to?(:period), "no period method"
end
end
def test_in_time_zone_with_argument
- with_tz_default 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
- assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone('Alaska').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @d.in_time_zone('Hawaii').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @d.in_time_zone('UTC').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone(-9.hours).inspect
+ with_tz_default "Eastern Time (US & Canada)" do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal "Sat, 01 Jan 2000 00:00:00 AKST -09:00", @d.in_time_zone("Alaska").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 HST -10:00", @d.in_time_zone("Hawaii").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 UTC +00:00", @d.in_time_zone("UTC").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 AKST -09:00", @d.in_time_zone(-9.hours).inspect
end
end
@@ -1144,15 +1254,15 @@ class TimeWithZoneMethodsForString < ActiveSupport::TestCase
end
def test_in_time_zone
- with_tz_default 'Alaska' do
- assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone.inspect
+ with_tz_default "Alaska" do
+ assert_equal "Sat, 01 Jan 2000 00:00:00 AKST -09:00", @s.in_time_zone.inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @u.in_time_zone.inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @z.in_time_zone.inspect
end
- with_tz_default 'Hawaii' do
- assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @s.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @u.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @z.in_time_zone.inspect
+ with_tz_default "Hawaii" do
+ assert_equal "Sat, 01 Jan 2000 00:00:00 HST -10:00", @s.in_time_zone.inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @u.in_time_zone.inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @z.in_time_zone.inspect
end
with_tz_default nil do
assert_equal @s.to_time, @s.in_time_zone
@@ -1163,26 +1273,26 @@ class TimeWithZoneMethodsForString < ActiveSupport::TestCase
def test_nil_time_zone
with_tz_default nil do
- assert !@s.in_time_zone.respond_to?(:period), 'no period method'
- assert !@u.in_time_zone.respond_to?(:period), 'no period method'
- assert !@z.in_time_zone.respond_to?(:period), 'no period method'
+ assert !@s.in_time_zone.respond_to?(:period), "no period method"
+ assert !@u.in_time_zone.respond_to?(:period), "no period method"
+ assert !@z.in_time_zone.respond_to?(:period), "no period method"
end
end
def test_in_time_zone_with_argument
- with_tz_default 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
- assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone('Alaska').inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone('Alaska').inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone('Alaska').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @s.in_time_zone('Hawaii').inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @u.in_time_zone('Hawaii').inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @z.in_time_zone('Hawaii').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @s.in_time_zone('UTC').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @u.in_time_zone('UTC').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @z.in_time_zone('UTC').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone(-9.hours).inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone(-9.hours).inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone(-9.hours).inspect
+ with_tz_default "Eastern Time (US & Canada)" do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal "Sat, 01 Jan 2000 00:00:00 AKST -09:00", @s.in_time_zone("Alaska").inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @u.in_time_zone("Alaska").inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @z.in_time_zone("Alaska").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 HST -10:00", @s.in_time_zone("Hawaii").inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @u.in_time_zone("Hawaii").inspect
+ assert_equal "Fri, 31 Dec 1999 14:00:00 HST -10:00", @z.in_time_zone("Hawaii").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 UTC +00:00", @s.in_time_zone("UTC").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 UTC +00:00", @u.in_time_zone("UTC").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 UTC +00:00", @z.in_time_zone("UTC").inspect
+ assert_equal "Sat, 01 Jan 2000 00:00:00 AKST -09:00", @s.in_time_zone(-9.hours).inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @u.in_time_zone(-9.hours).inspect
+ assert_equal "Fri, 31 Dec 1999 15:00:00 AKST -09:00", @z.in_time_zone(-9.hours).inspect
end
end
@@ -1197,4 +1307,10 @@ class TimeWithZoneMethodsForString < ActiveSupport::TestCase
assert_raise(ArgumentError) { @u.in_time_zone(Object.new) }
assert_raise(ArgumentError) { @z.in_time_zone(Object.new) }
end
+
+ def test_in_time_zone_with_ambiguous_time
+ with_tz_default "Moscow" do
+ assert_equal Time.utc(2014, 10, 25, 22, 0, 0), "2014-10-26 01:00:00".in_time_zone
+ end
+ end
end
diff --git a/activesupport/test/core_ext/uri_ext_test.rb b/activesupport/test/core_ext/uri_ext_test.rb
index 1694fe7e72..8816b0d392 100644
--- a/activesupport/test/core_ext/uri_ext_test.rb
+++ b/activesupport/test/core_ext/uri_ext_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'uri'
-require 'active_support/core_ext/uri'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "uri"
+require "active_support/core_ext/uri"
class URIExtTest < ActiveSupport::TestCase
def test_uri_decode_handle_multibyte
diff --git a/activesupport/test/current_attributes_test.rb b/activesupport/test/current_attributes_test.rb
new file mode 100644
index 0000000000..1669f08f68
--- /dev/null
+++ b/activesupport/test/current_attributes_test.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+
+class CurrentAttributesTest < ActiveSupport::TestCase
+ Person = Struct.new(:name, :time_zone)
+
+ class Current < ActiveSupport::CurrentAttributes
+ attribute :world, :account, :person, :request
+ delegate :time_zone, to: :person
+
+ resets { Time.zone = "UTC" }
+
+ def account=(account)
+ super
+ self.person = "#{account}'s person"
+ end
+
+ def person=(person)
+ super
+ Time.zone = person.try(:time_zone)
+ end
+
+ def request
+ "#{super} something"
+ end
+
+ def intro
+ "#{person.name}, in #{time_zone}"
+ end
+ end
+
+ setup do
+ @original_time_zone = Time.zone
+ Current.reset
+ end
+
+ teardown do
+ Time.zone = @original_time_zone
+ end
+
+ test "read and write attribute" do
+ Current.world = "world/1"
+ assert_equal "world/1", Current.world
+ end
+
+ test "read overwritten attribute method" do
+ Current.request = "request/1"
+ assert_equal "request/1 something", Current.request
+ end
+
+ test "set attribute via overwritten method" do
+ Current.account = "account/1"
+ assert_equal "account/1", Current.account
+ assert_equal "account/1's person", Current.person
+ end
+
+ test "set auxiliary class via overwritten method" do
+ Current.person = Person.new("David", "Central Time (US & Canada)")
+ assert_equal "Central Time (US & Canada)", Time.zone.name
+ end
+
+ test "resets auxiliary class via callback" do
+ Current.person = Person.new("David", "Central Time (US & Canada)")
+ assert_equal "Central Time (US & Canada)", Time.zone.name
+
+ Current.reset
+ assert_equal "UTC", Time.zone.name
+ end
+
+ test "set attribute only via scope" do
+ Current.world = "world/1"
+
+ Current.set(world: "world/2") do
+ assert_equal "world/2", Current.world
+ end
+
+ assert_equal "world/1", Current.world
+ end
+
+ test "set multiple attributes" do
+ Current.world = "world/1"
+ Current.account = "account/1"
+
+ Current.set(world: "world/2", account: "account/2") do
+ assert_equal "world/2", Current.world
+ assert_equal "account/2", Current.account
+ end
+
+ assert_equal "world/1", Current.world
+ assert_equal "account/1", Current.account
+ end
+
+ test "delegation" do
+ Current.person = Person.new("David", "Central Time (US & Canada)")
+ assert_equal "Central Time (US & Canada)", Current.time_zone
+ assert_equal "Central Time (US & Canada)", Current.instance.time_zone
+ end
+
+ test "all methods forward to the instance" do
+ Current.person = Person.new("David", "Central Time (US & Canada)")
+ assert_equal "David, in Central Time (US & Canada)", Current.intro
+ assert_equal "David, in Central Time (US & Canada)", Current.instance.intro
+ end
+end
diff --git a/activesupport/test/dependencies/check_warnings.rb b/activesupport/test/dependencies/check_warnings.rb
index 03c3dca1d6..f7d7d2dbc7 100644
--- a/activesupport/test/dependencies/check_warnings.rb
+++ b/activesupport/test/dependencies/check_warnings.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
$check_warnings_load_count += 1
$checked_verbose = $VERBOSE
diff --git a/activesupport/test/dependencies/conflict.rb b/activesupport/test/dependencies/conflict.rb
index e888b7b54c..aa22ec0b09 100644
--- a/activesupport/test/dependencies/conflict.rb
+++ b/activesupport/test/dependencies/conflict.rb
@@ -1 +1,3 @@
-Conflict = 1 \ No newline at end of file
+# frozen_string_literal: true
+
+Conflict = 1
diff --git a/activesupport/test/dependencies/cross_site_depender.rb b/activesupport/test/dependencies/cross_site_depender.rb
index a31015fc5e..3ddea7fc4b 100644
--- a/activesupport/test/dependencies/cross_site_depender.rb
+++ b/activesupport/test/dependencies/cross_site_depender.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
class CrossSiteDepender
CrossSiteDependency
-end \ No newline at end of file
+end
diff --git a/activesupport/test/dependencies/mutual_one.rb b/activesupport/test/dependencies/mutual_one.rb
index 576eb31711..bb48fddd4d 100644
--- a/activesupport/test/dependencies/mutual_one.rb
+++ b/activesupport/test/dependencies/mutual_one.rb
@@ -1,4 +1,6 @@
+# frozen_string_literal: true
+
$mutual_dependencies_count += 1
-require_dependency 'mutual_two'
-require_dependency 'mutual_two.rb'
-require_dependency 'mutual_two'
+require_dependency "mutual_two"
+require_dependency "mutual_two.rb"
+require_dependency "mutual_two"
diff --git a/activesupport/test/dependencies/mutual_two.rb b/activesupport/test/dependencies/mutual_two.rb
index fdbc2dcd84..ed354ed75e 100644
--- a/activesupport/test/dependencies/mutual_two.rb
+++ b/activesupport/test/dependencies/mutual_two.rb
@@ -1,4 +1,6 @@
+# frozen_string_literal: true
+
$mutual_dependencies_count += 1
-require_dependency 'mutual_one.rb'
-require_dependency 'mutual_one'
-require_dependency 'mutual_one.rb'
+require_dependency "mutual_one.rb"
+require_dependency "mutual_one"
+require_dependency "mutual_one.rb"
diff --git a/activesupport/test/dependencies/raises_exception.rb b/activesupport/test/dependencies/raises_exception.rb
index dd745ac20e..67bfaabb3e 100644
--- a/activesupport/test/dependencies/raises_exception.rb
+++ b/activesupport/test/dependencies/raises_exception.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
$raises_exception_load_count += 1
-raise Exception, 'Loading me failed, so do not add to loaded or history.'
+raise Exception, "Loading me failed, so do not add to loaded or history."
$raises_exception_load_count += 1
diff --git a/activesupport/test/dependencies/raises_exception_without_blame_file.rb b/activesupport/test/dependencies/raises_exception_without_blame_file.rb
index 4b2da6ff30..3a6533cd3a 100644
--- a/activesupport/test/dependencies/raises_exception_without_blame_file.rb
+++ b/activesupport/test/dependencies/raises_exception_without_blame_file.rb
@@ -1,4 +1,6 @@
-exception = Exception.new('I am not blamable!')
+# frozen_string_literal: true
+
+exception = Exception.new("I am not blamable!")
class << exception
undef_method(:blame_file!)
end
diff --git a/activesupport/test/dependencies/requires_nonexistent0.rb b/activesupport/test/dependencies/requires_nonexistent0.rb
index 7e24b3916c..d09dbd2485 100644
--- a/activesupport/test/dependencies/requires_nonexistent0.rb
+++ b/activesupport/test/dependencies/requires_nonexistent0.rb
@@ -1 +1,3 @@
-require 'RMagickDontExistDude'
+# frozen_string_literal: true
+
+require "RMagickDontExistDude"
diff --git a/activesupport/test/dependencies/requires_nonexistent1.rb b/activesupport/test/dependencies/requires_nonexistent1.rb
index 41e6668164..ce96229172 100644
--- a/activesupport/test/dependencies/requires_nonexistent1.rb
+++ b/activesupport/test/dependencies/requires_nonexistent1.rb
@@ -1 +1,3 @@
-require_dependency 'requires_nonexistent0'
+# frozen_string_literal: true
+
+require_dependency "requires_nonexistent0"
diff --git a/activesupport/test/dependencies/service_one.rb b/activesupport/test/dependencies/service_one.rb
index f43bfea235..2a4a39144d 100644
--- a/activesupport/test/dependencies/service_one.rb
+++ b/activesupport/test/dependencies/service_one.rb
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+
$loaded_service_one ||= 0
$loaded_service_one += 1
class ServiceOne
-end \ No newline at end of file
+end
diff --git a/activesupport/test/dependencies/service_two.rb b/activesupport/test/dependencies/service_two.rb
index 5205a78bb8..29cd73cbcd 100644
--- a/activesupport/test/dependencies/service_two.rb
+++ b/activesupport/test/dependencies/service_two.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class ServiceTwo
-end \ No newline at end of file
+end
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 04e7b24d30..d636da46d2 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -1,7 +1,9 @@
-require 'abstract_unit'
-require 'pp'
-require 'active_support/dependencies'
-require 'dependencies_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "pp"
+require "active_support/dependencies"
+require "dependencies_test_helpers"
module ModuleWithMissing
mattr_accessor :missing_count
@@ -29,18 +31,18 @@ class DependenciesTest < ActiveSupport::TestCase
def test_depend_on_path
expected = assert_raises(LoadError) do
- Kernel.require 'omgwtfbbq'
+ Kernel.require "omgwtfbbq"
end
e = assert_raises(LoadError) do
- ActiveSupport::Dependencies.depend_on 'omgwtfbbq'
+ ActiveSupport::Dependencies.depend_on "omgwtfbbq"
end
assert_equal expected.path, e.path
end
def test_require_dependency_accepts_an_object_which_implements_to_path
o = Object.new
- def o.to_path; 'dependencies/service_one'; end
+ def o.to_path; "dependencies/service_one"; end
assert_nothing_raised {
require_dependency o
}
@@ -51,8 +53,8 @@ class DependenciesTest < ActiveSupport::TestCase
def test_tracking_loaded_files
with_loading do
- require_dependency 'dependencies/service_one'
- require_dependency 'dependencies/service_two'
+ require_dependency "dependencies/service_one"
+ require_dependency "dependencies/service_two"
assert_equal 2, ActiveSupport::Dependencies.loaded.size
end
ensure
@@ -61,8 +63,8 @@ class DependenciesTest < ActiveSupport::TestCase
def test_tracking_identical_loaded_files
with_loading do
- require_dependency 'dependencies/service_one'
- require_dependency 'dependencies/service_one'
+ require_dependency "dependencies/service_one"
+ require_dependency "dependencies/service_one"
assert_equal 1, ActiveSupport::Dependencies.loaded.size
end
ensure
@@ -75,16 +77,16 @@ class DependenciesTest < ActiveSupport::TestCase
def test_dependency_which_raises_exception_isnt_added_to_loaded_set
with_loading do
- filename = 'dependencies/raises_exception'
+ filename = "dependencies/raises_exception"
expanded = File.expand_path(filename)
$raises_exception_load_count = 0
5.times do |count|
- e = assert_raise Exception, 'should have loaded dependencies/raises_exception which raises an exception' do
+ e = assert_raise Exception, "should have loaded dependencies/raises_exception which raises an exception" do
require_dependency filename
end
- assert_equal 'Loading me failed, so do not add to loaded or history.', e.message
+ assert_equal "Loading me failed, so do not add to loaded or history.", e.message
assert_equal count + 1, $raises_exception_load_count
assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
@@ -95,16 +97,16 @@ class DependenciesTest < ActiveSupport::TestCase
def test_dependency_which_raises_doesnt_blindly_call_blame_file!
with_loading do
- filename = 'dependencies/raises_exception_without_blame_file'
+ filename = "dependencies/raises_exception_without_blame_file"
assert_raises(Exception) { require_dependency filename }
end
end
def test_warnings_should_be_enabled_on_first_load
- with_loading 'dependencies' do
+ with_loading "dependencies" do
old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true
filename = "check_warnings"
- expanded = File.expand_path("#{File.dirname(__FILE__)}/dependencies/#{filename}")
+ expanded = File.expand_path("dependencies/#{filename}", __dir__)
$check_warnings_load_count = 0
assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
@@ -112,41 +114,41 @@ class DependenciesTest < ActiveSupport::TestCase
silence_warnings { require_dependency filename }
assert_equal 1, $check_warnings_load_count
- assert_equal true, $checked_verbose, 'On first load warnings should be enabled.'
+ assert_equal true, $checked_verbose, "On first load warnings should be enabled."
- assert ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert_includes ActiveSupport::Dependencies.loaded, expanded
ActiveSupport::Dependencies.clear
assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
- assert ActiveSupport::Dependencies.history.include?(expanded)
+ assert_includes ActiveSupport::Dependencies.history, expanded
silence_warnings { require_dependency filename }
assert_equal 2, $check_warnings_load_count
- assert_equal nil, $checked_verbose, 'After first load warnings should be left alone.'
+ assert_nil $checked_verbose, "After first load warnings should be left alone."
- assert ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert_includes ActiveSupport::Dependencies.loaded, expanded
ActiveSupport::Dependencies.clear
assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
- assert ActiveSupport::Dependencies.history.include?(expanded)
+ assert_includes ActiveSupport::Dependencies.history, expanded
enable_warnings { require_dependency filename }
assert_equal 3, $check_warnings_load_count
- assert_equal true, $checked_verbose, 'After first load warnings should be left alone.'
+ assert_equal true, $checked_verbose, "After first load warnings should be left alone."
- assert ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert_includes ActiveSupport::Dependencies.loaded, expanded
ActiveSupport::Dependencies.warnings_on_first_load = old_warnings
end
end
def test_mutual_dependencies_dont_infinite_loop
- with_loading 'dependencies' do
+ with_loading "dependencies" do
$mutual_dependencies_count = 0
- assert_nothing_raised { require_dependency 'mutual_one' }
+ assert_nothing_raised { require_dependency "mutual_one" }
assert_equal 2, $mutual_dependencies_count
ActiveSupport::Dependencies.clear
$mutual_dependencies_count = 0
- assert_nothing_raised { require_dependency 'mutual_two' }
+ assert_nothing_raised { require_dependency "mutual_two" }
assert_equal 2, $mutual_dependencies_count
end
end
@@ -167,7 +169,7 @@ class DependenciesTest < ActiveSupport::TestCase
def test_require_dependency_does_not_assume_any_particular_constant_is_defined
with_autoloading_fixtures do
- require_dependency 'typo'
+ require_dependency "typo"
assert_equal 1, TypO
end
end
@@ -175,7 +177,7 @@ class DependenciesTest < ActiveSupport::TestCase
# Regression, see https://github.com/rails/rails/issues/16468.
def test_require_dependency_interaction_with_autoloading
with_autoloading_fixtures do
- require_dependency 'typo'
+ require_dependency "typo"
assert_equal 1, TypO
e = assert_raise(LoadError) { Typo }
@@ -253,7 +255,7 @@ class DependenciesTest < ActiveSupport::TestCase
with_autoloading_fixtures do
assert_kind_of Class, ClassFolder::ClassFolderSubclass
assert_kind_of Class, ClassFolder
- assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder
+ assert_equal "indeed", ClassFolder::ClassFolderSubclass::ConstantInClassFolder
end
ensure
remove_constants(:ClassFolder)
@@ -271,7 +273,8 @@ class DependenciesTest < ActiveSupport::TestCase
def test_raising_discards_autoloaded_constants
with_autoloading_fixtures do
- assert_raises(Exception, 'arbitray exception message') { RaisesArbitraryException }
+ e = assert_raises(Exception) { RaisesArbitraryException }
+ assert_equal("arbitrary exception message", e.message)
assert_not defined?(A)
assert_not defined?(RaisesArbitraryException)
end
@@ -292,7 +295,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_doesnt_break_normal_require
- path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ path = File.expand_path("autoloading_fixtures/load_path", __dir__)
original_path = $:.dup
$:.push(path)
with_autoloading_fixtures do
@@ -311,7 +314,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_doesnt_break_normal_require_nested
- path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ path = File.expand_path("autoloading_fixtures/load_path", __dir__)
original_path = $:.dup
$:.push(path)
@@ -331,12 +334,12 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_require_returns_true_when_file_not_yet_required
- path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ path = File.expand_path("autoloading_fixtures/load_path", __dir__)
original_path = $:.dup
$:.push(path)
with_loading do
- assert_equal true, require('loaded_constant')
+ assert_equal true, require("loaded_constant")
end
ensure
remove_constants(:LoadedConstant)
@@ -344,13 +347,13 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_require_returns_true_when_file_not_yet_required_even_when_no_new_constants_added
- path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ path = File.expand_path("autoloading_fixtures/load_path", __dir__)
original_path = $:.dup
$:.push(path)
with_loading do
Object.module_eval "module LoadedConstant; end"
- assert_equal true, require('loaded_constant')
+ assert_equal true, require("loaded_constant")
end
ensure
remove_constants(:LoadedConstant)
@@ -358,13 +361,13 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_require_returns_false_when_file_already_required
- path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ path = File.expand_path("autoloading_fixtures/load_path", __dir__)
original_path = $:.dup
$:.push(path)
with_loading do
- require 'loaded_constant'
- assert_equal false, require('loaded_constant')
+ require "loaded_constant"
+ assert_equal false, require("loaded_constant")
end
ensure
remove_constants(:LoadedConstant)
@@ -373,18 +376,18 @@ class DependenciesTest < ActiveSupport::TestCase
def test_require_raises_load_error_when_file_not_found
with_loading do
- assert_raise(LoadError) { require 'this_file_dont_exist_dude' }
+ assert_raise(LoadError) { require "this_file_dont_exist_dude" }
end
end
def test_load_returns_true_when_file_found
- path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ path = File.expand_path("autoloading_fixtures/load_path", __dir__)
original_path = $:.dup
$:.push(path)
with_loading do
- assert_equal true, load('loaded_constant.rb')
- assert_equal true, load('loaded_constant.rb')
+ assert_equal true, load("loaded_constant.rb")
+ assert_equal true, load("loaded_constant.rb")
end
ensure
remove_constants(:LoadedConstant)
@@ -393,18 +396,21 @@ class DependenciesTest < ActiveSupport::TestCase
def test_load_raises_load_error_when_file_not_found
with_loading do
- assert_raise(LoadError) { load 'this_file_dont_exist_dude.rb' }
+ assert_raise(LoadError) { load "this_file_dont_exist_dude.rb" }
end
end
- def failing_test_access_thru_and_upwards_fails
- with_autoloading_fixtures do
- assert_not defined?(ModuleFolder)
- assert_raise(NameError) { ModuleFolder::Object }
- assert_raise(NameError) { ModuleFolder::NestedClass::Object }
+ # This raises only on 2.5.. (warns on ..2.4)
+ if RUBY_VERSION > "2.5"
+ def test_access_thru_and_upwards_fails
+ with_autoloading_fixtures do
+ assert_not defined?(ModuleFolder)
+ assert_raise(NameError) { ModuleFolder::Object }
+ assert_raise(NameError) { ModuleFolder::NestedClass::Object }
+ end
+ ensure
+ remove_constants(:ModuleFolder)
end
- ensure
- remove_constants(:ModuleFolder)
end
def test_non_existing_const_raises_name_error_with_fully_qualified_name
@@ -429,38 +435,38 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_loadable_constants_for_path_should_handle_empty_autoloads
- assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path('hello')
+ assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path("hello")
end
def test_loadable_constants_for_path_should_handle_relative_paths
- fake_root = 'dependencies'
- relative_root = File.dirname(__FILE__) + '/dependencies'
- ['', '/'].each do |suffix|
+ fake_root = "dependencies"
+ relative_root = File.expand_path("dependencies", __dir__)
+ ["", "/"].each do |suffix|
with_loading fake_root + suffix do
- assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(relative_root + '/a/b')
+ assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(relative_root + "/a/b")
end
end
end
def test_loadable_constants_for_path_should_provide_all_results
- fake_root = '/usr/apps/backpack'
- with_loading fake_root, fake_root + '/lib' do
+ fake_root = "/usr/apps/backpack"
+ with_loading fake_root, fake_root + "/lib" do
root = ActiveSupport::Dependencies.autoload_paths.first
- assert_equal ["Lib::A::B", "A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/lib/a/b')
+ assert_equal ["Lib::A::B", "A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + "/lib/a/b")
end
end
def test_loadable_constants_for_path_should_uniq_results
- fake_root = '/usr/apps/backpack/lib'
- with_loading fake_root, fake_root + '/' do
+ fake_root = "/usr/apps/backpack/lib"
+ with_loading fake_root, fake_root + "/" do
root = ActiveSupport::Dependencies.autoload_paths.first
- assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/a/b')
+ assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + "/a/b")
end
end
def test_loadable_constants_with_load_path_without_trailing_slash
- path = File.dirname(__FILE__) + '/autoloading_fixtures/class_folder/inline_class.rb'
- with_loading 'autoloading_fixtures/class/' do
+ path = File.expand_path("autoloading_fixtures/class_folder/inline_class.rb", __dir__)
+ with_loading "autoloading_fixtures/class/" do
assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path(path)
end
end
@@ -524,31 +530,30 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_file_search
- with_loading 'dependencies' do
+ with_loading "dependencies" do
root = ActiveSupport::Dependencies.autoload_paths.first
- assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three')
- assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three.rb')
- assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one')
- assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one.rb')
+ assert_nil ActiveSupport::Dependencies.search_for_file("service_three")
+ assert_nil ActiveSupport::Dependencies.search_for_file("service_three.rb")
+ assert_equal root + "/service_one.rb", ActiveSupport::Dependencies.search_for_file("service_one")
+ assert_equal root + "/service_one.rb", ActiveSupport::Dependencies.search_for_file("service_one.rb")
end
end
def test_file_search_uses_first_in_load_path
- with_loading 'dependencies', 'autoloading_fixtures' do
+ with_loading "dependencies", "autoloading_fixtures" do
deps, autoload = ActiveSupport::Dependencies.autoload_paths
assert_match %r/dependencies/, deps
assert_match %r/autoloading_fixtures/, autoload
- assert_equal deps + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict')
+ assert_equal deps + "/conflict.rb", ActiveSupport::Dependencies.search_for_file("conflict")
end
- with_loading 'autoloading_fixtures', 'dependencies' do
+ with_loading "autoloading_fixtures", "dependencies" do
autoload, deps = ActiveSupport::Dependencies.autoload_paths
assert_match %r/dependencies/, deps
assert_match %r/autoloading_fixtures/, autoload
- assert_equal autoload + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict')
+ assert_equal autoload + "/conflict.rb", ActiveSupport::Dependencies.search_for_file("conflict")
end
-
end
def test_custom_const_missing_should_work
@@ -584,11 +589,11 @@ class DependenciesTest < ActiveSupport::TestCase
def test_const_missing_in_anonymous_modules_raises_if_the_constant_belongs_to_Object
with_autoloading_fixtures do
- require_dependency 'em'
+ require_dependency "em"
mod = Module.new
e = assert_raise(NameError) { mod::EM }
- assert_equal 'EM cannot be autoloaded from an anonymous class or module', e.message
+ assert_equal "EM cannot be autoloaded from an anonymous class or module", e.message
assert_equal :EM, e.name
end
ensure
@@ -596,7 +601,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_removal_from_tree_should_be_detected
- with_loading 'dependencies' do
+ with_loading "dependencies" do
c = ServiceOne
ActiveSupport::Dependencies.clear
assert_not defined?(ServiceOne)
@@ -610,7 +615,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_references_should_work
- with_loading 'dependencies' do
+ with_loading "dependencies" do
c = ActiveSupport::Dependencies.reference("ServiceOne")
service_one_first = ServiceOne
assert_equal service_one_first, c.get("ServiceOne")
@@ -625,7 +630,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_constantize_shortcut_for_cached_constant_lookups
- with_loading 'dependencies' do
+ with_loading "dependencies" do
assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne")
end
ensure
@@ -633,7 +638,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_nested_load_error_isnt_rescued
- with_loading 'dependencies' do
+ with_loading "dependencies" do
assert_raise(LoadError) do
RequiresNonexistent1
end
@@ -659,7 +664,7 @@ class DependenciesTest < ActiveSupport::TestCase
def test_autoload_once_pathnames_do_not_add_to_autoloaded_constants
with_autoloading_fixtures do
- pathnames = ActiveSupport::Dependencies.autoload_paths.collect{|p| Pathname.new(p)}
+ pathnames = ActiveSupport::Dependencies.autoload_paths.collect { |p| Pathname.new(p) }
ActiveSupport::Dependencies.autoload_paths = pathnames
ActiveSupport::Dependencies.autoload_once_paths = pathnames
@@ -677,7 +682,7 @@ class DependenciesTest < ActiveSupport::TestCase
def test_application_should_special_case_application_controller
with_autoloading_fixtures do
- require_dependency 'application'
+ require_dependency "application"
assert_equal 10, ApplicationController
assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController)
end
@@ -687,14 +692,14 @@ class DependenciesTest < ActiveSupport::TestCase
def test_preexisting_constants_are_not_marked_as_autoloaded
with_autoloading_fixtures do
- require_dependency 'em'
+ require_dependency "em"
assert ActiveSupport::Dependencies.autoloaded?(:EM)
ActiveSupport::Dependencies.clear
end
Object.const_set :EM, Class.new
with_autoloading_fixtures do
- require_dependency 'em'
+ require_dependency "em"
assert ! ActiveSupport::Dependencies.autoloaded?(:EM), "EM shouldn't be marked autoloaded!"
ActiveSupport::Dependencies.clear
end
@@ -756,15 +761,15 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_new_contants_in_without_constants
- assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) { })
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) {})
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k, v| v.empty? }
end
def test_new_constants_in_with_a_single_constant
assert_equal ["Hello"], ActiveSupport::Dependencies.new_constants_in(Object) {
Object.const_set :Hello, 10
}.map(&:to_s)
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k, v| v.empty? }
ensure
remove_constants(:Hello)
end
@@ -781,7 +786,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s)
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k, v| v.empty? }
ensure
remove_constants(:OuterBefore, :Inner, :OuterAfter)
end
@@ -800,7 +805,7 @@ class DependenciesTest < ActiveSupport::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k, v| v.empty? }
ensure
remove_constants(:M)
end
@@ -818,7 +823,7 @@ class DependenciesTest < ActiveSupport::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k, v| v.empty? }
ensure
remove_constants(:M)
end
@@ -841,7 +846,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_not defined?(MultipleConstantFile)
assert_not defined?(SiblingConstant)
- require_dependency 'multiple_constant_file'
+ require_dependency "multiple_constant_file"
assert defined?(MultipleConstantFile)
assert defined?(SiblingConstant)
assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile)
@@ -881,7 +886,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_not defined?(ClassFolder::NestedClass)
assert_not defined?(ClassFolder::SiblingClass)
- require_dependency 'class_folder/nested_class'
+ require_dependency "class_folder/nested_class"
assert defined?(ClassFolder::NestedClass)
assert defined?(ClassFolder::SiblingClass)
@@ -959,7 +964,7 @@ class DependenciesTest < ActiveSupport::TestCase
e = assert_raise NameError do
::RaisesNameError::FooBarBaz.object_id
end
- assert_equal 'uninitialized constant RaisesNameError::FooBarBaz', e.message
+ assert_equal "uninitialized constant RaisesNameError::FooBarBaz", e.message
assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!"
end
@@ -974,8 +979,8 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_remove_constant_handles_double_colon_at_start
- Object.const_set 'DeleteMe', Module.new
- DeleteMe.const_set 'OrMe', Module.new
+ Object.const_set "DeleteMe", Module.new
+ DeleteMe.const_set "OrMe", Module.new
ActiveSupport::Dependencies.remove_constant "::DeleteMe::OrMe"
assert_not defined?(DeleteMe::OrMe)
assert defined?(DeleteMe)
@@ -986,9 +991,9 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_remove_constant_does_not_trigger_loading_autoloads
- constant = 'ShouldNotBeAutoloaded'
+ constant = "ShouldNotBeAutoloaded"
Object.class_eval do
- autoload constant, File.expand_path('../autoloading_fixtures/should_not_be_required', __FILE__)
+ autoload constant, File.expand_path("autoloading_fixtures/should_not_be_required", __dir__)
end
assert_nil ActiveSupport::Dependencies.remove_constant(constant), "Kernel#autoload has been triggered by remove_constant"
@@ -1001,8 +1006,8 @@ class DependenciesTest < ActiveSupport::TestCase
with_autoloading_fixtures do
_ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context"
_ = ::A::B # assignment to silence parse-time warning "possibly useless use of :: in void context"
- ActiveSupport::Dependencies.remove_constant('A')
- ActiveSupport::Dependencies.remove_constant('A::B')
+ ActiveSupport::Dependencies.remove_constant("A")
+ ActiveSupport::Dependencies.remove_constant("A::B")
assert_not defined?(A)
end
ensure
@@ -1036,10 +1041,9 @@ class DependenciesTest < ActiveSupport::TestCase
remove_constants(:A)
end
-
def test_autoload_once_paths_should_behave_when_recursively_loading
old_path = ActiveSupport::Dependencies.autoload_once_paths
- with_loading 'dependencies', 'autoloading_fixtures' do
+ with_loading "dependencies", "autoloading_fixtures" do
ActiveSupport::Dependencies.autoload_once_paths = [ActiveSupport::Dependencies.autoload_paths.last]
assert_not defined?(CrossSiteDependency)
assert_nothing_raised { CrossSiteDepender.nil? }
@@ -1060,13 +1064,13 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_load_and_require_stay_private
- assert Object.private_methods.include?(:load)
- assert Object.private_methods.include?(:require)
+ assert_includes Object.private_methods, :load
+ assert_includes Object.private_methods, :require
ActiveSupport::Dependencies.unhook!
- assert Object.private_methods.include?(:load)
- assert Object.private_methods.include?(:require)
+ assert_includes Object.private_methods, :load
+ assert_includes Object.private_methods, :require
ensure
ActiveSupport::Dependencies.hook!
end
diff --git a/activesupport/test/dependencies_test_helpers.rb b/activesupport/test/dependencies_test_helpers.rb
index e4d5197112..b54a7e70c8 100644
--- a/activesupport/test/dependencies_test_helpers.rb
+++ b/activesupport/test/dependencies_test_helpers.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
module DependenciesTestHelpers
def with_loading(*from)
old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load
- this_dir = File.dirname(__FILE__)
+ this_dir = __dir__
parent_dir = File.dirname(this_dir)
path_copy = $LOAD_PATH.dup
$LOAD_PATH.unshift(parent_dir) unless $LOAD_PATH.include?(parent_dir)
@@ -17,7 +19,7 @@ module DependenciesTestHelpers
end
def with_autoloading_fixtures(&block)
- with_loading 'autoloading_fixtures', &block
+ with_loading "autoloading_fixtures", &block
end
def remove_constants(*constants)
@@ -25,4 +27,4 @@ module DependenciesTestHelpers
Object.send(:remove_const, constant) if Object.const_defined?(constant)
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/deprecation/method_wrappers_test.rb b/activesupport/test/deprecation/method_wrappers_test.rb
index 9a4ca2b217..439e117c1d 100644
--- a/activesupport/test/deprecation/method_wrappers_test.rb
+++ b/activesupport/test/deprecation/method_wrappers_test.rb
@@ -1,17 +1,29 @@
-require 'abstract_unit'
-require 'active_support/deprecation'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/deprecation"
class MethodWrappersTest < ActiveSupport::TestCase
def setup
@klass = Class.new do
def new_method; "abc" end
alias_method :old_method, :new_method
+
+ protected
+
+ def new_protected_method; "abc" end
+ alias_method :old_protected_method, :new_protected_method
+
+ private
+
+ def new_private_method; "abc" end
+ alias_method :old_private_method, :new_private_method
end
end
def test_deprecate_methods_warning_default
warning = /old_method is deprecated and will be removed from Rails \d.\d \(use new_method instead\)/
- ActiveSupport::Deprecation.deprecate_methods(@klass, :old_method => :new_method)
+ ActiveSupport::Deprecation.deprecate_methods(@klass, old_method: :new_method)
assert_deprecated(warning) { assert_equal "abc", @klass.new.old_method }
end
@@ -19,7 +31,7 @@ class MethodWrappersTest < ActiveSupport::TestCase
def test_deprecate_methods_warning_with_optional_deprecator
warning = /old_method is deprecated and will be removed from MyGem next-release \(use new_method instead\)/
deprecator = ActiveSupport::Deprecation.new("next-release", "MyGem")
- ActiveSupport::Deprecation.deprecate_methods(@klass, :old_method => :new_method, :deprecator => deprecator)
+ ActiveSupport::Deprecation.deprecate_methods(@klass, old_method: :new_method, deprecator: deprecator)
assert_deprecated(warning, deprecator) { assert_equal "abc", @klass.new.old_method }
end
@@ -27,8 +39,20 @@ class MethodWrappersTest < ActiveSupport::TestCase
def test_deprecate_methods_warning_when_deprecated_with_custom_deprecator
warning = /old_method is deprecated and will be removed from MyGem next-release \(use new_method instead\)/
deprecator = ActiveSupport::Deprecation.new("next-release", "MyGem")
- deprecator.deprecate_methods(@klass, :old_method => :new_method)
+ deprecator.deprecate_methods(@klass, old_method: :new_method)
assert_deprecated(warning, deprecator) { assert_equal "abc", @klass.new.old_method }
end
+
+ def test_deprecate_methods_protected_method
+ ActiveSupport::Deprecation.deprecate_methods(@klass, old_protected_method: :new_protected_method)
+
+ assert(@klass.protected_method_defined?(:old_protected_method))
+ end
+
+ def test_deprecate_methods_private_method
+ ActiveSupport::Deprecation.deprecate_methods(@klass, old_private_method: :new_private_method)
+
+ assert(@klass.private_method_defined?(:old_private_method))
+ end
end
diff --git a/activesupport/test/deprecation/proxy_wrappers_test.rb b/activesupport/test/deprecation/proxy_wrappers_test.rb
index e4f0f0f7c2..2f866775f6 100644
--- a/activesupport/test/deprecation/proxy_wrappers_test.rb
+++ b/activesupport/test/deprecation/proxy_wrappers_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/deprecation'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/deprecation"
class ProxyWrappersTest < ActiveSupport::TestCase
Waffles = false
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 45c88b79cb..f2267a822f 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -1,22 +1,24 @@
-require 'abstract_unit'
-require 'active_support/testing/stream'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/testing/stream"
class Deprecatee
def initialize
@request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request)
- @_request = 'there we go'
+ @_request = "there we go"
end
def request; @_request end
def old_request; @request end
def partially(foo = nil)
- ActiveSupport::Deprecation.warn('calling with foo=nil is out') if foo.nil?
+ ActiveSupport::Deprecation.warn("calling with foo=nil is out") if foo.nil?
end
def not() 2 end
def none() 1 end
def one(a) a end
- def multi(a,b,c) [a,b,c] end
+ def multi(a, b, c) [a, b, c] end
deprecate :none, :one, :multi
def a; end
@@ -24,7 +26,7 @@ class Deprecatee
def c; end
def d; end
def e; end
- deprecate :a, :b, :c => :e, :d => "you now need to do something extra for this one"
+ deprecate :a, :b, c: :e, d: "you now need to do something extra for this one"
def f=(v); end
deprecate :f=
@@ -32,9 +34,20 @@ class Deprecatee
module B
C = 1
end
- A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Deprecatee::A', 'Deprecatee::B::C')
+ A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::A", "Deprecatee::B::C")
end
+class DeprecateeWithAccessor
+ include ActiveSupport::Deprecation::DeprecatedConstantAccessor
+
+ module B
+ C = 1
+ end
+ deprecate_constant "A", "DeprecateeWithAccessor::B::C"
+
+ class NewException < StandardError; end
+ deprecate_constant "OldException", "DeprecateeWithAccessor::NewException"
+end
class DeprecationTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Stream
@@ -74,12 +87,12 @@ class DeprecationTest < ActiveSupport::TestCase
end
assert_deprecated(/multi is deprecated/) do
- assert_equal [1,2,3], @dtc.multi(1,2,3)
+ assert_equal [1, 2, 3], @dtc.multi(1, 2, 3)
end
end
def test_deprecate_object
- deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, ':bomb:')
+ deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, ":bomb:")
assert_deprecated(/:bomb:/) { deprecated_object.to_s }
end
@@ -89,26 +102,28 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_several_behaviors
- @a, @b = nil, nil
+ @a, @b, @c = nil, nil, nil
ActiveSupport::Deprecation.behavior = [
- Proc.new { |msg, callstack| @a = msg },
- Proc.new { |msg, callstack| @b = msg }
+ lambda { |msg, callstack, horizon, gem| @a = msg },
+ lambda { |msg, callstack| @b = msg },
+ lambda { |*args| @c = args },
]
@dtc.partially
assert_match(/foo=nil/, @a)
assert_match(/foo=nil/, @b)
+ assert_equal 4, @c.size
end
def test_raise_behaviour
ActiveSupport::Deprecation.behavior = :raise
- message = 'Revise this deprecated stuff now!'
+ message = "Revise this deprecated stuff now!"
callstack = caller_locations
e = assert_raise ActiveSupport::DeprecationException do
- ActiveSupport::Deprecation.behavior.first.call(message, callstack)
+ ActiveSupport::Deprecation.behavior.first.call(message, callstack, "horizon", "gem")
end
assert_equal message, e.message
assert_equal callstack.map(&:to_s), e.backtrace.map(&:to_s)
@@ -119,7 +134,7 @@ class DeprecationTest < ActiveSupport::TestCase
behavior = ActiveSupport::Deprecation.behavior.first
content = capture(:stderr) {
- assert_nil behavior.call('Some error!', ['call stack!'])
+ assert_nil behavior.call("Some error!", ["call stack!"], "horizon", "gem")
}
assert_match(/Some error!/, content)
assert_match(/call stack!/, content)
@@ -129,7 +144,7 @@ class DeprecationTest < ActiveSupport::TestCase
ActiveSupport::Deprecation.behavior = :stderr
content = capture(:stderr) {
- ActiveSupport::Deprecation.warn('Instance error!', ['instance call stack!'])
+ ActiveSupport::Deprecation.warn("Instance error!", ["instance call stack!"])
}
assert_match(/Instance error!/, content)
@@ -141,16 +156,37 @@ class DeprecationTest < ActiveSupport::TestCase
behavior = ActiveSupport::Deprecation.behavior.first
stderr_output = capture(:stderr) {
- assert_nil behavior.call('Some error!', ['call stack!'])
+ assert_nil behavior.call("Some error!", ["call stack!"], "horizon", "gem")
}
- assert stderr_output.blank?
+ assert stderr_output.empty?
+ end
+
+ def test_default_notify_behavior
+ ActiveSupport::Deprecation.behavior = :notify
+ behavior = ActiveSupport::Deprecation.behavior.first
+
+ begin
+ events = []
+ ActiveSupport::Notifications.subscribe("deprecation.my_gem_custom") { |_, **args|
+ events << args
+ }
+
+ assert_nil behavior.call("Some error!", ["call stack!"], "horizon", "MyGem::Custom")
+ assert_equal 1, events.size
+ assert_equal "Some error!", events.first[:message]
+ assert_equal ["call stack!"], events.first[:callstack]
+ assert_equal "horizon", events.first[:deprecation_horizon]
+ assert_equal "MyGem::Custom", events.first[:gem_name]
+ ensure
+ ActiveSupport::Notifications.unsubscribe("deprecation.my_gem_custom")
+ end
end
def test_deprecated_instance_variable_proxy
assert_not_deprecated { @dtc.request.size }
- assert_deprecated('@request.size') { assert_equal @dtc.request.size, @dtc.old_request.size }
- assert_deprecated('@request.to_s') { assert_equal @dtc.request.to_s, @dtc.old_request.to_s }
+ assert_deprecated("@request.size") { assert_equal @dtc.request.size, @dtc.old_request.size }
+ assert_deprecated("@request.to_s") { assert_equal @dtc.request.to_s, @dtc.old_request.to_s }
end
def test_deprecated_instance_variable_proxy_shouldnt_warn_on_inspect
@@ -159,10 +195,21 @@ class DeprecationTest < ActiveSupport::TestCase
def test_deprecated_constant_proxy
assert_not_deprecated { Deprecatee::B::C }
- assert_deprecated('Deprecatee::A') { assert_equal Deprecatee::B::C, Deprecatee::A }
+ assert_deprecated("Deprecatee::A") { assert_equal Deprecatee::B::C, Deprecatee::A }
assert_not_deprecated { assert_equal Deprecatee::B::C.class, Deprecatee::A.class }
end
+ def test_deprecated_constant_accessor
+ assert_not_deprecated { DeprecateeWithAccessor::B::C }
+ assert_deprecated("DeprecateeWithAccessor::A") { assert_equal DeprecateeWithAccessor::B::C, DeprecateeWithAccessor::A }
+ end
+
+ def test_deprecated_constant_accessor_exception
+ raise DeprecateeWithAccessor::NewException.new("Test")
+ rescue DeprecateeWithAccessor::OldException => e
+ assert_kind_of DeprecateeWithAccessor::NewException, e
+ end
+
def test_assert_deprecated_raises_when_method_not_deprecated
assert_raises(Minitest::Assertion) { assert_deprecated { @dtc.not } }
end
@@ -178,12 +225,12 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_assert_deprecated_matches_any_warning
- assert_deprecated 'abc' do
- ActiveSupport::Deprecation.warn 'abc'
- ActiveSupport::Deprecation.warn 'def'
+ assert_deprecated "abc" do
+ ActiveSupport::Deprecation.warn "abc"
+ ActiveSupport::Deprecation.warn "def"
end
rescue Minitest::Assertion
- flunk 'assert_deprecated should match any warning in block, not just the last one'
+ flunk "assert_deprecated should match any warning in block, not just the last one"
end
def test_assert_not_deprecated_returns_result_of_block
@@ -191,17 +238,17 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_assert_deprecated_returns_result_of_block
- result = assert_deprecated('abc') do
- ActiveSupport::Deprecation.warn 'abc'
+ result = assert_deprecated("abc") do
+ ActiveSupport::Deprecation.warn "abc"
123
end
assert_equal 123, result
end
def test_assert_deprecated_warn_work_with_default_behavior
- ActiveSupport::Deprecation.instance_variable_set('@behavior', nil)
- assert_deprecated('abc') do
- ActiveSupport::Deprecation.warn 'abc'
+ ActiveSupport::Deprecation.instance_variable_set("@behavior", nil)
+ assert_deprecated("abc") do
+ ActiveSupport::Deprecation.warn "abc"
end
end
@@ -280,12 +327,22 @@ class DeprecationTest < ActiveSupport::TestCase
def test_deprecated_constant_with_deprecator_given
deprecator = deprecator_with_messages
klass = Class.new
- klass.const_set(:OLD, ActiveSupport::Deprecation::DeprecatedConstantProxy.new('klass::OLD', 'Object', deprecator) )
+ klass.const_set(:OLD, ActiveSupport::Deprecation::DeprecatedConstantProxy.new("klass::OLD", "Object", deprecator))
assert_difference("deprecator.messages.size") do
klass::OLD.to_s
end
end
+ def test_deprecated_constant_with_custom_message
+ deprecator = deprecator_with_messages
+
+ klass = Class.new
+ klass.const_set(:OLD, ActiveSupport::Deprecation::DeprecatedConstantProxy.new("klass::OLD", "Object", deprecator, message: "foo"))
+
+ klass::OLD.to_s
+ assert_match "foo", deprecator.messages.last
+ end
+
def test_deprecated_instance_variable_with_instance_deprecator
deprecator = deprecator_with_messages
@@ -341,7 +398,7 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_default_deprecation_horizon_should_always_bigger_than_current_rails_version
- assert ActiveSupport::Deprecation.new.deprecation_horizon > ActiveSupport::VERSION::STRING
+ assert_operator ActiveSupport::Deprecation.new.deprecation_horizon, :>, ActiveSupport::VERSION::STRING
end
def test_default_gem_name
@@ -353,7 +410,7 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_custom_gem_name
- deprecator = ActiveSupport::Deprecation.new('2.0', 'Custom')
+ deprecator = ActiveSupport::Deprecation.new("2.0", "Custom")
deprecator.send(:deprecated_method_warning, :deprecated_method, "You are calling deprecated method").tap do |message|
assert_match(/is deprecated and will be removed from Custom/, message)
@@ -364,11 +421,10 @@ class DeprecationTest < ActiveSupport::TestCase
def deprecator_with_messages
klass = Class.new(ActiveSupport::Deprecation)
deprecator = klass.new
- deprecator.behavior = Proc.new{|message, callstack| deprecator.messages << message}
+ deprecator.behavior = Proc.new { |message, callstack| deprecator.messages << message }
def deprecator.messages
@messages ||= []
end
deprecator
end
-
end
diff --git a/activesupport/test/descendants_tracker_test_cases.rb b/activesupport/test/descendants_tracker_test_cases.rb
index 69e046998e..1f8b4a8605 100644
--- a/activesupport/test/descendants_tracker_test_cases.rb
+++ b/activesupport/test/descendants_tracker_test_cases.rb
@@ -1,4 +1,6 @@
-require 'set'
+# frozen_string_literal: true
+
+require "set"
module DescendantsTrackerTestCases
class Parent
@@ -40,26 +42,26 @@ module DescendantsTrackerTestCases
end
end
- protected
-
- def assert_equal_sets(expected, actual)
- assert_equal Set.new(expected), Set.new(actual)
- end
+ private
- def mark_as_autoloaded(*klasses)
- # If ActiveSupport::Dependencies is not loaded, forget about autoloading.
- # This allows using AS::DescendantsTracker without AS::Dependencies.
- if defined? ActiveSupport::Dependencies
- old_autoloaded = ActiveSupport::Dependencies.autoloaded_constants.dup
- ActiveSupport::Dependencies.autoloaded_constants = klasses.map(&:name)
+ def assert_equal_sets(expected, actual)
+ assert_equal Set.new(expected), Set.new(actual)
end
- old_descendants = ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").dup
- old_descendants.each { |k, v| old_descendants[k] = v.dup }
+ def mark_as_autoloaded(*klasses)
+ # If ActiveSupport::Dependencies is not loaded, forget about autoloading.
+ # This allows using AS::DescendantsTracker without AS::Dependencies.
+ if defined? ActiveSupport::Dependencies
+ old_autoloaded = ActiveSupport::Dependencies.autoloaded_constants.dup
+ ActiveSupport::Dependencies.autoloaded_constants = klasses.map(&:name)
+ end
- yield
- ensure
- ActiveSupport::Dependencies.autoloaded_constants = old_autoloaded if defined? ActiveSupport::Dependencies
- ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").replace(old_descendants)
- end
+ old_descendants = ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").dup
+ old_descendants.each { |k, v| old_descendants[k] = v.dup }
+
+ yield
+ ensure
+ ActiveSupport::Dependencies.autoloaded_constants = old_autoloaded if defined? ActiveSupport::Dependencies
+ ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").replace(old_descendants)
+ end
end
diff --git a/activesupport/test/descendants_tracker_with_autoloading_test.rb b/activesupport/test/descendants_tracker_with_autoloading_test.rb
index a2ae066a21..7c396b7c8e 100644
--- a/activesupport/test/descendants_tracker_with_autoloading_test.rb
+++ b/activesupport/test/descendants_tracker_with_autoloading_test.rb
@@ -1,7 +1,9 @@
-require 'abstract_unit'
-require 'active_support/descendants_tracker'
-require 'active_support/dependencies'
-require 'descendants_tracker_test_cases'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/descendants_tracker"
+require "active_support/dependencies"
+require "descendants_tracker_test_cases"
class DescendantsTrackerWithAutoloadingTest < ActiveSupport::TestCase
include DescendantsTrackerTestCases
diff --git a/activesupport/test/descendants_tracker_without_autoloading_test.rb b/activesupport/test/descendants_tracker_without_autoloading_test.rb
index 00b449af51..f5c6a3045d 100644
--- a/activesupport/test/descendants_tracker_without_autoloading_test.rb
+++ b/activesupport/test/descendants_tracker_without_autoloading_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/descendants_tracker'
-require 'descendants_tracker_test_cases'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/descendants_tracker"
+require "descendants_tracker_test_cases"
class DescendantsTrackerWithoutAutoloadingTest < ActiveSupport::TestCase
include DescendantsTrackerTestCases
diff --git a/activesupport/test/digest_test.rb b/activesupport/test/digest_test.rb
new file mode 100644
index 0000000000..83ff2a8d83
--- /dev/null
+++ b/activesupport/test/digest_test.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "openssl"
+
+class DigestTest < ActiveSupport::TestCase
+ class InvalidDigest; end
+ def test_with_default_hash_digest_class
+ assert_equal ::Digest::MD5.hexdigest("hello friend"), ActiveSupport::Digest.hexdigest("hello friend")
+ end
+
+ def test_with_custom_hash_digest_class
+ original_hash_digest_class = ActiveSupport::Digest.hash_digest_class
+
+ ActiveSupport::Digest.hash_digest_class = ::Digest::SHA1
+ digest = ActiveSupport::Digest.hexdigest("hello friend")
+
+ assert_equal 32, digest.length
+ assert_equal ::Digest::SHA1.hexdigest("hello friend")[0...32], digest
+ ensure
+ ActiveSupport::Digest.hash_digest_class = original_hash_digest_class
+ end
+
+ def test_should_raise_argument_error_if_custom_digest_is_missing_hexdigest_method
+ assert_raises(ArgumentError) { ActiveSupport::Digest.hash_digest_class = InvalidDigest }
+ end
+end
diff --git a/activesupport/test/encrypted_configuration_test.rb b/activesupport/test/encrypted_configuration_test.rb
new file mode 100644
index 0000000000..93ccf457de
--- /dev/null
+++ b/activesupport/test/encrypted_configuration_test.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/encrypted_configuration"
+
+class EncryptedConfigurationTest < ActiveSupport::TestCase
+ setup do
+ @credentials_config_path = File.join(Dir.tmpdir, "credentials.yml.enc")
+
+ @credentials_key_path = File.join(Dir.tmpdir, "master.key")
+ File.write(@credentials_key_path, ActiveSupport::EncryptedConfiguration.generate_key)
+
+ @credentials = ActiveSupport::EncryptedConfiguration.new(
+ config_path: @credentials_config_path, key_path: @credentials_key_path,
+ env_key: "RAILS_MASTER_KEY", raise_if_missing_key: true
+ )
+ end
+
+ teardown do
+ FileUtils.rm_rf @credentials_config_path
+ FileUtils.rm_rf @credentials_key_path
+ end
+
+ test "reading configuration by env key" do
+ FileUtils.rm_rf @credentials_key_path
+
+ begin
+ ENV["RAILS_MASTER_KEY"] = ActiveSupport::EncryptedConfiguration.generate_key
+ @credentials.write({ something: { good: true, bad: false } }.to_yaml)
+
+ assert @credentials[:something][:good]
+ assert_not @credentials.dig(:something, :bad)
+ assert_nil @credentials.fetch(:nothing, nil)
+ ensure
+ ENV["RAILS_MASTER_KEY"] = nil
+ end
+ end
+
+ test "reading configuration by key file" do
+ @credentials.write({ something: { good: true } }.to_yaml)
+
+ assert @credentials.something[:good]
+ end
+
+ test "change configuration by key file" do
+ @credentials.write({ something: { good: true } }.to_yaml)
+ @credentials.change do |config_file|
+ config = YAML.load(config_file.read)
+ config_file.write config.merge(new: "things").to_yaml
+ end
+
+ assert @credentials.something[:good]
+ assert_equal "things", @credentials[:new]
+ end
+
+ test "raise error when writing an invalid format value" do
+ assert_raise(Psych::SyntaxError) do
+ @credentials.change do |config_file|
+ config_file.write "login: *login\n username: dummy"
+ end
+ end
+ end
+
+ test "raises key error when accessing config via bang method" do
+ assert_raise(KeyError) { @credentials.something! }
+ end
+end
diff --git a/activesupport/test/encrypted_file_test.rb b/activesupport/test/encrypted_file_test.rb
new file mode 100644
index 0000000000..ba3bbef903
--- /dev/null
+++ b/activesupport/test/encrypted_file_test.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/encrypted_file"
+
+class EncryptedFileTest < ActiveSupport::TestCase
+ setup do
+ @content = "One little fox jumped over the hedge"
+
+ @content_path = File.join(Dir.tmpdir, "content.txt.enc")
+
+ @key_path = File.join(Dir.tmpdir, "content.txt.key")
+ File.write(@key_path, ActiveSupport::EncryptedFile.generate_key)
+
+ @encrypted_file = ActiveSupport::EncryptedFile.new(
+ content_path: @content_path, key_path: @key_path, env_key: "CONTENT_KEY", raise_if_missing_key: true
+ )
+ end
+
+ teardown do
+ FileUtils.rm_rf @content_path
+ FileUtils.rm_rf @key_path
+ end
+
+ test "reading content by env key" do
+ FileUtils.rm_rf @key_path
+
+ begin
+ ENV["CONTENT_KEY"] = ActiveSupport::EncryptedFile.generate_key
+ @encrypted_file.write @content
+
+ assert_equal @content, @encrypted_file.read
+ ensure
+ ENV["CONTENT_KEY"] = nil
+ end
+ end
+
+ test "reading content by key file" do
+ @encrypted_file.write(@content)
+ assert_equal @content, @encrypted_file.read
+ end
+
+ test "change content by key file" do
+ @encrypted_file.write(@content)
+ @encrypted_file.change do |file|
+ file.write(file.read + " and went by the lake")
+ end
+
+ assert_equal "#{@content} and went by the lake", @encrypted_file.read
+ end
+
+ test "raise MissingKeyError when key is missing" do
+ assert_raise(ActiveSupport::EncryptedFile::MissingKeyError) do
+ ActiveSupport::EncryptedFile.new(
+ content_path: @content_path, key_path: "", env_key: "", raise_if_missing_key: true
+ ).read
+ end
+ end
+end
diff --git a/activesupport/test/evented_file_update_checker_test.rb b/activesupport/test/evented_file_update_checker_test.rb
index bc3f77bd54..9b560f7f42 100644
--- a/activesupport/test/evented_file_update_checker_test.rb
+++ b/activesupport/test/evented_file_update_checker_test.rb
@@ -1,17 +1,20 @@
-require 'abstract_unit'
-require 'pathname'
-require 'file_update_checker_shared_tests'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "pathname"
+require "file_update_checker_shared_tests"
class EventedFileUpdateCheckerTest < ActiveSupport::TestCase
include FileUpdateCheckerSharedTests
def setup
- skip if ENV['LISTEN'] == '0'
+ skip if ENV["LISTEN"] == "0"
+ require "listen"
super
end
def new_checker(files = [], dirs = {}, &block)
- ActiveSupport::EventedFileUpdateChecker.new(files, dirs, &block).tap do
+ ActiveSupport::EventedFileUpdateChecker.new(files, dirs, &block).tap do |c|
wait
end
end
@@ -30,9 +33,48 @@ class EventedFileUpdateCheckerTest < ActiveSupport::TestCase
wait # wait for the events to fire
end
- def rm_f(files)
- super
- wait
+ test "notifies forked processes" do
+ jruby_skip "Forking not available on JRuby"
+
+ FileUtils.touch(tmpfiles)
+
+ checker = new_checker(tmpfiles) {}
+ assert !checker.updated?
+
+ # Pipes used for flow control across fork.
+ boot_reader, boot_writer = IO.pipe
+ touch_reader, touch_writer = IO.pipe
+
+ pid = fork do
+ assert checker.updated?
+
+ # Clear previous check value.
+ checker.execute
+ assert !checker.updated?
+
+ # Fork is booted, ready for file to be touched
+ # notify parent process.
+ boot_writer.write("booted")
+
+ # Wait for parent process to signal that file
+ # has been touched.
+ IO.select([touch_reader])
+
+ assert checker.updated?
+ end
+
+ assert pid
+
+ # Wait for fork to be booted before touching files.
+ IO.select([boot_reader])
+ touch(tmpfiles)
+
+ # Notify fork that files have been touched.
+ touch_writer.write("touched")
+
+ assert checker.updated?
+
+ Process.wait(pid)
end
end
@@ -45,33 +87,33 @@ class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
@ph = ActiveSupport::EventedFileUpdateChecker::PathHelper.new
end
- test '#xpath returns the expanded path as a Pathname object' do
+ test "#xpath returns the expanded path as a Pathname object" do
assert_equal pn(__FILE__).expand_path, @ph.xpath(__FILE__)
end
- test '#normalize_extension returns a bare extension as is' do
- assert_equal 'rb', @ph.normalize_extension('rb')
+ test "#normalize_extension returns a bare extension as is" do
+ assert_equal "rb", @ph.normalize_extension("rb")
end
- test '#normalize_extension removes a leading dot' do
- assert_equal 'rb', @ph.normalize_extension('.rb')
+ test "#normalize_extension removes a leading dot" do
+ assert_equal "rb", @ph.normalize_extension(".rb")
end
- test '#normalize_extension supports symbols' do
- assert_equal 'rb', @ph.normalize_extension(:rb)
+ test "#normalize_extension supports symbols" do
+ assert_equal "rb", @ph.normalize_extension(:rb)
end
- test '#longest_common_subpath finds the longest common subpath, if there is one' do
+ test "#longest_common_subpath finds the longest common subpath, if there is one" do
paths = %w(
/foo/bar
/foo/baz
/foo/bar/baz/woo/zoo
).map { |path| pn(path) }
- assert_equal pn('/foo'), @ph.longest_common_subpath(paths)
+ assert_equal pn("/foo"), @ph.longest_common_subpath(paths)
end
- test '#longest_common_subpath returns the root directory as an edge case' do
+ test "#longest_common_subpath returns the root directory as an edge case" do
paths = %w(
/foo/bar
/foo/baz
@@ -79,30 +121,30 @@ class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
/wadus
).map { |path| pn(path) }
- assert_equal pn('/'), @ph.longest_common_subpath(paths)
+ assert_equal pn("/"), @ph.longest_common_subpath(paths)
end
- test '#longest_common_subpath returns nil for an empty collection' do
+ test "#longest_common_subpath returns nil for an empty collection" do
assert_nil @ph.longest_common_subpath([])
end
- test '#existing_parent returns the most specific existing ascendant' do
+ test "#existing_parent returns the most specific existing ascendant" do
wd = Pathname.getwd
assert_equal wd, @ph.existing_parent(wd)
- assert_equal wd, @ph.existing_parent(wd.join('non-existing/directory'))
- assert_equal pn('/'), @ph.existing_parent(pn('/non-existing/directory'))
+ assert_equal wd, @ph.existing_parent(wd.join("non-existing/directory"))
+ assert_equal pn("/"), @ph.existing_parent(pn("/non-existing/directory"))
end
- test '#filter_out_descendants returns the same collection if there are no descendants (empty)' do
+ test "#filter_out_descendants returns the same collection if there are no descendants (empty)" do
assert_equal [], @ph.filter_out_descendants([])
end
- test '#filter_out_descendants returns the same collection if there are no descendants (one)' do
- assert_equal ['/foo'], @ph.filter_out_descendants(['/foo'])
+ test "#filter_out_descendants returns the same collection if there are no descendants (one)" do
+ assert_equal ["/foo"], @ph.filter_out_descendants(["/foo"])
end
- test '#filter_out_descendants returns the same collection if there are no descendants (several)' do
+ test "#filter_out_descendants returns the same collection if there are no descendants (several)" do
paths = %w(
/Rails.root/app/controllers
/Rails.root/app/models
@@ -112,7 +154,7 @@ class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
assert_equal paths, @ph.filter_out_descendants(paths)
end
- test '#filter_out_descendants filters out descendants preserving order' do
+ test "#filter_out_descendants filters out descendants preserving order" do
paths = %w(
/Rails.root/app/controllers
/Rails.root/app/controllers/concerns
@@ -124,7 +166,7 @@ class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
assert_equal paths.values_at(0, 2, 4), @ph.filter_out_descendants(paths)
end
- test '#filter_out_descendants works on path units' do
+ test "#filter_out_descendants works on path units" do
paths = %w(
/foo/bar
/foo/barrrr
@@ -133,7 +175,7 @@ class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
assert_equal paths, @ph.filter_out_descendants(paths)
end
- test '#filter_out_descendants deals correctly with the root directory' do
+ test "#filter_out_descendants deals correctly with the root directory" do
paths = %w(
/
/foo
@@ -143,7 +185,7 @@ class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
assert_equal paths.values_at(0), @ph.filter_out_descendants(paths)
end
- test '#filter_out_descendants preserves duplicates' do
+ test "#filter_out_descendants preserves duplicates" do
paths = %w(
/foo
/foo/bar
diff --git a/activesupport/test/executor_test.rb b/activesupport/test/executor_test.rb
index d9b389461a..af441064dd 100644
--- a/activesupport/test/executor_test.rb
+++ b/activesupport/test/executor_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class ExecutorTest < ActiveSupport::TestCase
class DummyError < RuntimeError
@@ -21,7 +23,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.to_run { @foo = true }
executor.to_complete { result = @foo }
- executor.wrap { }
+ executor.wrap {}
assert result
end
@@ -83,7 +85,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.register_hook(hook)
- executor.wrap { }
+ executor.wrap {}
assert_equal :some_state, supplied_state
end
@@ -103,9 +105,9 @@ class ExecutorTest < ActiveSupport::TestCase
executor.register_hook(hook)
- executor.wrap { }
+ executor.wrap {}
- assert_equal nil, supplied_state
+ assert_nil supplied_state
end
def test_exception_skips_uninvoked_hook
@@ -127,7 +129,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.register_hook(hook)
assert_raises(DummyError) do
- executor.wrap { }
+ executor.wrap {}
end
assert_equal :none, supplied_state
@@ -152,12 +154,69 @@ class ExecutorTest < ActiveSupport::TestCase
end
assert_raises(DummyError) do
- executor.wrap { }
+ executor.wrap {}
end
assert_equal :some_state, supplied_state
end
+ def test_hook_insertion_order
+ invoked = []
+ supplied_state = []
+
+ hook_class = Class.new do
+ attr_accessor :letter
+
+ define_method(:initialize) do |letter|
+ self.letter = letter
+ end
+
+ define_method(:run) do
+ invoked << :"run_#{letter}"
+ :"state_#{letter}"
+ end
+
+ define_method(:complete) do |state|
+ invoked << :"complete_#{letter}"
+ supplied_state << state
+ end
+ end
+
+ executor.register_hook(hook_class.new(:a))
+ executor.register_hook(hook_class.new(:b))
+ executor.register_hook(hook_class.new(:c), outer: true)
+ executor.register_hook(hook_class.new(:d))
+
+ executor.wrap {}
+
+ assert_equal [:run_c, :run_a, :run_b, :run_d, :complete_a, :complete_b, :complete_d, :complete_c], invoked
+ assert_equal [:state_a, :state_b, :state_d, :state_c], supplied_state
+ end
+
+ def test_class_serial_is_unaffected
+ skip if !defined?(RubyVM)
+
+ hook = Class.new do
+ define_method(:run) do
+ nil
+ end
+
+ define_method(:complete) do |state|
+ nil
+ end
+ end.new
+
+ executor.register_hook(hook)
+
+ before = RubyVM.stat(:class_serial)
+ executor.wrap {}
+ executor.wrap {}
+ executor.wrap {}
+ after = RubyVM.stat(:class_serial)
+
+ assert_equal before, after
+ end
+
def test_separate_classes_can_wrap
other_executor = Class.new(ActiveSupport::Executor)
diff --git a/activesupport/test/file_update_checker_shared_tests.rb b/activesupport/test/file_update_checker_shared_tests.rb
index 40ae0c7617..f8266dac06 100644
--- a/activesupport/test/file_update_checker_shared_tests.rb
+++ b/activesupport/test/file_update_checker_shared_tests.rb
@@ -1,4 +1,6 @@
-require 'fileutils'
+# frozen_string_literal: true
+
+require "fileutils"
module FileUpdateCheckerSharedTests
extend ActiveSupport::Testing::Declarative
@@ -22,8 +24,8 @@ module FileUpdateCheckerSharedTests
end
end
- test 'should not execute the block if no paths are given' do
- silence_warnings { require 'listen' }
+ test "should not execute the block if no paths are given" do
+ silence_warnings { require "listen" }
i = 0
checker = new_checker { i += 1 }
@@ -32,7 +34,7 @@ module FileUpdateCheckerSharedTests
assert_equal 0, i
end
- test 'should not execute the block if no files change' do
+ test "should not execute the block if no files change" do
i = 0
FileUtils.touch(tmpfiles)
@@ -43,18 +45,19 @@ module FileUpdateCheckerSharedTests
assert_equal 0, i
end
- test 'should execute the block once when files are created' do
+ test "should execute the block once when files are created" do
i = 0
checker = new_checker(tmpfiles) { i += 1 }
touch(tmpfiles)
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'should execute the block once when files are modified' do
+ test "should execute the block once when files are modified" do
i = 0
FileUtils.touch(tmpfiles)
@@ -62,12 +65,13 @@ module FileUpdateCheckerSharedTests
checker = new_checker(tmpfiles) { i += 1 }
touch(tmpfiles)
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'should execute the block once when files are deleted' do
+ test "should execute the block once when files are deleted" do
i = 0
FileUtils.touch(tmpfiles)
@@ -75,25 +79,25 @@ module FileUpdateCheckerSharedTests
checker = new_checker(tmpfiles) { i += 1 }
rm_f(tmpfiles)
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
-
- test 'updated should become true when watched files are created' do
+ test "updated should become true when watched files are created" do
i = 0
checker = new_checker(tmpfiles) { i += 1 }
assert !checker.updated?
touch(tmpfiles)
+ wait
assert checker.updated?
end
-
- test 'updated should become true when watched files are modified' do
+ test "updated should become true when watched files are modified" do
i = 0
FileUtils.touch(tmpfiles)
@@ -102,11 +106,12 @@ module FileUpdateCheckerSharedTests
assert !checker.updated?
touch(tmpfiles)
+ wait
assert checker.updated?
end
- test 'updated should become true when watched files are deleted' do
+ test "updated should become true when watched files are deleted" do
i = 0
FileUtils.touch(tmpfiles)
@@ -115,11 +120,12 @@ module FileUpdateCheckerSharedTests
assert !checker.updated?
rm_f(tmpfiles)
+ wait
assert checker.updated?
end
- test 'should be robust to handle files with wrong modified time' do
+ test "should be robust to handle files with wrong modified time" do
i = 0
FileUtils.touch(tmpfiles)
@@ -131,12 +137,13 @@ module FileUpdateCheckerSharedTests
checker = new_checker(tmpfiles) { i += 1 }
touch(tmpfiles[1..-1])
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'should return max_time for files with mtime = Time.at(0)' do
+ test "should return max_time for files with mtime = Time.at(0)" do
i = 0
FileUtils.touch(tmpfiles)
@@ -147,80 +154,87 @@ module FileUpdateCheckerSharedTests
checker = new_checker(tmpfiles) { i += 1 }
touch(tmpfiles[1..-1])
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'should cache updated result until execute' do
+ test "should cache updated result until execute" do
i = 0
checker = new_checker(tmpfiles) { i += 1 }
assert !checker.updated?
touch(tmpfiles)
+ wait
assert checker.updated?
checker.execute
assert !checker.updated?
end
- test 'should execute the block if files change in a watched directory one extension' do
+ test "should execute the block if files change in a watched directory one extension" do
i = 0
checker = new_checker([], tmpdir => :rb) { i += 1 }
- touch(tmpfile('foo.rb'))
+ touch(tmpfile("foo.rb"))
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'should execute the block if files change in a watched directory several extensions' do
+ test "should execute the block if files change in a watched directory several extensions" do
i = 0
checker = new_checker([], tmpdir => [:rb, :txt]) { i += 1 }
- touch(tmpfile('foo.rb'))
+ touch(tmpfile("foo.rb"))
+ wait
assert checker.execute_if_updated
assert_equal 1, i
- touch(tmpfile('foo.txt'))
+ touch(tmpfile("foo.txt"))
+ wait
assert checker.execute_if_updated
assert_equal 2, i
end
- test 'should not execute the block if the file extension is not watched' do
+ test "should not execute the block if the file extension is not watched" do
i = 0
checker = new_checker([], tmpdir => :txt) { i += 1 }
- touch(tmpfile('foo.rb'))
+ touch(tmpfile("foo.rb"))
+ wait
assert !checker.execute_if_updated
assert_equal 0, i
end
- test 'does not assume files exist on instantiation' do
+ test "does not assume files exist on instantiation" do
i = 0
- non_existing = tmpfile('non_existing.rb')
+ non_existing = tmpfile("non_existing.rb")
checker = new_checker([non_existing]) { i += 1 }
touch(non_existing)
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'detects files in new subdirectories' do
+ test "detects files in new subdirectories" do
i = 0
checker = new_checker([], tmpdir => :rb) { i += 1 }
- subdir = tmpfile('subdir')
+ subdir = tmpfile("subdir")
mkdir(subdir)
wait
@@ -228,33 +242,43 @@ module FileUpdateCheckerSharedTests
assert_equal 0, i
touch(File.join(subdir, "nested.rb"))
+ wait
assert checker.execute_if_updated
assert_equal 1, i
end
- test 'looked up extensions are inherited in subdirectories not listening to them' do
+ test "looked up extensions are inherited in subdirectories not listening to them" do
i = 0
- subdir = tmpfile('subdir')
+ subdir = tmpfile("subdir")
mkdir(subdir)
checker = new_checker([], tmpdir => :rb, subdir => :txt) { i += 1 }
- touch(tmpfile('new.txt'))
+ touch(tmpfile("new.txt"))
+ wait
assert !checker.execute_if_updated
assert_equal 0, i
# subdir does not look for Ruby files, but its parent tmpdir does.
touch(File.join(subdir, "nested.rb"))
+ wait
assert checker.execute_if_updated
assert_equal 1, i
touch(File.join(subdir, "nested.txt"))
+ wait
assert checker.execute_if_updated
assert_equal 2, i
end
+
+ test "initialize raises an ArgumentError if no block given" do
+ assert_raise ArgumentError do
+ new_checker([])
+ end
+ end
end
diff --git a/activesupport/test/file_update_checker_test.rb b/activesupport/test/file_update_checker_test.rb
index 752f7836cd..ec1df0df67 100644
--- a/activesupport/test/file_update_checker_test.rb
+++ b/activesupport/test/file_update_checker_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'file_update_checker_shared_tests'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "file_update_checker_shared_tests"
class FileUpdateCheckerTest < ActiveSupport::TestCase
include FileUpdateCheckerSharedTests
diff --git a/activesupport/test/fixtures/autoload/another_class.rb b/activesupport/test/fixtures/autoload/another_class.rb
index a240b3de41..cf38336cf8 100644
--- a/activesupport/test/fixtures/autoload/another_class.rb
+++ b/activesupport/test/fixtures/autoload/another_class.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class Fixtures::AnotherClass
-end \ No newline at end of file
+end
diff --git a/activesupport/test/fixtures/autoload/some_class.rb b/activesupport/test/fixtures/autoload/some_class.rb
index 13b3c73ef5..ff25eb995e 100644
--- a/activesupport/test/fixtures/autoload/some_class.rb
+++ b/activesupport/test/fixtures/autoload/some_class.rb
@@ -1,2 +1,4 @@
+# frozen_string_literal: true
+
class Fixtures::Autoload::SomeClass
-end \ No newline at end of file
+end
diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb
index 0e3cf3b429..05ce12fe86 100644
--- a/activesupport/test/gzip_test.rb
+++ b/activesupport/test/gzip_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object/blank'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object/blank"
class GzipTest < ActiveSupport::TestCase
def test_compress_should_decompress_to_the_same_value
@@ -13,14 +15,14 @@ class GzipTest < ActiveSupport::TestCase
end
def test_compress_should_return_a_binary_string
- compressed = ActiveSupport::Gzip.compress('')
+ compressed = ActiveSupport::Gzip.compress("")
- assert_equal Encoding.find('binary'), compressed.encoding
+ assert_equal Encoding.find("binary"), compressed.encoding
assert !compressed.blank?, "a compressed blank string should not be blank"
end
def test_compress_should_return_gzipped_string_by_compression_level
- source_string = "Hello World"*100
+ source_string = "Hello World" * 100
gzipped_by_speed = ActiveSupport::Gzip.compress(source_string, Zlib::BEST_SPEED)
assert_equal 1, Zlib::GzipReader.new(StringIO.new(gzipped_by_speed)).level
@@ -30,4 +32,14 @@ class GzipTest < ActiveSupport::TestCase
assert_equal true, (gzipped_by_best_compression.bytesize < gzipped_by_speed.bytesize)
end
+
+ def test_decompress_checks_crc
+ compressed = ActiveSupport::Gzip.compress("Hello World")
+ first_crc_byte_index = compressed.bytesize - 8
+ compressed.setbyte(first_crc_byte_index, compressed.getbyte(first_crc_byte_index) ^ 0xff)
+
+ assert_raises(Zlib::GzipFile::CRCError) do
+ ActiveSupport::Gzip.decompress(compressed)
+ end
+ end
end
diff --git a/activesupport/test/hash_with_indifferent_access_test.rb b/activesupport/test/hash_with_indifferent_access_test.rb
new file mode 100644
index 0000000000..41d653fa59
--- /dev/null
+++ b/activesupport/test/hash_with_indifferent_access_test.rb
@@ -0,0 +1,803 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/hash"
+require "bigdecimal"
+require "active_support/core_ext/string/access"
+require "active_support/ordered_hash"
+require "active_support/core_ext/object/conversions"
+require "active_support/core_ext/object/deep_dup"
+require "active_support/inflections"
+
+class HashWithIndifferentAccessTest < ActiveSupport::TestCase
+ HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
+
+ class IndifferentHash < ActiveSupport::HashWithIndifferentAccess
+ end
+
+ class SubclassingArray < Array
+ end
+
+ class SubclassingHash < Hash
+ end
+
+ class NonIndifferentHash < Hash
+ def nested_under_indifferent_access
+ self
+ end
+ end
+
+ class HashByConversion
+ def initialize(hash)
+ @hash = hash
+ end
+
+ def to_hash
+ @hash
+ end
+ end
+
+ def setup
+ @strings = { "a" => 1, "b" => 2 }
+ @nested_strings = { "a" => { "b" => { "c" => 3 } } }
+ @symbols = { a: 1, b: 2 }
+ @nested_symbols = { a: { b: { c: 3 } } }
+ @mixed = { :a => 1, "b" => 2 }
+ @nested_mixed = { "a" => { b: { "c" => 3 } } }
+ @integers = { 0 => 1, 1 => 2 }
+ @nested_integers = { 0 => { 1 => { 2 => 3 } } }
+ @illegal_symbols = { [] => 3 }
+ @nested_illegal_symbols = { [] => { [] => 3 } }
+ end
+
+ def test_symbolize_keys_for_hash_with_indifferent_access
+ assert_instance_of Hash, @symbols.with_indifferent_access.symbolize_keys
+ assert_equal @symbols, @symbols.with_indifferent_access.symbolize_keys
+ assert_equal @symbols, @strings.with_indifferent_access.symbolize_keys
+ assert_equal @symbols, @mixed.with_indifferent_access.symbolize_keys
+ end
+
+ def test_deep_symbolize_keys_for_hash_with_indifferent_access
+ assert_instance_of Hash, @nested_symbols.with_indifferent_access.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_symbols.with_indifferent_access.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_strings.with_indifferent_access.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_mixed.with_indifferent_access.deep_symbolize_keys
+ end
+
+ def test_symbolize_keys_bang_for_hash_with_indifferent_access
+ assert_raise(NoMethodError) { @symbols.with_indifferent_access.dup.symbolize_keys! }
+ assert_raise(NoMethodError) { @strings.with_indifferent_access.dup.symbolize_keys! }
+ assert_raise(NoMethodError) { @mixed.with_indifferent_access.dup.symbolize_keys! }
+ end
+
+ def test_deep_symbolize_keys_bang_for_hash_with_indifferent_access
+ assert_raise(NoMethodError) { @nested_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ assert_raise(NoMethodError) { @nested_strings.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ assert_raise(NoMethodError) { @nested_mixed.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ end
+
+ def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
+ assert_equal @illegal_symbols, @illegal_symbols.with_indifferent_access.symbolize_keys
+ assert_raise(NoMethodError) { @illegal_symbols.with_indifferent_access.dup.symbolize_keys! }
+ end
+
+ def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
+ assert_equal @nested_illegal_symbols, @nested_illegal_symbols.with_indifferent_access.deep_symbolize_keys
+ assert_raise(NoMethodError) { @nested_illegal_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ end
+
+ def test_symbolize_keys_preserves_integer_keys_for_hash_with_indifferent_access
+ assert_equal @integers, @integers.with_indifferent_access.symbolize_keys
+ assert_raise(NoMethodError) { @integers.with_indifferent_access.dup.symbolize_keys! }
+ end
+
+ def test_deep_symbolize_keys_preserves_integer_keys_for_hash_with_indifferent_access
+ assert_equal @nested_integers, @nested_integers.with_indifferent_access.deep_symbolize_keys
+ assert_raise(NoMethodError) { @nested_integers.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ end
+
+ def test_stringify_keys_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.stringify_keys
+ assert_equal @strings, @symbols.with_indifferent_access.stringify_keys
+ assert_equal @strings, @strings.with_indifferent_access.stringify_keys
+ assert_equal @strings, @mixed.with_indifferent_access.stringify_keys
+ end
+
+ def test_deep_stringify_keys_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.deep_stringify_keys
+ assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_stringify_keys
+ assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_stringify_keys
+ assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_stringify_keys
+ end
+
+ def test_stringify_keys_bang_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.dup.stringify_keys!
+ assert_equal @strings, @symbols.with_indifferent_access.dup.stringify_keys!
+ assert_equal @strings, @strings.with_indifferent_access.dup.stringify_keys!
+ assert_equal @strings, @mixed.with_indifferent_access.dup.stringify_keys!
+ end
+
+ def test_deep_stringify_keys_bang_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_dup.deep_stringify_keys!
+ end
+
+ def test_nested_under_indifferent_access
+ foo = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of ActiveSupport::HashWithIndifferentAccess, foo["foo"]
+
+ foo = { "foo" => NonIndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of NonIndifferentHash, foo["foo"]
+
+ foo = { "foo" => IndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of IndifferentHash, foo["foo"]
+ end
+
+ def test_indifferent_assorted
+ @strings = @strings.with_indifferent_access
+ @symbols = @symbols.with_indifferent_access
+ @mixed = @mixed.with_indifferent_access
+
+ assert_equal "a", @strings.__send__(:convert_key, :a)
+
+ assert_equal 1, @strings.fetch("a")
+ assert_equal 1, @strings.fetch(:a.to_s)
+ assert_equal 1, @strings.fetch(:a)
+
+ hashes = { :@strings => @strings, :@symbols => @symbols, :@mixed => @mixed }
+ method_map = { '[]': 1, fetch: 1, values_at: [1],
+ has_key?: true, include?: true, key?: true,
+ member?: true }
+
+ hashes.each do |name, hash|
+ method_map.sort_by(&:to_s).each do |meth, expected|
+ assert_equal(expected, hash.__send__(meth, "a"),
+ "Calling #{name}.#{meth} 'a'")
+ assert_equal(expected, hash.__send__(meth, :a),
+ "Calling #{name}.#{meth} :a")
+ end
+ end
+
+ assert_equal [1, 2], @strings.values_at("a", "b")
+ assert_equal [1, 2], @strings.values_at(:a, :b)
+ assert_equal [1, 2], @symbols.values_at("a", "b")
+ assert_equal [1, 2], @symbols.values_at(:a, :b)
+ assert_equal [1, 2], @mixed.values_at("a", "b")
+ assert_equal [1, 2], @mixed.values_at(:a, :b)
+ end
+
+ def test_indifferent_fetch_values
+ skip unless Hash.method_defined?(:fetch_values)
+
+ @mixed = @mixed.with_indifferent_access
+
+ assert_equal [1, 2], @mixed.fetch_values("a", "b")
+ assert_equal [1, 2], @mixed.fetch_values(:a, :b)
+ assert_equal [1, 2], @mixed.fetch_values(:a, "b")
+ assert_equal [1, "c"], @mixed.fetch_values(:a, :c) { |key| key }
+ assert_raise(KeyError) { @mixed.fetch_values(:a, :c) }
+ end
+
+ def test_indifferent_reading
+ hash = HashWithIndifferentAccess.new
+ hash["a"] = 1
+ hash["b"] = true
+ hash["c"] = false
+ hash["d"] = nil
+
+ assert_equal 1, hash[:a]
+ assert_equal true, hash[:b]
+ assert_equal false, hash[:c]
+ assert_nil hash[:d]
+ assert_nil hash[:e]
+ end
+
+ def test_indifferent_reading_with_nonnil_default
+ hash = HashWithIndifferentAccess.new(1)
+ hash["a"] = 1
+ hash["b"] = true
+ hash["c"] = false
+ hash["d"] = nil
+
+ assert_equal 1, hash[:a]
+ assert_equal true, hash[:b]
+ assert_equal false, hash[:c]
+ assert_nil hash[:d]
+ assert_equal 1, hash[:e]
+ end
+
+ def test_indifferent_writing
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 1
+ hash["b"] = 2
+ hash[3] = 3
+
+ assert_equal 1, hash["a"]
+ assert_equal 2, hash["b"]
+ assert_equal 1, hash[:a]
+ assert_equal 2, hash[:b]
+ assert_equal 3, hash[3]
+ end
+
+ def test_indifferent_update
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = "a"
+ hash["b"] = "b"
+
+ updated_with_strings = hash.update(@strings)
+ updated_with_symbols = hash.update(@symbols)
+ updated_with_mixed = hash.update(@mixed)
+
+ assert_equal 1, updated_with_strings[:a]
+ assert_equal 1, updated_with_strings["a"]
+ assert_equal 2, updated_with_strings["b"]
+
+ assert_equal 1, updated_with_symbols[:a]
+ assert_equal 2, updated_with_symbols["b"]
+ assert_equal 2, updated_with_symbols[:b]
+
+ assert_equal 1, updated_with_mixed[:a]
+ assert_equal 2, updated_with_mixed["b"]
+
+ assert [updated_with_strings, updated_with_symbols, updated_with_mixed].all? { |h| h.keys.size == 2 }
+ end
+
+ def test_update_with_to_hash_conversion
+ hash = HashWithIndifferentAccess.new
+ hash.update HashByConversion.new(a: 1)
+ assert_equal 1, hash["a"]
+ end
+
+ def test_indifferent_merging
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = "failure"
+ hash["b"] = "failure"
+
+ other = { "a" => 1, :b => 2 }
+
+ merged = hash.merge(other)
+
+ assert_equal HashWithIndifferentAccess, merged.class
+ assert_equal 1, merged[:a]
+ assert_equal 2, merged["b"]
+
+ hash.update(other)
+
+ assert_equal 1, hash[:a]
+ assert_equal 2, hash["b"]
+ end
+
+ def test_merge_with_to_hash_conversion
+ hash = HashWithIndifferentAccess.new
+ merged = hash.merge HashByConversion.new(a: 1)
+ assert_equal 1, merged["a"]
+ end
+
+ def test_indifferent_replace
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 42
+
+ replaced = hash.replace(b: 12)
+
+ assert hash.key?("b")
+ assert !hash.key?(:a)
+ assert_equal 12, hash[:b]
+ assert_same hash, replaced
+ end
+
+ def test_replace_with_to_hash_conversion
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 42
+
+ replaced = hash.replace(HashByConversion.new(b: 12))
+
+ assert hash.key?("b")
+ assert !hash.key?(:a)
+ assert_equal 12, hash[:b]
+ assert_same hash, replaced
+ end
+
+ def test_indifferent_merging_with_block
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 1
+ hash["b"] = 3
+
+ other = { "a" => 4, :b => 2, "c" => 10 }
+
+ merged = hash.merge(other) { |key, old, new| old > new ? old : new }
+
+ assert_equal HashWithIndifferentAccess, merged.class
+ assert_equal 4, merged[:a]
+ assert_equal 3, merged["b"]
+ assert_equal 10, merged[:c]
+
+ other_indifferent = HashWithIndifferentAccess.new("a" => 9, :b => 2)
+
+ merged = hash.merge(other_indifferent) { |key, old, new| old + new }
+
+ assert_equal HashWithIndifferentAccess, merged.class
+ assert_equal 10, merged[:a]
+ assert_equal 5, merged[:b]
+ end
+
+ def test_indifferent_reverse_merging
+ hash = HashWithIndifferentAccess.new key: :old_value
+ hash.reverse_merge! key: :new_value
+ assert_equal :old_value, hash[:key]
+
+ hash = HashWithIndifferentAccess.new("some" => "value", "other" => "value")
+ hash.reverse_merge!(some: "noclobber", another: "clobber")
+ assert_equal "value", hash[:some]
+ assert_equal "clobber", hash[:another]
+ end
+
+ def test_indifferent_with_defaults_aliases_reverse_merge
+ hash = HashWithIndifferentAccess.new key: :old_value
+ actual = hash.with_defaults key: :new_value
+ assert_equal :old_value, actual[:key]
+
+ hash = HashWithIndifferentAccess.new key: :old_value
+ hash.with_defaults! key: :new_value
+ assert_equal :old_value, hash[:key]
+ end
+
+ def test_indifferent_deleting
+ get_hash = proc { { a: "foo" }.with_indifferent_access }
+ hash = get_hash.call
+ assert_equal "foo", hash.delete(:a)
+ assert_nil hash.delete(:a)
+ hash = get_hash.call
+ assert_equal "foo", hash.delete("a")
+ assert_nil hash.delete("a")
+ end
+
+ def test_indifferent_select
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select { |k, v| v == 1 }
+
+ assert_equal({ "a" => 1 }, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_select_returns_enumerator
+ enum = ActiveSupport::HashWithIndifferentAccess.new(@strings).select
+ assert_instance_of Enumerator, enum
+ end
+
+ def test_indifferent_select_returns_a_hash_when_unchanged
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select { |k, v| true }
+
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_select_bang
+ indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
+ indifferent_strings.select! { |k, v| v == 1 }
+
+ assert_equal({ "a" => 1 }, indifferent_strings)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
+ end
+
+ def test_indifferent_reject
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject { |k, v| v != 1 }
+
+ assert_equal({ "a" => 1 }, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_reject_returns_enumerator
+ enum = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject
+ assert_instance_of Enumerator, enum
+ end
+
+ def test_indifferent_reject_bang
+ indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
+ indifferent_strings.reject! { |k, v| v != 1 }
+
+ assert_equal({ "a" => 1 }, indifferent_strings)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
+ end
+
+ def test_indifferent_transform_keys
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).transform_keys { |k| k * 2 }
+
+ assert_equal({ "aa" => 1, "bb" => 2 }, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_transform_keys_bang
+ indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
+ indifferent_strings.transform_keys! { |k| k * 2 }
+
+ assert_equal({ "aa" => 1, "bb" => 2 }, indifferent_strings)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
+ end
+
+ def test_indifferent_transform_values
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).transform_values { |v| v * 2 }
+
+ assert_equal({ "a" => 2, "b" => 4 }, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_transform_values_bang
+ indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
+ indifferent_strings.transform_values! { |v| v * 2 }
+
+ assert_equal({ "a" => 2, "b" => 4 }, indifferent_strings)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
+ end
+
+ def test_indifferent_compact
+ hash_contain_nil_value = @strings.merge("z" => nil)
+ hash = ActiveSupport::HashWithIndifferentAccess.new(hash_contain_nil_value)
+ compacted_hash = hash.compact
+
+ assert_equal(@strings, compacted_hash)
+ assert_equal(hash_contain_nil_value, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, compacted_hash
+
+ empty_hash = ActiveSupport::HashWithIndifferentAccess.new
+ compacted_hash = empty_hash.compact
+
+ assert_equal compacted_hash, empty_hash
+
+ non_empty_hash = ActiveSupport::HashWithIndifferentAccess.new(foo: :bar)
+ compacted_hash = non_empty_hash.compact
+
+ assert_equal compacted_hash, non_empty_hash
+ end
+
+ def test_indifferent_to_hash
+ # Should convert to a Hash with String keys.
+ assert_equal @strings, @mixed.with_indifferent_access.to_hash
+
+ # Should preserve the default value.
+ mixed_with_default = @mixed.dup
+ mixed_with_default.default = "1234"
+ roundtrip = mixed_with_default.with_indifferent_access.to_hash
+ assert_equal @strings, roundtrip
+ assert_equal "1234", roundtrip.default
+
+ # Ensure nested hashes are not HashWithIndiffereneAccess
+ new_to_hash = @nested_mixed.with_indifferent_access.to_hash
+ assert_not new_to_hash.instance_of?(HashWithIndifferentAccess)
+ assert_not new_to_hash["a"].instance_of?(HashWithIndifferentAccess)
+ assert_not new_to_hash["a"]["b"].instance_of?(HashWithIndifferentAccess)
+ end
+
+ def test_lookup_returns_the_same_object_that_is_stored_in_hash_indifferent_access
+ hash = HashWithIndifferentAccess.new { |h, k| h[k] = [] }
+ hash[:a] << 1
+
+ assert_equal [1], hash[:a]
+ end
+
+ def test_with_indifferent_access_has_no_side_effects_on_existing_hash
+ hash = { content: [{ :foo => :bar, "bar" => "baz" }] }
+ hash.with_indifferent_access
+
+ assert_equal [:foo, "bar"], hash[:content].first.keys
+ end
+
+ def test_indifferent_hash_with_array_of_hashes
+ hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] } }.with_indifferent_access
+ assert_equal "1", hash[:urls][:url].first[:address]
+
+ hash = hash.to_hash
+ assert_not hash.instance_of?(HashWithIndifferentAccess)
+ assert_not hash["urls"].instance_of?(HashWithIndifferentAccess)
+ assert_not hash["urls"]["url"].first.instance_of?(HashWithIndifferentAccess)
+ end
+
+ def test_should_preserve_array_subclass_when_value_is_array
+ array = SubclassingArray.new
+ array << { "address" => "1" }
+ hash = { "urls" => { "url" => array } }.with_indifferent_access
+ assert_equal SubclassingArray, hash[:urls][:url].class
+ end
+
+ def test_should_preserve_array_class_when_hash_value_is_frozen_array
+ array = SubclassingArray.new
+ array << { "address" => "1" }
+ hash = { "urls" => { "url" => array.freeze } }.with_indifferent_access
+ assert_equal SubclassingArray, hash[:urls][:url].class
+ end
+
+ def test_stringify_and_symbolize_keys_on_indifferent_preserves_hash
+ h = HashWithIndifferentAccess.new
+ h[:first] = 1
+ h = h.stringify_keys
+ assert_equal 1, h["first"]
+ h = HashWithIndifferentAccess.new
+ h["first"] = 1
+ h = h.symbolize_keys
+ assert_equal 1, h[:first]
+ end
+
+ def test_deep_stringify_and_deep_symbolize_keys_on_indifferent_preserves_hash
+ h = HashWithIndifferentAccess.new
+ h[:first] = 1
+ h = h.deep_stringify_keys
+ assert_equal 1, h["first"]
+ h = HashWithIndifferentAccess.new
+ h["first"] = 1
+ h = h.deep_symbolize_keys
+ assert_equal 1, h[:first]
+ end
+
+ def test_to_options_on_indifferent_preserves_hash
+ h = HashWithIndifferentAccess.new
+ h["first"] = 1
+ h.to_options!
+ assert_equal 1, h["first"]
+ end
+
+ def test_to_options_on_indifferent_preserves_works_as_hash_with_dup
+ h = HashWithIndifferentAccess.new(a: { b: "b" })
+ dup = h.dup
+
+ dup[:a][:c] = "c"
+ assert_equal "c", h[:a][:c]
+ end
+
+ def test_indifferent_sub_hashes
+ h = { "user" => { "id" => 5 } }.with_indifferent_access
+ ["user", :user].each { |user| [:id, "id"].each { |id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5" } }
+
+ h = { user: { id: 5 } }.with_indifferent_access
+ ["user", :user].each { |user| [:id, "id"].each { |id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5" } }
+ end
+
+ def test_indifferent_duplication
+ # Should preserve default value
+ h = HashWithIndifferentAccess.new
+ h.default = "1234"
+ assert_equal h.default, h.dup.default
+
+ # Should preserve class for subclasses
+ h = IndifferentHash.new
+ assert_equal h.class, h.dup.class
+ end
+
+ def test_nested_dig_indifferent_access
+ skip if RUBY_VERSION < "2.3.0"
+ data = { "this" => { "views" => 1234 } }.with_indifferent_access
+ assert_equal 1234, data.dig(:this, :views)
+ end
+
+ def test_argless_default_with_existing_nil_key
+ h = Hash.new(:default).merge(nil => "defined").with_indifferent_access
+
+ assert_equal :default, h.default
+ end
+
+ def test_default_with_argument
+ h = Hash.new { 5 }.merge(1 => 2).with_indifferent_access
+
+ assert_equal 5, h.default(1)
+ end
+
+ def test_default_proc
+ h = ActiveSupport::HashWithIndifferentAccess.new { |hash, key| key }
+
+ assert_nil h.default
+ assert_equal "foo", h.default("foo")
+ assert_equal "foo", h.default(:foo)
+ end
+
+ def test_double_conversion_with_nil_key
+ h = { nil => "defined" }.with_indifferent_access.with_indifferent_access
+
+ assert_nil h[:undefined_key]
+ end
+
+ def test_assorted_keys_not_stringified
+ original = { Object.new => 2, 1 => 2, [] => true }
+ indiff = original.with_indifferent_access
+ assert(!indiff.keys.any? { |k| k.kind_of? String }, "A key was converted to a string!")
+ end
+
+ def test_deep_merge_on_indifferent_access
+ hash_1 = HashWithIndifferentAccess.new(a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } })
+ hash_2 = HashWithIndifferentAccess.new(a: 1, c: { c1: 2, c3: { d2: "d2" } })
+ hash_3 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } }
+ expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } }
+ assert_equal expected, hash_1.deep_merge(hash_2)
+ assert_equal expected, hash_1.deep_merge(hash_3)
+
+ hash_1.deep_merge!(hash_2)
+ assert_equal expected, hash_1
+ end
+
+ def test_store_on_indifferent_access
+ hash = HashWithIndifferentAccess.new
+ hash.store(:test1, 1)
+ hash.store("test1", 11)
+ hash[:test2] = 2
+ hash["test2"] = 22
+ expected = { "test1" => 11, "test2" => 22 }
+ assert_equal expected, hash
+ end
+
+ def test_constructor_on_indifferent_access
+ hash = HashWithIndifferentAccess[:foo, 1]
+ assert_equal 1, hash[:foo]
+ assert_equal 1, hash["foo"]
+ hash[:foo] = 3
+ assert_equal 3, hash[:foo]
+ assert_equal 3, hash["foo"]
+ end
+
+ def test_indifferent_slice
+ original = { a: "x", b: "y", c: 10 }.with_indifferent_access
+ expected = { a: "x", b: "y" }.with_indifferent_access
+
+ [["a", "b"], [:a, :b]].each do |keys|
+ # 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)
+ end
+ end
+
+ def test_indifferent_slice_access_with_symbols
+ original = { "login" => "bender", "password" => "shiny", "stuff" => "foo" }
+ original = original.with_indifferent_access
+
+ slice = original.slice(:login, :password)
+
+ assert_equal "bender", slice[:login]
+ assert_equal "bender", slice["login"]
+ end
+
+ def test_indifferent_extract
+ original = { :a => 1, "b" => 2, :c => 3, "d" => 4 }.with_indifferent_access
+ expected = { a: 1, b: 2 }.with_indifferent_access
+ remaining = { c: 3, d: 4 }.with_indifferent_access
+
+ [["a", "b"], [:a, :b]].each do |keys|
+ copy = original.dup
+ assert_equal expected, copy.extract!(*keys)
+ assert_equal remaining, copy
+ end
+ end
+
+ def test_new_with_to_hash_conversion
+ hash = HashWithIndifferentAccess.new(HashByConversion.new(a: 1))
+ assert hash.key?("a")
+ assert_equal 1, hash[:a]
+ end
+
+ def test_dup_with_default_proc
+ hash = HashWithIndifferentAccess.new
+ hash.default_proc = proc { |h, v| raise "walrus" }
+ assert_nothing_raised { hash.dup }
+ end
+
+ def test_dup_with_default_proc_sets_proc
+ hash = HashWithIndifferentAccess.new
+ hash.default_proc = proc { |h, k| k + 1 }
+ new_hash = hash.dup
+
+ assert_equal 3, new_hash[2]
+
+ new_hash.default = 2
+ assert_equal 2, new_hash[:non_existent]
+ end
+
+ def test_to_hash_with_raising_default_proc
+ hash = HashWithIndifferentAccess.new
+ hash.default_proc = proc { |h, k| raise "walrus" }
+
+ assert_nothing_raised { hash.to_hash }
+ end
+
+ def test_new_with_to_hash_conversion_copies_default
+ normal_hash = Hash.new(3)
+ normal_hash[:a] = 1
+
+ hash = HashWithIndifferentAccess.new(HashByConversion.new(normal_hash))
+ assert_equal 1, hash[:a]
+ assert_equal 3, hash[:b]
+ end
+
+ def test_new_with_to_hash_conversion_copies_default_proc
+ normal_hash = Hash.new { 1 + 2 }
+ normal_hash[:a] = 1
+
+ hash = HashWithIndifferentAccess.new(HashByConversion.new(normal_hash))
+ assert_equal 1, hash[:a]
+ assert_equal 3, hash[:b]
+ end
+
+ def test_inheriting_from_top_level_hash_with_indifferent_access_preserves_ancestors_chain
+ klass = Class.new(::HashWithIndifferentAccess)
+ assert_equal ActiveSupport::HashWithIndifferentAccess, klass.ancestors[1]
+ end
+
+ def test_inheriting_from_hash_with_indifferent_access_properly_dumps_ivars
+ klass = Class.new(::HashWithIndifferentAccess) do
+ def initialize(*)
+ @foo = "bar"
+ super
+ end
+ end
+
+ yaml_output = klass.new.to_yaml
+
+ # `hash-with-ivars` was introduced in 2.0.9 (https://git.io/vyUQW)
+ if Gem::Version.new(Psych::VERSION) >= Gem::Version.new("2.0.9")
+ assert_includes yaml_output, "hash-with-ivars"
+ assert_includes yaml_output, "@foo: bar"
+ else
+ assert_includes yaml_output, "hash"
+ end
+ end
+
+ def test_should_use_default_proc_for_unknown_key
+ hash_wia = HashWithIndifferentAccess.new { 1 + 2 }
+ assert_equal 3, hash_wia[:new_key]
+ end
+
+ def test_should_return_nil_if_no_key_is_supplied
+ hash_wia = HashWithIndifferentAccess.new { 1 + 2 }
+ assert_nil hash_wia.default
+ end
+
+ def test_should_use_default_value_for_unknown_key
+ hash_wia = HashWithIndifferentAccess.new(3)
+ assert_equal 3, hash_wia[:new_key]
+ end
+
+ def test_should_use_default_value_if_no_key_is_supplied
+ hash_wia = HashWithIndifferentAccess.new(3)
+ assert_equal 3, hash_wia.default
+ end
+
+ def test_should_nil_if_no_default_value_is_supplied
+ hash_wia = HashWithIndifferentAccess.new
+ assert_nil hash_wia.default
+ end
+
+ def test_should_return_dup_for_with_indifferent_access
+ hash_wia = HashWithIndifferentAccess.new
+ assert_equal hash_wia, hash_wia.with_indifferent_access
+ assert_not_same hash_wia, hash_wia.with_indifferent_access
+ end
+
+ def test_allows_setting_frozen_array_values_with_indifferent_access
+ value = [1, 2, 3].freeze
+ hash = HashWithIndifferentAccess.new
+ hash[:key] = value
+ assert_equal hash[:key], value
+ end
+
+ def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
+ hash = Hash.new(3)
+ hash_wia = hash.with_indifferent_access
+ assert_equal 3, hash_wia.default
+ end
+
+ def test_should_copy_the_default_proc_when_converting_to_hash_with_indifferent_access
+ hash = Hash.new do
+ 2 + 1
+ end
+ assert_equal 3, hash[:foo]
+
+ hash_wia = hash.with_indifferent_access
+ assert_equal 3, hash_wia[:foo]
+ assert_equal 3, hash_wia[:bar]
+ end
+end
diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb
index 3faa15e7fd..8ad9441f9d 100644
--- a/activesupport/test/i18n_test.rb
+++ b/activesupport/test/i18n_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'active_support/core_ext/array/conversions'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "active_support/core_ext/array/conversions"
class I18nTest < ActiveSupport::TestCase
def setup
@@ -18,15 +20,15 @@ class I18nTest < ActiveSupport::TestCase
end
def test_date_localization_with_default_format
- assert_equal @date.strftime("%Y-%m-%d"), I18n.localize(@date, :format => :default)
+ assert_equal @date.strftime("%Y-%m-%d"), I18n.localize(@date, format: :default)
end
def test_date_localization_with_short_format
- assert_equal @date.strftime("%b %d"), I18n.localize(@date, :format => :short)
+ assert_equal @date.strftime("%b %d"), I18n.localize(@date, format: :short)
end
def test_date_localization_with_long_format
- assert_equal @date.strftime("%B %d, %Y"), I18n.localize(@date, :format => :long)
+ assert_equal @date.strftime("%B %d, %Y"), I18n.localize(@date, format: :long)
end
def test_time_localization_should_use_default_format
@@ -34,15 +36,15 @@ class I18nTest < ActiveSupport::TestCase
end
def test_time_localization_with_default_format
- assert_equal @time.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(@time, :format => :default)
+ assert_equal @time.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(@time, format: :default)
end
def test_time_localization_with_short_format
- assert_equal @time.strftime("%d %b %H:%M"), I18n.localize(@time, :format => :short)
+ assert_equal @time.strftime("%d %b %H:%M"), I18n.localize(@time, format: :short)
end
def test_time_localization_with_long_format
- assert_equal @time.strftime("%B %d, %Y %H:%M"), I18n.localize(@time, :format => :long)
+ assert_equal @time.strftime("%B %d, %Y %H:%M"), I18n.localize(@time, format: :long)
end
def test_day_names
@@ -66,39 +68,39 @@ class I18nTest < ActiveSupport::TestCase
end
def test_time_am
- assert_equal 'am', I18n.translate(:'time.am')
+ assert_equal "am", I18n.translate(:'time.am')
end
def test_time_pm
- assert_equal 'pm', I18n.translate(:'time.pm')
+ assert_equal "pm", I18n.translate(:'time.pm')
end
def test_words_connector
- assert_equal ', ', I18n.translate(:'support.array.words_connector')
+ assert_equal ", ", I18n.translate(:'support.array.words_connector')
end
def test_two_words_connector
- assert_equal ' and ', I18n.translate(:'support.array.two_words_connector')
+ assert_equal " and ", I18n.translate(:'support.array.two_words_connector')
end
def test_last_word_connector
- assert_equal ', and ', I18n.translate(:'support.array.last_word_connector')
+ assert_equal ", and ", I18n.translate(:'support.array.last_word_connector')
end
def test_to_sentence
default_two_words_connector = I18n.translate(:'support.array.two_words_connector')
default_last_word_connector = I18n.translate(:'support.array.last_word_connector')
- assert_equal 'a, b, and c', %w[a b c].to_sentence
- I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => ' & ' } }
- assert_equal 'a & b', %w[a b].to_sentence
- I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => ' and ' } }
- assert_equal 'a, b and c', %w[a b c].to_sentence
+ assert_equal "a, b, and c", %w[a b c].to_sentence
+ I18n.backend.store_translations "en", support: { array: { two_words_connector: " & " } }
+ assert_equal "a & b", %w[a b].to_sentence
+ I18n.backend.store_translations "en", support: { array: { last_word_connector: " and " } }
+ assert_equal "a, b and c", %w[a b c].to_sentence
ensure
- I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => default_two_words_connector } }
- I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => default_last_word_connector } }
+ I18n.backend.store_translations "en", support: { array: { two_words_connector: default_two_words_connector } }
+ I18n.backend.store_translations "en", support: { array: { last_word_connector: default_last_word_connector } }
end
def test_to_sentence_with_empty_i18n_store
- assert_equal 'a, b, and c', %w[a b c].to_sentence(locale: 'empty')
+ assert_equal "a, b, and c", %w[a b c].to_sentence(locale: "empty")
end
end
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index 06cd41c86d..0e3e576a70 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -1,8 +1,10 @@
-require 'abstract_unit'
-require 'active_support/inflector'
+# frozen_string_literal: true
-require 'inflector_test_cases'
-require 'constantize_test_cases'
+require "abstract_unit"
+require "active_support/inflector"
+
+require "inflector_test_cases"
+require "constantize_test_cases"
class InflectorTest < ActiveSupport::TestCase
include InflectorTestCases
@@ -31,6 +33,32 @@ class InflectorTest < ActiveSupport::TestCase
assert_equal "", ActiveSupport::Inflector.pluralize("")
end
+ test "uncountability of ascii word" do
+ word = "HTTP"
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.uncountable word
+ end
+
+ assert_equal word, ActiveSupport::Inflector.pluralize(word)
+ assert_equal word, ActiveSupport::Inflector.singularize(word)
+ assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word)
+
+ ActiveSupport::Inflector.inflections.uncountables.pop
+ end
+
+ test "uncountability of non-ascii word" do
+ word = "猫"
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.uncountable word
+ end
+
+ assert_equal word, ActiveSupport::Inflector.pluralize(word)
+ assert_equal word, ActiveSupport::Inflector.singularize(word)
+ assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word)
+
+ ActiveSupport::Inflector.inflections.uncountables.pop
+ end
+
ActiveSupport::Inflector.inflections.uncountable.each do |word|
define_method "test_uncountability_of_#{word}" do
assert_equal word, ActiveSupport::Inflector.singularize(word)
@@ -80,7 +108,6 @@ class InflectorTest < ActiveSupport::TestCase
end
end
-
def test_overwrite_previous_inflectors
assert_equal("series", ActiveSupport::Inflector.singularize("series"))
ActiveSupport::Inflector.inflections.singular "series", "serie"
@@ -94,6 +121,13 @@ class InflectorTest < ActiveSupport::TestCase
end
end
+ MixtureToTitleCaseWithKeepIdSuffix.each_with_index do |(before, titleized), index|
+ define_method "test_titleize_with_keep_id_suffix_mixture_to_title_case_#{index}" do
+ assert_equal(titleized, ActiveSupport::Inflector.titleize(before, keep_id_suffix: true),
+ "mixture to TitleCase with keep_id_suffix failed for #{before}")
+ end
+ end
+
def test_camelize
CamelToUnderscore.each do |camel, underscore|
assert_equal(camel, ActiveSupport::Inflector.camelize(underscore))
@@ -101,11 +135,11 @@ class InflectorTest < ActiveSupport::TestCase
end
def test_camelize_with_lower_downcases_the_first_letter
- assert_equal('capital', ActiveSupport::Inflector.camelize('Capital', false))
+ assert_equal("capital", ActiveSupport::Inflector.camelize("Capital", false))
end
def test_camelize_with_underscores
- assert_equal("CamelCase", ActiveSupport::Inflector.camelize('Camel_Case'))
+ assert_equal("CamelCase", ActiveSupport::Inflector.camelize("Camel_Case"))
end
def test_acronyms
@@ -190,6 +224,12 @@ class InflectorTest < ActiveSupport::TestCase
assert_equal("json_html_api", ActiveSupport::Inflector.underscore("JSONHTMLAPI"))
end
+ def test_acronym_regexp_is_deprecated
+ assert_deprecated do
+ ActiveSupport::Inflector.inflections.acronym_regex
+ end
+ end
+
def test_underscore
CamelToUnderscore.each do |camel, underscore|
assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
@@ -246,55 +286,27 @@ class InflectorTest < ActiveSupport::TestCase
end
end
-# FIXME: get following tests to pass on jruby, currently skipped
-#
-# Currently this fails because ActiveSupport::Multibyte::Unicode#tidy_bytes
-# required a specific Encoding::Converter(UTF-8 to UTF8-MAC) which unavailable on JRuby
-# causing our tests to error out.
-# related bug http://jira.codehaus.org/browse/JRUBY-7194
def test_parameterize
- jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterized.each do |some_string, parameterized_string|
assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
end
end
def test_parameterize_and_normalize
- jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterizedAndNormalized.each do |some_string, parameterized_string|
assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
end
end
def test_parameterize_with_custom_separator
- jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
- StringToParameterizeWithUnderscore.each do |some_string, parameterized_string|
- assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string, separator: '_'))
- end
- end
-
- def test_parameterize_with_custom_separator_deprecated
- jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterizeWithUnderscore.each do |some_string, parameterized_string|
- assert_deprecated(/Passing the separator argument as a positional parameter is deprecated and will soon be removed. Use `separator: '_'` instead./i) do
- assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string, '_'))
- end
+ assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string, separator: "_"))
end
end
def test_parameterize_with_multi_character_separator
- jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterized.each do |some_string, parameterized_string|
- assert_equal(parameterized_string.gsub('-', '__sep__'), ActiveSupport::Inflector.parameterize(some_string, separator: '__sep__'))
- end
- end
-
- def test_parameterize_with_multi_character_separator_deprecated
- jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
- StringToParameterized.each do |some_string, parameterized_string|
- assert_deprecated(/Passing the separator argument as a positional parameter is deprecated and will soon be removed. Use `separator: '__sep__'` instead./i) do
- assert_equal(parameterized_string.gsub('-', '__sep__'), ActiveSupport::Inflector.parameterize(some_string, '__sep__'))
- end
+ assert_equal(parameterized_string.gsub("-", "__sep__"), ActiveSupport::Inflector.parameterize(some_string, separator: "__sep__"))
end
end
@@ -307,12 +319,12 @@ class InflectorTest < ActiveSupport::TestCase
def test_classify_with_symbol
assert_nothing_raised do
- assert_equal 'FooBar', ActiveSupport::Inflector.classify(:foo_bars)
+ assert_equal "FooBar", ActiveSupport::Inflector.classify(:foo_bars)
end
end
def test_classify_with_leading_schema_name
- assert_equal 'FooBar', ActiveSupport::Inflector.classify('schema.foo_bar')
+ assert_equal "FooBar", ActiveSupport::Inflector.classify("schema.foo_bar")
end
def test_humanize
@@ -327,6 +339,12 @@ class InflectorTest < ActiveSupport::TestCase
end
end
+ def test_humanize_with_keep_id_suffix
+ UnderscoreToHumanWithKeepIdSuffix.each do |underscore, human|
+ assert_equal(human, ActiveSupport::Inflector.humanize(underscore, keep_id_suffix: true))
+ end
+ end
+
def test_humanize_by_rule
ActiveSupport::Inflector.inflections do |inflect|
inflect.human(/_cnt$/i, '\1_count')
@@ -344,6 +362,19 @@ class InflectorTest < ActiveSupport::TestCase
assert_equal("Col rpted bugs", ActiveSupport::Inflector.humanize("COL_rpted_bugs"))
end
+ def test_humanize_with_acronyms
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym "LAX"
+ inflect.acronym "SFO"
+ end
+ assert_equal("LAX roundtrip to SFO", ActiveSupport::Inflector.humanize("LAX ROUNDTRIP TO SFO"))
+ assert_equal("LAX roundtrip to SFO", ActiveSupport::Inflector.humanize("LAX ROUNDTRIP TO SFO", capitalize: false))
+ assert_equal("LAX roundtrip to SFO", ActiveSupport::Inflector.humanize("lax roundtrip to sfo"))
+ assert_equal("LAX roundtrip to SFO", ActiveSupport::Inflector.humanize("lax roundtrip to sfo", capitalize: false))
+ assert_equal("LAX roundtrip to SFO", ActiveSupport::Inflector.humanize("Lax Roundtrip To Sfo"))
+ assert_equal("LAX roundtrip to SFO", ActiveSupport::Inflector.humanize("Lax Roundtrip To Sfo", capitalize: false))
+ end
+
def test_constantize
run_constantize_tests_on do |string|
ActiveSupport::Inflector.constantize(string)
@@ -403,31 +434,38 @@ class InflectorTest < ActiveSupport::TestCase
def test_inflector_locality
ActiveSupport::Inflector.inflections(:es) do |inflect|
- inflect.plural(/$/, 's')
- inflect.plural(/z$/i, 'ces')
+ inflect.plural(/$/, "s")
+ inflect.plural(/z$/i, "ces")
+
+ inflect.singular(/s$/, "")
+ inflect.singular(/es$/, "")
- inflect.singular(/s$/, '')
- inflect.singular(/es$/, '')
+ inflect.irregular("el", "los")
- inflect.irregular('el', 'los')
+ inflect.uncountable("agua")
end
- assert_equal('hijos', 'hijo'.pluralize(:es))
- assert_equal('luces', 'luz'.pluralize(:es))
- assert_equal('luzs', 'luz'.pluralize)
+ assert_equal("hijos", "hijo".pluralize(:es))
+ assert_equal("luces", "luz".pluralize(:es))
+ assert_equal("luzs", "luz".pluralize)
+
+ assert_equal("sociedad", "sociedades".singularize(:es))
+ assert_equal("sociedade", "sociedades".singularize)
- assert_equal('sociedad', 'sociedades'.singularize(:es))
- assert_equal('sociedade', 'sociedades'.singularize)
+ assert_equal("los", "el".pluralize(:es))
+ assert_equal("els", "el".pluralize)
- assert_equal('los', 'el'.pluralize(:es))
- assert_equal('els', 'el'.pluralize)
+ assert_equal("agua", "agua".pluralize(:es))
+ assert_equal("aguas", "agua".pluralize)
ActiveSupport::Inflector.inflections(:es) { |inflect| inflect.clear }
assert ActiveSupport::Inflector.inflections(:es).plurals.empty?
assert ActiveSupport::Inflector.inflections(:es).singulars.empty?
+ assert ActiveSupport::Inflector.inflections(:es).uncountables.empty?
assert !ActiveSupport::Inflector.inflections.plurals.empty?
assert !ActiveSupport::Inflector.inflections.singulars.empty?
+ assert !ActiveSupport::Inflector.inflections.uncountables.empty?
end
def test_clear_all
@@ -435,7 +473,7 @@ class InflectorTest < ActiveSupport::TestCase
# ensure any data is present
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/(database)s$/i, '\1')
- inflect.uncountable('series')
+ inflect.uncountable("series")
inflect.human("col_rpted_bugs", "Reported bugs")
inflect.clear :all
@@ -452,7 +490,7 @@ class InflectorTest < ActiveSupport::TestCase
# ensure any data is present
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/(database)s$/i, '\1')
- inflect.uncountable('series')
+ inflect.uncountable("series")
inflect.human("col_rpted_bugs", "Reported bugs")
inflect.clear
@@ -526,12 +564,4 @@ class InflectorTest < ActiveSupport::TestCase
end
end
end
-
- def test_inflections_with_uncountable_words
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.uncountable "HTTP"
- end
-
- assert_equal "HTTP", ActiveSupport::Inflector.pluralize("HTTP")
- end
end
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 14fe97a986..689370cccf 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module InflectorTestCases
SingularToPlural = {
"search" => "searches",
@@ -128,10 +130,10 @@ module InflectorTestCases
}
SymbolToLowerCamel = {
- :product => 'product',
- :special_guest => 'specialGuest',
- :application_controller => 'applicationController',
- :area51_controller => 'area51Controller'
+ product: "product",
+ special_guest: "specialGuest",
+ application_controller: "applicationController",
+ area51_controller: "area51Controller"
}
CamelToUnderscoreWithoutReverse = {
@@ -176,12 +178,12 @@ module InflectorTestCases
StringToParameterizedPreserveCase = {
"Donald E. Knuth" => "Donald-E-Knuth",
- "Random text with *(bad)* characters" => "Random-text-with-bad-characters",
- "Allow_Under_Scores" => "Allow_Under_Scores",
- "Trailing bad characters!@#" => "Trailing-bad-characters",
- "!@#Leading bad characters" => "Leading-bad-characters",
- "Squeeze separators" => "Squeeze-separators",
- "Test with + sign" => "Test-with-sign",
+ "Random text with *(bad)* characters" => "Random-text-with-bad-characters",
+ "Allow_Under_Scores" => "Allow_Under_Scores",
+ "Trailing bad characters!@#" => "Trailing-bad-characters",
+ "!@#Leading bad characters" => "Leading-bad-characters",
+ "Squeeze separators" => "Squeeze-separators",
+ "Test with + sign" => "Test-with-sign",
"Test with malformed utf8 \xA9" => "Test-with-malformed-utf8"
}
@@ -199,11 +201,11 @@ module InflectorTestCases
StringToParameterizePreserveCaseWithNoSeparator = {
"Donald E. Knuth" => "DonaldEKnuth",
"With-some-dashes" => "With-some-dashes",
- "Random text with *(bad)* characters" => "Randomtextwithbadcharacters",
- "Trailing bad characters!@#" => "Trailingbadcharacters",
- "!@#Leading bad characters" => "Leadingbadcharacters",
- "Squeeze separators" => "Squeezeseparators",
- "Test with + sign" => "Testwithsign",
+ "Random text with *(bad)* characters" => "Randomtextwithbadcharacters",
+ "Trailing bad characters!@#" => "Trailingbadcharacters",
+ "!@#Leading bad characters" => "Leadingbadcharacters",
+ "Squeeze separators" => "Squeezeseparators",
+ "Test with + sign" => "Testwithsign",
"Test with malformed utf8 \xA9" => "Testwithmalformedutf8"
}
@@ -219,15 +221,15 @@ module InflectorTestCases
"Test with malformed utf8 \251" => "test_with_malformed_utf8"
}
- StringToParameterizePreserceCaseWithUnderscore = {
- "Donald E. Knuth" => "Donald_E_Knuth",
+ StringToParameterizePreserveCaseWithUnderscore = {
+ "Donald E. Knuth" => "Donald_E_Knuth",
"Random text with *(bad)* characters" => "Random_text_with_bad_characters",
- "With-some-dashes" => "With-some-dashes",
- "Allow_Under_Scores" => "Allow_Under_Scores",
- "Trailing bad characters!@#" => "Trailing_bad_characters",
- "!@#Leading bad characters" => "Leading_bad_characters",
- "Squeeze separators" => "Squeeze_separators",
- "Test with + sign" => "Test_with_sign",
+ "With-some-dashes" => "With-some-dashes",
+ "Allow_Under_Scores" => "Allow_Under_Scores",
+ "Trailing bad characters!@#" => "Trailing_bad_characters",
+ "!@#Leading bad characters" => "Leading_bad_characters",
+ "Squeeze separators" => "Squeeze_separators",
+ "Test with + sign" => "Test_with_sign",
"Test with malformed utf8 \xA9" => "Test_with_malformed_utf8"
}
@@ -237,15 +239,24 @@ module InflectorTestCases
"Ops\331" => "opsu",
"Ærøskøbing" => "aeroskobing",
"Aßlar" => "asslar",
- "Japanese: 日本語" => "japanese"
+ "Japanese: 日本語" => "japanese"
}
UnderscoreToHuman = {
- 'employee_salary' => 'Employee salary',
- 'employee_id' => 'Employee',
- 'underground' => 'Underground',
- '_id' => 'Id',
- '_external_id' => 'External'
+ "employee_salary" => "Employee salary",
+ "employee_id" => "Employee",
+ "underground" => "Underground",
+ "_id" => "Id",
+ "_external_id" => "External"
+ }
+
+ UnderscoreToHumanWithKeepIdSuffix = {
+ "this_is_a_string_ending_with_id" => "This is a string ending with id",
+ "employee_id" => "Employee id",
+ "employee_id_something_else" => "Employee id something else",
+ "underground" => "Underground",
+ "_id" => "Id",
+ "_external_id" => "External id"
}
UnderscoreToHumanWithoutCapitalize = {
@@ -254,23 +265,31 @@ module InflectorTestCases
"underground" => "underground"
}
+ MixtureToTitleCaseWithKeepIdSuffix = {
+ "this_is_a_string_ending_with_id" => "This Is A String Ending With Id",
+ "EmployeeId" => "Employee Id",
+ "Author Id" => "Author Id"
+ }
+
MixtureToTitleCase = {
- 'active_record' => 'Active Record',
- 'ActiveRecord' => 'Active Record',
- 'action web service' => 'Action Web Service',
- 'Action Web Service' => 'Action Web Service',
- 'Action web service' => 'Action Web Service',
- 'actionwebservice' => 'Actionwebservice',
- 'Actionwebservice' => 'Actionwebservice',
+ "active_record" => "Active Record",
+ "ActiveRecord" => "Active Record",
+ "action web service" => "Action Web Service",
+ "Action Web Service" => "Action Web Service",
+ "Action web service" => "Action Web Service",
+ "actionwebservice" => "Actionwebservice",
+ "Actionwebservice" => "Actionwebservice",
"david's code" => "David's Code",
"David's code" => "David's Code",
"david's Code" => "David's Code",
"sgt. pepper's" => "Sgt. Pepper's",
"i've just seen a face" => "I've Just Seen A Face",
"maybe you'll be there" => "Maybe You'll Be There",
- "¿por qué?" => '¿Por Qué?',
+ "¿por qué?" => "¿Por Qué?",
"Fred’s" => "Fred’s",
- "Fred`s" => "Fred`s"
+ "Fred`s" => "Fred`s",
+ "this was 'fake news'" => "This Was 'Fake News'",
+ ActiveSupport::SafeBuffer.new("confirmation num") => "Confirmation Num"
}
OrdinalNumbers = {
@@ -344,13 +363,13 @@ module InflectorTestCases
}
Irregularities = {
- 'person' => 'people',
- 'man' => 'men',
- 'child' => 'children',
- 'sex' => 'sexes',
- 'move' => 'moves',
- 'cow' => 'kine', # Test inflections with different starting letters
- 'zombie' => 'zombies',
- 'genus' => 'genera'
+ "person" => "people",
+ "man" => "men",
+ "child" => "children",
+ "sex" => "sexes",
+ "move" => "moves",
+ "cow" => "kine", # Test inflections with different starting letters
+ "zombie" => "zombies",
+ "genus" => "genera"
}
end
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index f2fc456f4b..8d9587f248 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -1,8 +1,13 @@
-require 'abstract_unit'
-require 'active_support/json'
-require 'active_support/time'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/json"
+require "active_support/time"
+require "time_zone_test_helpers"
class TestJSONDecoding < ActiveSupport::TestCase
+ include TimeZoneTestHelpers
+
class Foo
def self.json_create(object)
"Foo"
@@ -10,72 +15,80 @@ class TestJSONDecoding < ActiveSupport::TestCase
end
TESTS = {
- %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}},
- %q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}},
- %q({"returnTo":{"\/categories":1}}) => {"returnTo" => {"/categories" => 1}},
- %({"returnTo":[1,"a"]}) => {"returnTo" => [1, "a"]},
- %({"returnTo":[1,"\\"a\\",", "b"]}) => {"returnTo" => [1, "\"a\",", "b"]},
- %({"a": "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"},
- %({"a": "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"},
+ %q({"returnTo":{"\/categories":"\/"}}) => { "returnTo" => { "/categories" => "/" } },
+ %q({"return\\"To\\":":{"\/categories":"\/"}}) => { "return\"To\":" => { "/categories" => "/" } },
+ %q({"returnTo":{"\/categories":1}}) => { "returnTo" => { "/categories" => 1 } },
+ %({"returnTo":[1,"a"]}) => { "returnTo" => [1, "a"] },
+ %({"returnTo":[1,"\\"a\\",", "b"]}) => { "returnTo" => [1, "\"a\",", "b"] },
+ %({"a": "'", "b": "5,000"}) => { "a" => "'", "b" => "5,000" },
+ %({"a": "a's, b's and c's", "b": "5,000"}) => { "a" => "a's, b's and c's", "b" => "5,000" },
# multibyte
- %({"matzue": "松江", "asakusa": "浅草"}) => {"matzue" => "松江", "asakusa" => "浅草"},
- %({"a": "2007-01-01"}) => {'a' => Date.new(2007, 1, 1)},
- %({"a": "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)},
+ %({"matzue": "松江", "asakusa": "浅草"}) => { "matzue" => "松江", "asakusa" => "浅草" },
+ %({"a": "2007-01-01"}) => { "a" => Date.new(2007, 1, 1) },
+ %({"a": "2007-01-01 01:12:34 Z"}) => { "a" => Time.utc(2007, 1, 1, 1, 12, 34) },
%(["2007-01-01 01:12:34 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34)],
%(["2007-01-01 01:12:34 Z", "2007-01-01 01:12:35 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34), Time.utc(2007, 1, 1, 1, 12, 35)],
# no time zone
- %({"a": "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"},
+ %({"a": "2007-01-01 01:12:34"}) => { "a" => Time.new(2007, 1, 1, 1, 12, 34, "-05:00") },
# invalid date
- %({"a": "1089-10-40"}) => {'a' => "1089-10-40"},
+ %({"a": "1089-10-40"}) => { "a" => "1089-10-40" },
# xmlschema date notation
- %({"a": "2009-08-10T19:01:02Z"}) => {'a' => Time.utc(2009, 8, 10, 19, 1, 2)},
- %({"a": "2009-08-10T19:01:02+02:00"}) => {'a' => Time.utc(2009, 8, 10, 17, 1, 2)},
- %({"a": "2009-08-10T19:01:02-05:00"}) => {'a' => Time.utc(2009, 8, 11, 00, 1, 2)},
+ %({"a": "2009-08-10T19:01:02"}) => { "a" => Time.new(2009, 8, 10, 19, 1, 2, "-04:00") },
+ %({"a": "2009-08-10T19:01:02Z"}) => { "a" => Time.utc(2009, 8, 10, 19, 1, 2) },
+ %({"a": "2009-08-10T19:01:02+02:00"}) => { "a" => Time.utc(2009, 8, 10, 17, 1, 2) },
+ %({"a": "2009-08-10T19:01:02-05:00"}) => { "a" => Time.utc(2009, 8, 11, 00, 1, 2) },
# needs to be *exact*
- %({"a": " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "},
- %({"a": "2007-01-01 : it's your birthday"}) => {'a' => "2007-01-01 : it's your birthday"},
+ %({"a": " 2007-01-01 01:12:34 Z "}) => { "a" => " 2007-01-01 01:12:34 Z " },
+ %({"a": "2007-01-01 : it's your birthday"}) => { "a" => "2007-01-01 : it's your birthday" },
%([]) => [],
%({}) => {},
- %({"a":1}) => {"a" => 1},
- %({"a": ""}) => {"a" => ""},
- %({"a":"\\""}) => {"a" => "\""},
- %({"a": null}) => {"a" => nil},
- %({"a": true}) => {"a" => true},
- %({"a": false}) => {"a" => false},
- %q({"bad":"\\\\","trailing":""}) => {"bad" => "\\", "trailing" => ""},
- %q({"a": "http:\/\/test.host\/posts\/1"}) => {"a" => "http://test.host/posts/1"},
- %q({"a": "\u003cunicode\u0020escape\u003e"}) => {"a" => "<unicode escape>"},
- %q({"a": "\\\\u0020skip double backslashes"}) => {"a" => "\\u0020skip double backslashes"},
- %q({"a": "\u003cbr /\u003e"}) => {'a' => "<br />"},
- %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => {'b' => ["<i>","<b>","<u>"]},
+ %({"a":1}) => { "a" => 1 },
+ %({"a": ""}) => { "a" => "" },
+ %({"a":"\\""}) => { "a" => "\"" },
+ %({"a": null}) => { "a" => nil },
+ %({"a": true}) => { "a" => true },
+ %({"a": false}) => { "a" => false },
+ '{"bad":"\\\\","trailing":""}' => { "bad" => "\\", "trailing" => "" },
+ %q({"a": "http:\/\/test.host\/posts\/1"}) => { "a" => "http://test.host/posts/1" },
+ %q({"a": "\u003cunicode\u0020escape\u003e"}) => { "a" => "<unicode escape>" },
+ '{"a": "\\\\u0020skip double backslashes"}' => { "a" => "\\u0020skip double backslashes" },
+ %q({"a": "\u003cbr /\u003e"}) => { "a" => "<br />" },
+ %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => { "b" => ["<i>", "<b>", "<u>"] },
# test combination of dates and escaped or unicode encoded data in arrays
%q([{"d":"1970-01-01", "s":"\u0020escape"},{"d":"1970-01-01", "s":"\u0020escape"}]) =>
- [{'d' => Date.new(1970, 1, 1), 's' => ' escape'},{'d' => Date.new(1970, 1, 1), 's' => ' escape'}],
+ [{ "d" => Date.new(1970, 1, 1), "s" => " escape" }, { "d" => Date.new(1970, 1, 1), "s" => " escape" }],
%q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) =>
- [{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'},
- {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}],
+ [{ "d" => Date.new(1970, 1, 1), "s" => "http://example.com" },
+ { "d" => Date.new(1970, 1, 1), "s" => "http://example.com" }],
# tests escaping of "\n" char with Yaml backend
- %q({"a":"\n"}) => {"a"=>"\n"},
- %q({"a":"\u000a"}) => {"a"=>"\n"},
- %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"},
+ %q({"a":"\n"}) => { "a" => "\n" },
+ %q({"a":"\u000a"}) => { "a" => "\n" },
+ %q({"a":"Line1\u000aLine2"}) => { "a" => "Line1\nLine2" },
# prevent json unmarshalling
- %q({"json_class":"TestJSONDecoding::Foo"}) => {"json_class"=>"TestJSONDecoding::Foo"},
+ '{"json_class":"TestJSONDecoding::Foo"}' => { "json_class" => "TestJSONDecoding::Foo" },
# json "fragments" - these are invalid JSON, but ActionPack relies on this
- %q("a string") => "a string",
- %q(1.1) => 1.1,
- %q(1) => 1,
- %q(-1) => -1,
- %q(true) => true,
- %q(false) => false,
- %q(null) => nil
+ '"a string"' => "a string",
+ "1.1" => 1.1,
+ "1" => 1,
+ "-1" => -1,
+ "true" => true,
+ "false" => false,
+ "null" => nil
}
TESTS.each_with_index do |(json, expected), index|
+ fail_message = "JSON decoding failed for #{json}"
+
test "json decodes #{index}" do
- with_parse_json_times(true) do
- silence_warnings do
- assert_equal expected, ActiveSupport::JSON.decode(json), "JSON decoding \
- failed for #{json}"
+ with_tz_default "Eastern Time (US & Canada)" do
+ with_parse_json_times(true) do
+ silence_warnings do
+ if expected.nil?
+ assert_nil ActiveSupport::JSON.decode(json), fail_message
+ else
+ assert_equal expected, ActiveSupport::JSON.decode(json), fail_message
+ end
+ end
end
end
end
@@ -83,7 +96,7 @@ class TestJSONDecoding < ActiveSupport::TestCase
test "json decodes time json with time parsing disabled" do
with_parse_json_times(false) do
- expected = {"a" => "2007-01-01 01:12:34 Z"}
+ expected = { "a" => "2007-01-01 01:12:34 Z" }
assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"}))
end
end
@@ -101,12 +114,11 @@ class TestJSONDecoding < ActiveSupport::TestCase
private
- def with_parse_json_times(value)
- old_value = ActiveSupport.parse_json_times
- ActiveSupport.parse_json_times = value
- yield
- ensure
- ActiveSupport.parse_json_times = old_value
- end
+ def with_parse_json_times(value)
+ old_value = ActiveSupport.parse_json_times
+ ActiveSupport.parse_json_times = value
+ yield
+ ensure
+ ActiveSupport.parse_json_times = old_value
+ end
end
-
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 5fc2e16336..340a2abf75 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -1,17 +1,23 @@
-require 'securerandom'
-require 'abstract_unit'
-require 'active_support/core_ext/string/inflections'
-require 'active_support/json'
-require 'active_support/time'
-require 'time_zone_test_helpers'
-require 'json/encoding_test_cases'
+# frozen_string_literal: true
+
+require "securerandom"
+require "abstract_unit"
+require "active_support/core_ext/string/inflections"
+require "active_support/core_ext/regexp"
+require "active_support/json"
+require "active_support/time"
+require "time_zone_test_helpers"
+require "json/encoding_test_cases"
class TestJSONEncoding < ActiveSupport::TestCase
include TimeZoneTestHelpers
def sorted_json(json)
- return json unless json =~ /^\{.*\}$/
- '{' + json[1..-2].split(',').sort.join(',') + '}'
+ if json.start_with?("{") && json.end_with?("}")
+ "{" + json[1..-2].split(",").sort.join(",") + "}"
+ else
+ json
+ end
end
JSONTest::EncodingTestCases.constants.each do |class_tests|
@@ -19,8 +25,10 @@ class TestJSONEncoding < ActiveSupport::TestCase
begin
prev = ActiveSupport.use_standard_json_time_format
- ActiveSupport.escape_html_entities_in_json = class_tests !~ /^Standard/
- ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/
+ standard_class_tests = /Standard/.match?(class_tests)
+
+ ActiveSupport.escape_html_entities_in_json = !standard_class_tests
+ ActiveSupport.use_standard_json_time_format = standard_class_tests
JSONTest::EncodingTestCases.const_get(class_tests).each do |pair|
assert_equal pair.last, sorted_json(ActiveSupport::JSON.encode(pair.first))
end
@@ -41,12 +49,12 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
def test_hash_encoding
- assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b)
- assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
- assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode('a' => [1,2])
+ assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(a: :b)
+ assert_equal %({\"a\":1}), ActiveSupport::JSON.encode("a" => 1)
+ assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode("a" => [1, 2])
assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2)
- assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d))
+ assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(a: :b, c: :d))
end
def test_hash_keys_encoding
@@ -57,24 +65,24 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
def test_utf8_string_encoded_properly
- result = ActiveSupport::JSON.encode('€2.99')
+ result = ActiveSupport::JSON.encode("€2.99")
assert_equal '"€2.99"', result
assert_equal(Encoding::UTF_8, result.encoding)
- result = ActiveSupport::JSON.encode('✎☺')
+ result = ActiveSupport::JSON.encode("✎☺")
assert_equal '"✎☺"', result
assert_equal(Encoding::UTF_8, result.encoding)
end
def test_non_utf8_string_transcodes
- s = '二'.encode('Shift_JIS')
+ s = "二".encode("Shift_JIS")
result = ActiveSupport::JSON.encode(s)
assert_equal '"二"', result
assert_equal Encoding::UTF_8, result.encoding
end
def test_wide_utf8_chars
- w = '𠜎'
+ w = "𠜎"
result = ActiveSupport::JSON.encode(w)
assert_equal '"𠜎"', result
end
@@ -83,33 +91,33 @@ class TestJSONEncoding < ActiveSupport::TestCase
hash = { string: "𐒑" }
json = ActiveSupport::JSON.encode(hash)
decoded_hash = ActiveSupport::JSON.decode(json)
- assert_equal "𐒑", decoded_hash['string']
+ assert_equal "𐒑", decoded_hash["string"]
end
def test_hash_key_identifiers_are_always_quoted
- values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"}
+ values = { 0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B" }
assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values))
end
def test_hash_should_allow_key_filtering_with_only
- assert_equal %({"a":1}), ActiveSupport::JSON.encode({'a' => 1, :b => 2, :c => 3}, :only => 'a')
+ assert_equal %({"a":1}), ActiveSupport::JSON.encode({ "a" => 1, :b => 2, :c => 3 }, { only: "a" })
end
def test_hash_should_allow_key_filtering_with_except
- assert_equal %({"b":2}), ActiveSupport::JSON.encode({'foo' => 'bar', :b => 2, :c => 3}, :except => ['foo', :c])
+ assert_equal %({"b":2}), ActiveSupport::JSON.encode({ "foo" => "bar", :b => 2, :c => 3 }, { except: ["foo", :c] })
end
def test_time_to_json_includes_local_offset
with_standard_json_time_format(true) do
- with_env_tz 'US/Eastern' do
- assert_equal %("2005-02-01T15:15:10.000-05:00"), ActiveSupport::JSON.encode(Time.local(2005,2,1,15,15,10))
+ with_env_tz "US/Eastern" do
+ assert_equal %("2005-02-01T15:15:10.000-05:00"), ActiveSupport::JSON.encode(Time.local(2005, 2, 1, 15, 15, 10))
end
end
end
def test_hash_with_time_to_json
with_standard_json_time_format(false) do
- assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { :time => Time.utc(2009) }.to_json
+ assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { time: Time.utc(2009) }.to_json
end
end
@@ -117,8 +125,8 @@ class TestJSONEncoding < ActiveSupport::TestCase
assert_nothing_raised do
hash = {
"CHI" => {
- :display_name => "chicago",
- :latitude => 123.234
+ display_name: "chicago",
+ latitude: 123.234
}
}
ActiveSupport::JSON.encode(hash)
@@ -127,64 +135,64 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_hash_like_with_options
h = JSONTest::Hashlike.new
- json = h.to_json :only => [:foo]
+ json = h.to_json only: [:foo]
- assert_equal({"foo"=>"hello"}, JSON.parse(json))
+ assert_equal({ "foo" => "hello" }, JSON.parse(json))
end
def test_object_to_json_with_options
obj = Object.new
obj.instance_variable_set :@foo, "hello"
obj.instance_variable_set :@bar, "world"
- json = obj.to_json :only => ["foo"]
+ json = obj.to_json only: ["foo"]
- assert_equal({"foo"=>"hello"}, JSON.parse(json))
+ assert_equal({ "foo" => "hello" }, JSON.parse(json))
end
def test_struct_to_json_with_options
struct = Struct.new(:foo, :bar).new
struct.foo = "hello"
struct.bar = "world"
- json = struct.to_json :only => [:foo]
+ json = struct.to_json only: [:foo]
- assert_equal({"foo"=>"hello"}, JSON.parse(json))
+ assert_equal({ "foo" => "hello" }, JSON.parse(json))
end
def test_hash_should_pass_encoding_options_to_children_in_as_json
person = {
- :name => 'John',
- :address => {
- :city => 'London',
- :country => 'UK'
+ name: "John",
+ address: {
+ city: "London",
+ country: "UK"
}
}
- json = person.as_json :only => [:address, :city]
+ json = person.as_json only: [:address, :city]
- assert_equal({ 'address' => { 'city' => 'London' }}, json)
+ assert_equal({ "address" => { "city" => "London" } }, json)
end
def test_hash_should_pass_encoding_options_to_children_in_to_json
person = {
- :name => 'John',
- :address => {
- :city => 'London',
- :country => 'UK'
+ name: "John",
+ address: {
+ city: "London",
+ country: "UK"
}
}
- json = person.to_json :only => [:address, :city]
+ json = person.to_json only: [:address, :city]
assert_equal(%({"address":{"city":"London"}}), json)
end
def test_array_should_pass_encoding_options_to_children_in_as_json
people = [
- { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
- { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ { name: "John", address: { city: "London", country: "UK" } },
+ { name: "Jean", address: { city: "Paris", country: "France" } }
]
- json = people.as_json :only => [:address, :city]
+ json = people.as_json only: [:address, :city]
expected = [
- { 'address' => { 'city' => 'London' }},
- { 'address' => { 'city' => 'Paris' }}
+ { "address" => { "city" => "London" } },
+ { "address" => { "city" => "Paris" } }
]
assert_equal(expected, json)
@@ -192,20 +200,20 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_array_should_pass_encoding_options_to_children_in_to_json
people = [
- { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
- { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ { name: "John", address: { city: "London", country: "UK" } },
+ { name: "Jean", address: { city: "Paris", country: "France" } }
]
- json = people.to_json :only => [:address, :city]
+ json = people.to_json only: [:address, :city]
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end
People = Class.new(BasicObject) do
include Enumerable
- def initialize()
+ def initialize
@people = [
- { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
- { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ { name: "John", address: { city: "London", country: "UK" } },
+ { name: "Jean", address: { city: "Paris", country: "France" } }
]
end
def each(*, &blk)
@@ -217,32 +225,32 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
def test_enumerable_should_generate_json_with_as_json
- json = People.new.as_json :only => [:address, :city]
+ json = People.new.as_json only: [:address, :city]
expected = [
- { 'address' => { 'city' => 'London' }},
- { 'address' => { 'city' => 'Paris' }}
+ { "address" => { "city" => "London" } },
+ { "address" => { "city" => "Paris" } }
]
assert_equal(expected, json)
end
def test_enumerable_should_generate_json_with_to_json
- json = People.new.to_json :only => [:address, :city]
+ json = People.new.to_json only: [:address, :city]
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end
def test_enumerable_should_pass_encoding_options_to_children_in_as_json
- json = People.new.each.as_json :only => [:address, :city]
+ json = People.new.each.as_json only: [:address, :city]
expected = [
- { 'address' => { 'city' => 'London' }},
- { 'address' => { 'city' => 'Paris' }}
+ { "address" => { "city" => "London" } },
+ { "address" => { "city" => "Paris" } }
]
assert_equal(expected, json)
end
def test_enumerable_should_pass_encoding_options_to_children_in_to_json
- json = People.new.each.to_json :only => [:address, :city]
+ json = People.new.each.to_json only: [:address, :city]
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end
@@ -250,7 +258,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
class CustomWithOptions
attr_accessor :foo, :bar
- def as_json(options={})
+ def as_json(options = {})
options[:only] = %w(foo bar)
super(options)
end
@@ -261,9 +269,9 @@ class TestJSONEncoding < ActiveSupport::TestCase
f.foo = "hello"
f.bar = "world"
- hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
- assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"},
- "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, ActiveSupport::JSON.decode(hash.to_json))
+ hash = { "foo" => f, "other_hash" => { "foo" => "other_foo", "test" => "other_test" } }
+ assert_equal({ "foo" => { "foo" => "hello", "bar" => "world" },
+ "other_hash" => { "foo" => "other_foo", "test" => "other_test" } }, ActiveSupport::JSON.decode(hash.to_json))
end
def test_array_to_json_should_not_keep_options_around
@@ -271,9 +279,9 @@ class TestJSONEncoding < ActiveSupport::TestCase
f.foo = "hello"
f.bar = "world"
- array = [f, {"foo" => "other_foo", "test" => "other_test"}]
- assert_equal([{"foo"=>"hello","bar"=>"world"},
- {"foo"=>"other_foo","test"=>"other_test"}], ActiveSupport::JSON.decode(array.to_json))
+ array = [f, { "foo" => "other_foo", "test" => "other_test" }]
+ assert_equal([{ "foo" => "hello", "bar" => "world" },
+ { "foo" => "other_foo", "test" => "other_test" }], ActiveSupport::JSON.decode(array.to_json))
end
class OptionsTest
@@ -284,7 +292,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_hash_as_json_without_options
json = { foo: OptionsTest.new }.as_json
- assert_equal({"foo" => :default}, json)
+ assert_equal({ "foo" => :default }, json)
end
def test_array_as_json_without_options
@@ -293,13 +301,12 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
def test_struct_encoding
- Struct.new('UserNameAndEmail', :name, :email)
- Struct.new('UserNameAndDate', :name, :date)
- Struct.new('Custom', :name, :sub)
- user_email = Struct::UserNameAndEmail.new 'David', 'sample@example.com'
- user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01)
- custom = Struct::Custom.new 'David', user_birthday
-
+ Struct.new("UserNameAndEmail", :name, :email)
+ Struct.new("UserNameAndDate", :name, :date)
+ Struct.new("Custom", :name, :sub)
+ user_email = Struct::UserNameAndEmail.new "David", "sample@example.com"
+ user_birthday = Struct::UserNameAndDate.new "David", Date.new(2010, 01, 01)
+ custom = Struct::Custom.new "David", user_birthday
json_strings = ""
json_string_and_date = ""
@@ -311,20 +318,20 @@ class TestJSONEncoding < ActiveSupport::TestCase
json_custom = custom.to_json
end
- assert_equal({"name" => "David",
+ assert_equal({ "name" => "David",
"sub" => {
"name" => "David",
- "date" => "2010-01-01" }}, ActiveSupport::JSON.decode(json_custom))
+ "date" => "2010-01-01" } }, ActiveSupport::JSON.decode(json_custom))
- assert_equal({"name" => "David", "email" => "sample@example.com"},
+ assert_equal({ "name" => "David", "email" => "sample@example.com" },
ActiveSupport::JSON.decode(json_strings))
- assert_equal({"name" => "David", "date" => "2010-01-01"},
+ assert_equal({ "name" => "David", "date" => "2010-01-01" },
ActiveSupport::JSON.decode(json_string_and_date))
end
def test_nil_true_and_false_represented_as_themselves
- assert_equal nil, nil.as_json
+ assert_nil nil.as_json
assert_equal true, true.as_json
assert_equal false, false.as_json
end
@@ -336,7 +343,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
super
end
- def as_json(options={})
+ def as_json(options = {})
@as_json_called = true
super
end
@@ -376,7 +383,7 @@ EXPECTED
def test_twz_to_json_with_use_standard_json_time_format_config_set_to_false
with_standard_json_time_format(false) do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
time = ActiveSupport::TimeWithZone.new(Time.utc(2000), zone)
assert_equal "\"1999/12/31 19:00:00 -0500\"", ActiveSupport::JSON.encode(time)
end
@@ -384,7 +391,7 @@ EXPECTED
def test_twz_to_json_with_use_standard_json_time_format_config_set_to_true
with_standard_json_time_format(true) do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
time = ActiveSupport::TimeWithZone.new(Time.utc(2000), zone)
assert_equal "\"1999-12-31T19:00:00.000-05:00\"", ActiveSupport::JSON.encode(time)
end
@@ -393,7 +400,7 @@ EXPECTED
def test_twz_to_json_with_custom_time_precision
with_standard_json_time_format(true) do
with_time_precision(0) do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
time = ActiveSupport::TimeWithZone.new(Time.utc(2000), zone)
assert_equal "\"1999-12-31T19:00:00-05:00\"", ActiveSupport::JSON.encode(time)
end
@@ -417,7 +424,7 @@ EXPECTED
end
def test_twz_to_json_when_wrapping_a_date_time
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
time = ActiveSupport::TimeWithZone.new(DateTime.new(2000), zone)
assert_equal '"1999-12-31T19:00:00.000-05:00"', ActiveSupport::JSON.encode(time)
end
@@ -427,7 +434,31 @@ EXPECTED
assert_equal '"foo"', ActiveSupport::JSON.encode(exception)
end
- protected
+ class InfiniteNumber
+ def as_json(options = nil)
+ { "number" => Float::INFINITY }
+ end
+ end
+
+ def test_to_json_works_when_as_json_returns_infinite_number
+ assert_equal '{"number":null}', InfiniteNumber.new.to_json
+ end
+
+ class NaNNumber
+ def as_json(options = nil)
+ { "number" => Float::NAN }
+ end
+ end
+
+ def test_to_json_works_when_as_json_returns_NaN_number
+ assert_equal '{"number":null}', NaNNumber.new.to_json
+ end
+
+ def test_to_json_works_on_io_objects
+ assert_equal STDOUT.to_s.to_json, STDOUT.to_json
+ end
+
+ private
def object_keys(json_object)
json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort
diff --git a/activesupport/test/json/encoding_test_cases.rb b/activesupport/test/json/encoding_test_cases.rb
index 0159ba8606..5a4700459f 100644
--- a/activesupport/test/json/encoding_test_cases.rb
+++ b/activesupport/test/json/encoding_test_cases.rb
@@ -1,4 +1,10 @@
-require 'bigdecimal'
+# frozen_string_literal: true
+
+require "bigdecimal"
+require "date"
+require "time"
+require "pathname"
+require "uri"
module JSONTest
class Foo
@@ -9,7 +15,7 @@ module JSONTest
class Hashlike
def to_hash
- { :foo => "hello", :bar => "world" }
+ { foo: "hello", bar: "world" }
end
end
@@ -23,7 +29,7 @@ module JSONTest
end
end
- class MyStruct < Struct.new(:name, :value)
+ MyStruct = Struct.new(:name, :value) do
def initialize(*)
@unused = "unused instance variable"
super
@@ -36,23 +42,23 @@ module JSONTest
NilTests = [[ nil, %(null) ]]
NumericTests = [[ 1, %(1) ],
[ 2.5, %(2.5) ],
- [ 0.0/0.0, %(null) ],
- [ 1.0/0.0, %(null) ],
- [ -1.0/0.0, %(null) ],
- [ BigDecimal('0.0')/BigDecimal('0.0'), %(null) ],
- [ BigDecimal('2.5'), %("#{BigDecimal('2.5')}") ]]
+ [ 0.0 / 0.0, %(null) ],
+ [ 1.0 / 0.0, %(null) ],
+ [ -1.0 / 0.0, %(null) ],
+ [ BigDecimal("0.0") / BigDecimal("0.0"), %(null) ],
+ [ BigDecimal("2.5"), %("#{BigDecimal('2.5')}") ]]
- StringTests = [[ 'this is the <string>', %("this is the \\u003cstring\\u003e")],
+ StringTests = [[ "this is the <string>", %("this is the \\u003cstring\\u003e")],
[ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ],
- [ 'http://test.host/posts/1', %("http://test.host/posts/1")],
+ [ "http://test.host/posts/1", %("http://test.host/posts/1")],
[ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\u2028\u2029",
%("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\\u2028\\u2029") ]]
- ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ],
- [ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
+ ArrayTests = [[ ["a", "b", "c"], %([\"a\",\"b\",\"c\"]) ],
+ [ [1, "a", :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
- HashTests = [[ {foo: "bar"}, %({\"foo\":\"bar\"}) ],
- [ {1 => 1, 2 => 'a', 3 => :b, 4 => nil, 5 => false}, %({\"1\":1,\"2\":\"a\",\"3\":\"b\",\"4\":null,\"5\":false}) ]]
+ HashTests = [[ { foo: "bar" }, %({\"foo\":\"bar\"}) ],
+ [ { 1 => 1, 2 => "a", 3 => :b, 4 => nil, 5 => false }, %({\"1\":1,\"2\":\"a\",\"3\":\"b\",\"4\":null,\"5\":false}) ]]
RangeTests = [[ 1..2, %("1..2")],
[ 1...2, %("1...2")],
@@ -67,22 +73,26 @@ module JSONTest
StructTests = [[ MyStruct.new(:foo, "bar"), %({\"name\":\"foo\",\"value\":\"bar\"}) ],
[ MyStruct.new(nil, nil), %({\"name\":null,\"value\":null}) ]]
CustomTests = [[ Custom.new("custom"), '"custom"' ],
- [ Custom.new(nil), 'null' ],
+ [ Custom.new(nil), "null" ],
[ Custom.new(:a), '"a"' ],
[ Custom.new([ :foo, "bar" ]), '["foo","bar"]' ],
- [ Custom.new({ :foo => "hello", :bar => "world" }), '{"bar":"world","foo":"hello"}' ],
+ [ Custom.new(foo: "hello", bar: "world"), '{"bar":"world","foo":"hello"}' ],
[ Custom.new(Hashlike.new), '{"bar":"world","foo":"hello"}' ],
[ Custom.new(Custom.new(Custom.new(:a))), '"a"' ]]
RegexpTests = [[ /^a/, '"(?-mix:^a)"' ], [/^\w{1,2}[a-z]+/ix, '"(?ix-m:^\\\\w{1,2}[a-z]+)"']]
- DateTests = [[ Date.new(2005,2,1), %("2005/02/01") ]]
- TimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
- DateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
+ URITests = [[ URI.parse("http://example.com"), %("http://example.com") ]]
+
+ PathnameTests = [[ Pathname.new("lib/index.rb"), %("lib/index.rb") ]]
+
+ DateTests = [[ Date.new(2005, 2, 1), %("2005/02/01") ]]
+ TimeTests = [[ Time.utc(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]
+ DateTimeTests = [[ DateTime.civil(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]
- StandardDateTests = [[ Date.new(2005,2,1), %("2005-02-01") ]]
- StandardTimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005-02-01T15:15:10.000Z") ]]
- StandardDateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005-02-01T15:15:10.000+00:00") ]]
- StandardStringTests = [[ 'this is the <string>', %("this is the <string>")]]
+ StandardDateTests = [[ Date.new(2005, 2, 1), %("2005-02-01") ]]
+ StandardTimeTests = [[ Time.utc(2005, 2, 1, 15, 15, 10), %("2005-02-01T15:15:10.000Z") ]]
+ StandardDateTimeTests = [[ DateTime.civil(2005, 2, 1, 15, 15, 10), %("2005-02-01T15:15:10.000+00:00") ]]
+ StandardStringTests = [[ "this is the <string>", %("this is the <string>")]]
end
end
diff --git a/activesupport/test/key_generator_test.rb b/activesupport/test/key_generator_test.rb
index f7e8e9a795..a948cfbd8e 100644
--- a/activesupport/test/key_generator_test.rb
+++ b/activesupport/test/key_generator_test.rb
@@ -1,62 +1,79 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
begin
- require 'openssl'
+ require "openssl"
OpenSSL::PKCS5
rescue LoadError, NameError
$stderr.puts "Skipping KeyGenerator test: broken OpenSSL install"
else
-require 'active_support/time'
-require 'active_support/json'
+ require "active_support/time"
+ require "active_support/json"
-class KeyGeneratorTest < ActiveSupport::TestCase
- def setup
- @secret = SecureRandom.hex(64)
- @generator = ActiveSupport::KeyGenerator.new(@secret, :iterations=>2)
- end
+ class KeyGeneratorTest < ActiveSupport::TestCase
+ def setup
+ @secret = SecureRandom.hex(64)
+ @generator = ActiveSupport::KeyGenerator.new(@secret, iterations: 2)
+ end
- test "Generating a key of the default length" do
- derived_key = @generator.generate_key("some_salt")
- assert_kind_of String, derived_key
- assert_equal OpenSSL::Digest::SHA1.new.block_length, derived_key.length, "Should have generated a key of the default size"
- end
+ test "Generating a key of the default length" do
+ derived_key = @generator.generate_key("some_salt")
+ assert_kind_of String, derived_key
+ assert_equal 64, derived_key.length, "Should have generated a key of the default size"
+ end
- test "Generating a key of an alternative length" do
- derived_key = @generator.generate_key("some_salt", 32)
- assert_kind_of String, derived_key
- assert_equal 32, derived_key.length, "Should have generated a key of the right size"
- end
-end
+ test "Generating a key of an alternative length" do
+ derived_key = @generator.generate_key("some_salt", 32)
+ assert_kind_of String, derived_key
+ assert_equal 32, derived_key.length, "Should have generated a key of the right size"
+ end
-class CachingKeyGeneratorTest < ActiveSupport::TestCase
- def setup
- @secret = SecureRandom.hex(64)
- @generator = ActiveSupport::KeyGenerator.new(@secret, :iterations=>2)
- @caching_generator = ActiveSupport::CachingKeyGenerator.new(@generator)
- end
+ test "Expected results" do
+ # For any given set of inputs, this method must continue to return
+ # the same output: if it changes, any existing values relying on a
+ # key would break.
- test "Generating a cached key for same salt and key size" do
- derived_key = @caching_generator.generate_key("some_salt", 32)
- cached_key = @caching_generator.generate_key("some_salt", 32)
+ expected = "b129376f68f1ecae788d7433310249d65ceec090ecacd4c872a3a9e9ec78e055739be5cc6956345d5ae38e7e1daa66f1de587dc8da2bf9e8b965af4b3918a122"
+ assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64).generate_key("some_salt").unpack("H*").first
- assert_equal derived_key, cached_key
- assert_equal derived_key.object_id, cached_key.object_id
+ expected = "b129376f68f1ecae788d7433310249d65ceec090ecacd4c872a3a9e9ec78e055"
+ assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64).generate_key("some_salt", 32).unpack("H*").first
+
+ expected = "cbea7f7f47df705967dc508f4e446fd99e7797b1d70011c6899cd39bbe62907b8508337d678505a7dc8184e037f1003ba3d19fc5d829454668e91d2518692eae"
+ assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64, iterations: 2).generate_key("some_salt").unpack("H*").first
+ end
end
- test "Does not cache key for different salt" do
- derived_key = @caching_generator.generate_key("some_salt", 32)
- different_salt_key = @caching_generator.generate_key("other_salt", 32)
+ class CachingKeyGeneratorTest < ActiveSupport::TestCase
+ def setup
+ @secret = SecureRandom.hex(64)
+ @generator = ActiveSupport::KeyGenerator.new(@secret, iterations: 2)
+ @caching_generator = ActiveSupport::CachingKeyGenerator.new(@generator)
+ end
- assert_not_equal derived_key, different_salt_key
- end
+ test "Generating a cached key for same salt and key size" do
+ derived_key = @caching_generator.generate_key("some_salt", 32)
+ cached_key = @caching_generator.generate_key("some_salt", 32)
+
+ assert_equal derived_key, cached_key
+ assert_equal derived_key.object_id, cached_key.object_id
+ end
- test "Does not cache key for different length" do
- derived_key = @caching_generator.generate_key("some_salt", 32)
- different_length_key = @caching_generator.generate_key("some_salt", 64)
+ test "Does not cache key for different salt" do
+ derived_key = @caching_generator.generate_key("some_salt", 32)
+ different_salt_key = @caching_generator.generate_key("other_salt", 32)
- assert_not_equal derived_key, different_length_key
+ assert_not_equal derived_key, different_salt_key
+ end
+
+ test "Does not cache key for different length" do
+ derived_key = @caching_generator.generate_key("some_salt", 32)
+ different_length_key = @caching_generator.generate_key("some_salt", 64)
+
+ assert_not_equal derived_key, different_length_key
+ end
end
-end
end
diff --git a/activesupport/test/lazy_load_hooks_test.rb b/activesupport/test/lazy_load_hooks_test.rb
index 7851634dbf..721d44d0c1 100644
--- a/activesupport/test/lazy_load_hooks_test.rb
+++ b/activesupport/test/lazy_load_hooks_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class LazyLoadHooksTest < ActiveSupport::TestCase
def test_basic_hook
@@ -18,6 +20,23 @@ class LazyLoadHooksTest < ActiveSupport::TestCase
assert_equal 7, i
end
+ def test_basic_hook_with_two_registrations_only_once
+ i = 0
+ block = proc { i += incr }
+ ActiveSupport.on_load(:basic_hook_with_two_once, run_once: true, &block)
+ ActiveSupport.on_load(:basic_hook_with_two_once) do
+ i += incr
+ end
+
+ ActiveSupport.on_load(:different_hook, run_once: true, &block)
+ ActiveSupport.run_load_hooks(:different_hook, FakeContext.new(2))
+ assert_equal 2, i
+ ActiveSupport.run_load_hooks(:basic_hook_with_two_once, FakeContext.new(2))
+ assert_equal 6, i
+ ActiveSupport.run_load_hooks(:basic_hook_with_two_once, FakeContext.new(5))
+ assert_equal 11, i
+ end
+
def test_hook_registered_after_run
i = 0
ActiveSupport.run_load_hooks(:registered_after)
@@ -35,6 +54,15 @@ class LazyLoadHooksTest < ActiveSupport::TestCase
assert_equal 7, i
end
+ def test_hook_registered_after_run_with_two_registrations_only_once
+ i = 0
+ ActiveSupport.run_load_hooks(:registered_after_with_two_once, FakeContext.new(2))
+ ActiveSupport.run_load_hooks(:registered_after_with_two_once, FakeContext.new(5))
+ assert_equal 0, i
+ ActiveSupport.on_load(:registered_after_with_two_once, run_once: true) { i += incr }
+ assert_equal 2, i
+ end
+
def test_hook_registered_interleaved_run_with_two_registrations
i = 0
ActiveSupport.run_load_hooks(:registered_interleaved_with_two, FakeContext.new(2))
@@ -45,6 +73,22 @@ class LazyLoadHooksTest < ActiveSupport::TestCase
assert_equal 7, i
end
+ def test_hook_registered_interleaved_run_with_two_registrations_once
+ i = 0
+ ActiveSupport
+ .run_load_hooks(:registered_interleaved_with_two_once, FakeContext.new(2))
+ assert_equal 0, i
+
+ ActiveSupport.on_load(:registered_interleaved_with_two_once, run_once: true) do
+ i += incr
+ end
+ assert_equal 2, i
+
+ ActiveSupport
+ .run_load_hooks(:registered_interleaved_with_two_once, FakeContext.new(5))
+ assert_equal 2, i
+ end
+
def test_hook_receives_a_context
i = 0
ActiveSupport.on_load(:contextual) { i += incr }
@@ -63,7 +107,7 @@ class LazyLoadHooksTest < ActiveSupport::TestCase
def test_hook_with_yield_true
i = 0
- ActiveSupport.on_load(:contextual_yield, :yield => true) do |obj|
+ ActiveSupport.on_load(:contextual_yield, yield: true) do |obj|
i += obj.incr + incr_amt
end
assert_equal 0, i
@@ -75,7 +119,7 @@ class LazyLoadHooksTest < ActiveSupport::TestCase
i = 0
ActiveSupport.run_load_hooks(:contextual_yield_after, FakeContext.new(2))
assert_equal 0, i
- ActiveSupport.on_load(:contextual_yield_after, :yield => true) do |obj|
+ ActiveSupport.on_load(:contextual_yield_after, yield: true) do |obj|
i += obj.incr + incr_amt
end
assert_equal 7, i
@@ -93,4 +137,4 @@ private
@incr = incr
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/load_paths_test.rb b/activesupport/test/load_paths_test.rb
deleted file mode 100644
index ac617a9fd8..0000000000
--- a/activesupport/test/load_paths_test.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require 'abstract_unit'
-
-class LoadPathsTest < ActiveSupport::TestCase
- def test_uniq_load_paths
- load_paths_count = $LOAD_PATH.inject({}) { |paths, path|
- expanded_path = File.expand_path(path)
- paths[expanded_path] ||= 0
- paths[expanded_path] += 1
- paths
- }
- load_paths_count[File.expand_path('../../lib', __FILE__)] -= 1
-
- load_paths_count.select! { |k, v| v > 1 }
- assert load_paths_count.empty?, load_paths_count.inspect
- end
-end
diff --git a/activesupport/test/log_subscriber_test.rb b/activesupport/test/log_subscriber_test.rb
index 998a6887c5..2af9b1de30 100644
--- a/activesupport/test/log_subscriber_test.rb
+++ b/activesupport/test/log_subscriber_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/log_subscriber/test_helper'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/log_subscriber/test_helper"
class MyLogSubscriber < ActiveSupport::LogSubscriber
attr_reader :event
@@ -116,7 +118,7 @@ class SyncLogSubscriberTest < ActiveSupport::TestCase
wait
assert_equal 1, @logger.logged(:info).size
- assert_equal 'some_event.my_log_subscriber', @logger.logged(:info).last
+ assert_equal "some_event.my_log_subscriber", @logger.logged(:info).last
assert_equal 1, @logger.logged(:error).size
assert_match 'Could not log "puke.my_log_subscriber" event. RuntimeError: puke', @logger.logged(:error).last
diff --git a/activesupport/test/logger_test.rb b/activesupport/test/logger_test.rb
index 5a91420f1e..5efbd10a7d 100644
--- a/activesupport/test/logger_test.rb
+++ b/activesupport/test/logger_test.rb
@@ -1,9 +1,11 @@
-require 'abstract_unit'
-require 'multibyte_test_helpers'
-require 'stringio'
-require 'fileutils'
-require 'tempfile'
-require 'concurrent/atomics'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "multibyte_test_helpers"
+require "stringio"
+require "fileutils"
+require "tempfile"
+require "concurrent/atomics"
class LoggerTest < ActiveSupport::TestCase
include MultibyteTestHelpers
@@ -26,18 +28,18 @@ class LoggerTest < ActiveSupport::TestCase
end
def test_write_binary_data_to_existing_file
- t = Tempfile.new ['development', 'log']
+ t = Tempfile.new ["development", "log"]
t.binmode
- t.write 'hi mom!'
+ t.write "hi mom!"
t.close
- f = File.open(t.path, 'w')
+ f = File.open(t.path, "w")
f.binmode
logger = Logger.new f
logger.level = Logger::DEBUG
- str = "\x80"
+ str = "\x80".dup
str.force_encoding("ASCII-8BIT")
logger.add Logger::DEBUG, str
@@ -47,15 +49,15 @@ class LoggerTest < ActiveSupport::TestCase
end
def test_write_binary_data_create_file
- fname = File.join Dir.tmpdir, 'lol', 'rofl.log'
+ fname = File.join Dir.tmpdir, "lol", "rofl.log"
FileUtils.mkdir_p File.dirname(fname)
- f = File.open(fname, 'w')
+ f = File.open(fname, "w")
f.binmode
logger = Logger.new f
logger.level = Logger::DEBUG
- str = "\x80"
+ str = "\x80".dup
str.force_encoding("ASCII-8BIT")
logger.add Logger::DEBUG, str
@@ -67,7 +69,7 @@ class LoggerTest < ActiveSupport::TestCase
def test_should_log_debugging_message_when_debugging
@logger.level = Logger::DEBUG
@logger.add(Logger::DEBUG, @message)
- assert @output.string.include?(@message)
+ assert_includes @output.string, @message
end
def test_should_not_log_debug_messages_when_log_level_is_info
@@ -78,32 +80,32 @@ class LoggerTest < ActiveSupport::TestCase
def test_should_add_message_passed_as_block_when_using_add
@logger.level = Logger::INFO
- @logger.add(Logger::INFO) {@message}
- assert @output.string.include?(@message)
+ @logger.add(Logger::INFO) { @message }
+ assert_includes @output.string, @message
end
def test_should_add_message_passed_as_block_when_using_shortcut
@logger.level = Logger::INFO
- @logger.info {@message}
- assert @output.string.include?(@message)
+ @logger.info { @message }
+ assert_includes @output.string, @message
end
def test_should_convert_message_to_string
@logger.level = Logger::INFO
@logger.info @integer_message
- assert @output.string.include?(@integer_message.to_s)
+ assert_includes @output.string, @integer_message.to_s
end
def test_should_convert_message_to_string_when_passed_in_block
@logger.level = Logger::INFO
- @logger.info {@integer_message}
- assert @output.string.include?(@integer_message.to_s)
+ @logger.info { @integer_message }
+ assert_includes @output.string, @integer_message.to_s
end
def test_should_not_evaluate_block_if_message_wont_be_logged
@logger.level = Logger::INFO
evaluated = false
- @logger.add(Logger::DEBUG) {evaluated = true}
+ @logger.add(Logger::DEBUG) { evaluated = true }
assert evaluated == false
end
@@ -115,7 +117,7 @@ class LoggerTest < ActiveSupport::TestCase
def test_should_know_if_its_loglevel_is_below_a_given_level
Logger::Severity.constants.each do |level|
- next if level.to_s == 'UNKNOWN'
+ next if level.to_s == "UNKNOWN"
@logger.level = Logger::Severity.const_get(level) - 1
assert @logger.send("#{level.downcase}?"), "didn't know if it was #{level.downcase}? or below"
end
@@ -125,10 +127,10 @@ class LoggerTest < ActiveSupport::TestCase
@logger.level = Logger::INFO
@logger.info(UNICODE_STRING)
@logger.info(BYTE_STRING)
- assert @output.string.include?(UNICODE_STRING)
+ assert_includes @output.string, UNICODE_STRING
byte_string = @output.string.dup
byte_string.force_encoding("ASCII-8BIT")
- assert byte_string.include?(BYTE_STRING)
+ assert_includes byte_string, BYTE_STRING
end
def test_silencing_everything_but_errors
@@ -138,27 +140,28 @@ class LoggerTest < ActiveSupport::TestCase
end
assert_not @output.string.include?("NOT THERE")
- assert @output.string.include?("THIS IS HERE")
+ assert_includes @output.string, "THIS IS HERE"
end
def test_logger_silencing_works_for_broadcast
another_output = StringIO.new
- another_logger = Logger.new(another_output)
+ another_logger = ActiveSupport::Logger.new(another_output)
- @logger.extend Logger.broadcast(another_logger)
+ @logger.extend ActiveSupport::Logger.broadcast(another_logger)
@logger.debug "CORRECT DEBUG"
- @logger.silence do
+ @logger.silence do |logger|
+ assert_kind_of ActiveSupport::Logger, logger
@logger.debug "FAILURE"
@logger.error "CORRECT ERROR"
end
- assert @output.string.include?("CORRECT DEBUG")
- assert @output.string.include?("CORRECT ERROR")
+ assert_includes @output.string, "CORRECT DEBUG"
+ assert_includes @output.string, "CORRECT ERROR"
assert_not @output.string.include?("FAILURE")
- assert another_output.string.include?("CORRECT DEBUG")
- assert another_output.string.include?("CORRECT ERROR")
+ assert_includes another_output.string, "CORRECT DEBUG"
+ assert_includes another_output.string, "CORRECT ERROR"
assert_not another_output.string.include?("FAILURE")
end
@@ -166,21 +169,22 @@ class LoggerTest < ActiveSupport::TestCase
another_output = StringIO.new
another_logger = ::Logger.new(another_output)
- @logger.extend Logger.broadcast(another_logger)
+ @logger.extend ActiveSupport::Logger.broadcast(another_logger)
@logger.debug "CORRECT DEBUG"
- @logger.silence do
+ @logger.silence do |logger|
+ assert_kind_of ActiveSupport::Logger, logger
@logger.debug "FAILURE"
@logger.error "CORRECT ERROR"
end
- assert @output.string.include?("CORRECT DEBUG")
- assert @output.string.include?("CORRECT ERROR")
+ assert_includes @output.string, "CORRECT DEBUG"
+ assert_includes @output.string, "CORRECT ERROR"
assert_not @output.string.include?("FAILURE")
- assert another_output.string.include?("CORRECT DEBUG")
- assert another_output.string.include?("CORRECT ERROR")
- assert another_output.string.include?("FAILURE")
+ assert_includes another_output.string, "CORRECT DEBUG"
+ assert_includes another_output.string, "CORRECT ERROR"
+ assert_includes another_output.string, "FAILURE"
# We can't silence plain ruby Logger cause with thread safety
# but at least we don't break it
end
diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb
index eb71369397..9edf07f762 100644
--- a/activesupport/test/message_encryptor_test.rb
+++ b/activesupport/test/message_encryptor_test.rb
@@ -1,7 +1,10 @@
-require 'abstract_unit'
-require 'openssl'
-require 'active_support/time'
-require 'active_support/json'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "openssl"
+require "active_support/time"
+require "active_support/json"
+require_relative "metadata/shared_metadata_tests"
class MessageEncryptorTest < ActiveSupport::TestCase
class JSONSerializer
@@ -15,10 +18,10 @@ class MessageEncryptorTest < ActiveSupport::TestCase
end
def setup
- @secret = SecureRandom.hex(64)
- @verifier = ActiveSupport::MessageVerifier.new(@secret, :serializer => ActiveSupport::MessageEncryptor::NullSerializer)
+ @secret = SecureRandom.random_bytes(32)
+ @verifier = ActiveSupport::MessageVerifier.new(@secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
@encryptor = ActiveSupport::MessageEncryptor.new(@secret)
- @data = { :some => "data", :now => Time.local(2010) }
+ @data = { some: "data", now: Time.local(2010) }
end
def test_encrypting_twice_yields_differing_cipher_text
@@ -48,11 +51,21 @@ class MessageEncryptorTest < ActiveSupport::TestCase
assert_equal @data, @encryptor.decrypt_and_verify(message)
end
+ def test_backwards_compat_for_64_bytes_key
+ # 64 bit key
+ secret = ["3942b1bf81e622559ed509e3ff274a780784fe9e75b065866bd270438c74da822219de3156473cc27df1fd590e4baf68c95eeb537b6e4d4c5a10f41635b5597e"].pack("H*")
+ # Encryptor with 32 bit key, 64 bit secret for verifier
+ encryptor = ActiveSupport::MessageEncryptor.new(secret[0..31], secret)
+ # Message generated with 64 bit key
+ message = "eHdGeExnZEwvMSt3U3dKaFl1WFo0TjVvYzA0eGpjbm5WSkt5MXlsNzhpZ0ZnbWhBWFlQZTRwaXE1bVJCS2oxMDZhYVp2dVN3V0lNZUlWQ3c2eVhQbnhnVjFmeVVubmhRKzF3WnZyWHVNMDg9LS1HSisyakJVSFlPb05ISzRMaXRzcFdBPT0=--831a1d54a3cda8a0658dc668a03dedcbce13b5ca"
+ assert_equal "data", encryptor.decrypt_and_verify(message)[:some]
+ end
+
def test_alternative_serialization_method
prev = ActiveSupport.use_standard_json_time_format
ActiveSupport.use_standard_json_time_format = true
- encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64), SecureRandom.hex(64), :serializer => JSONSerializer.new)
- message = encryptor.encrypt_and_sign({ :foo => 123, 'bar' => Time.utc(2010) })
+ encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.random_bytes(32), SecureRandom.random_bytes(128), serializer: JSONSerializer.new)
+ message = encryptor.encrypt_and_sign(:foo => 123, "bar" => Time.utc(2010))
exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00.000Z" }
assert_equal exp, encryptor.decrypt_and_verify(message)
ensure
@@ -61,7 +74,7 @@ class MessageEncryptorTest < ActiveSupport::TestCase
def test_message_obeys_strict_encoding
bad_encoding_characters = "\n!@#"
- message, iv = @encryptor.encrypt_and_sign("This is a very \n\nhumble string"+bad_encoding_characters)
+ message, iv = @encryptor.encrypt_and_sign("This is a very \n\nhumble string" + bad_encoding_characters)
assert_not_decrypted("#{::Base64.encode64 message.to_s}--#{::Base64.encode64 iv.to_s}")
assert_not_verified("#{::Base64.encode64 message.to_s}--#{::Base64.encode64 iv.to_s}")
@@ -70,23 +83,164 @@ class MessageEncryptorTest < ActiveSupport::TestCase
assert_not_verified([iv, message] * bad_encoding_characters)
end
+ def test_aead_mode_encryption
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
+ message = encryptor.encrypt_and_sign(@data)
+ assert_equal @data, encryptor.decrypt_and_verify(message)
+ end
+
+ def test_aead_mode_with_hmac_cbc_cipher_text
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
+
+ assert_aead_not_decrypted(encryptor, "eHdGeExnZEwvMSt3U3dKaFl1WFo0TjVvYzA0eGpjbm5WSkt5MXlsNzhpZ0ZnbWhBWFlQZTRwaXE1bVJCS2oxMDZhYVp2dVN3V0lNZUlWQ3c2eVhQbnhnVjFmeVVubmhRKzF3WnZyWHVNMDg9LS1HSisyakJVSFlPb05ISzRMaXRzcFdBPT0=--831a1d54a3cda8a0658dc668a03dedcbce13b5ca")
+ end
+
+ def test_messing_with_aead_values_causes_failures
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
+ text, iv, auth_tag = encryptor.encrypt_and_sign(@data).split("--")
+ assert_aead_not_decrypted(encryptor, [iv, text, auth_tag] * "--")
+ assert_aead_not_decrypted(encryptor, [munge(text), iv, auth_tag] * "--")
+ assert_aead_not_decrypted(encryptor, [text, munge(iv), auth_tag] * "--")
+ assert_aead_not_decrypted(encryptor, [text, iv, munge(auth_tag)] * "--")
+ assert_aead_not_decrypted(encryptor, [munge(text), munge(iv), munge(auth_tag)] * "--")
+ assert_aead_not_decrypted(encryptor, [text, iv] * "--")
+ assert_aead_not_decrypted(encryptor, [text, iv, auth_tag[0..-2]] * "--")
+ end
+
+ def test_backwards_compatibility_decrypt_previously_encrypted_messages_without_metadata
+ secret = "\xB7\xF0\xBCW\xB1\x18`\xAB\xF0\x81\x10\xA4$\xF44\xEC\xA1\xDC\xC1\xDDD\xAF\xA9\xB8\x14\xCD\x18\x9A\x99 \x80)"
+ encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm")
+ encrypted_message = "9cVnFs2O3lL9SPvIJuxBOLS51nDiBMw=--YNI5HAfHEmZ7VDpl--ddFJ6tXA0iH+XGcCgMINYQ=="
+
+ assert_equal "Ruby on Rails", encryptor.decrypt_and_verify(encrypted_message)
+ end
+
+ def test_rotating_secret
+ old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm").encrypt_and_sign("old")
+
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
+ encryptor.rotate secrets[:old]
+
+ assert_equal "old", encryptor.decrypt_and_verify(old_message)
+ end
+
+ def test_rotating_serializer
+ old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm", serializer: JSON).
+ encrypt_and_sign(ahoy: :hoy)
+
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm", serializer: JSON)
+ encryptor.rotate secrets[:old]
+
+ assert_equal({ "ahoy" => "hoy" }, encryptor.decrypt_and_verify(old_message))
+ end
+
+ def test_rotating_aes_cbc_secrets
+ old_encryptor = ActiveSupport::MessageEncryptor.new(secrets[:old], "old sign", cipher: "aes-256-cbc")
+ old_message = old_encryptor.encrypt_and_sign("old")
+
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret)
+ encryptor.rotate secrets[:old], "old sign", cipher: "aes-256-cbc"
+
+ assert_equal "old", encryptor.decrypt_and_verify(old_message)
+ end
+
+ def test_multiple_rotations
+ older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign("older")
+ old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], "old sign").encrypt_and_sign("old")
+
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret)
+ encryptor.rotate secrets[:old], "old sign"
+ encryptor.rotate secrets[:older], "older sign"
+
+ assert_equal "new", encryptor.decrypt_and_verify(encryptor.encrypt_and_sign("new"))
+ assert_equal "old", encryptor.decrypt_and_verify(old_message)
+ assert_equal "older", encryptor.decrypt_and_verify(older_message)
+ end
+
+ def test_on_rotation_is_called_and_returns_modified_messages
+ older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign(encoded: "message")
+
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret)
+ encryptor.rotate secrets[:old]
+ encryptor.rotate secrets[:older], "older sign"
+
+ rotated = false
+ message = encryptor.decrypt_and_verify(older_message, on_rotation: proc { rotated = true })
+
+ assert_equal({ encoded: "message" }, message)
+ assert rotated
+ end
+
+ def test_with_rotated_metadata
+ old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm").
+ encrypt_and_sign("metadata", purpose: :rotation)
+
+ encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
+ encryptor.rotate secrets[:old]
+
+ assert_equal "metadata", encryptor.decrypt_and_verify(old_message, purpose: :rotation)
+ end
+
private
+ def assert_aead_not_decrypted(encryptor, value)
+ assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
+ encryptor.decrypt_and_verify(value)
+ end
+ end
- def assert_not_decrypted(value)
- assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
- @encryptor.decrypt_and_verify(@verifier.generate(value))
+ def assert_not_decrypted(value)
+ assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
+ @encryptor.decrypt_and_verify(@verifier.generate(value))
+ end
end
- end
- def assert_not_verified(value)
- assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
- @encryptor.decrypt_and_verify(value)
+ def assert_not_verified(value)
+ assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @encryptor.decrypt_and_verify(value)
+ end
end
- end
- def munge(base64_string)
- bits = ::Base64.strict_decode64(base64_string)
- bits.reverse!
- ::Base64.strict_encode64(bits)
+ def secrets
+ @secrets ||= Hash.new { |h, k| h[k] = SecureRandom.random_bytes(32) }
+ end
+
+ def munge(base64_string)
+ bits = ::Base64.strict_decode64(base64_string)
+ bits.reverse!
+ ::Base64.strict_encode64(bits)
+ end
+end
+
+class MessageEncryptorMetadataTest < ActiveSupport::TestCase
+ include SharedMessageMetadataTests
+
+ setup do
+ @secret = SecureRandom.random_bytes(32)
+ @encryptor = ActiveSupport::MessageEncryptor.new(@secret, encryptor_options)
end
+
+ private
+ def generate(message, **options)
+ @encryptor.encrypt_and_sign(message, options)
+ end
+
+ def parse(data, **options)
+ @encryptor.decrypt_and_verify(data, options)
+ end
+
+ def encryptor_options; end
+end
+
+class MessageEncryptorMetadataMarshalTest < MessageEncryptorMetadataTest
+ private
+ def encryptor_options
+ { serializer: Marshal }
+ end
+end
+
+class MessageEncryptorMetadataJSONTest < MessageEncryptorMetadataTest
+ private
+ def encryptor_options
+ { serializer: MessageEncryptorTest::JSONSerializer.new }
+ end
end
diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb
index 668d78492e..05d5c1cbc3 100644
--- a/activesupport/test/message_verifier_test.rb
+++ b/activesupport/test/message_verifier_test.rb
@@ -1,10 +1,12 @@
-require 'abstract_unit'
-require 'openssl'
-require 'active_support/time'
-require 'active_support/json'
+# frozen_string_literal: true
-class MessageVerifierTest < ActiveSupport::TestCase
+require "abstract_unit"
+require "openssl"
+require "active_support/time"
+require "active_support/json"
+require_relative "metadata/shared_metadata_tests"
+class MessageVerifierTest < ActiveSupport::TestCase
class JSONSerializer
def dump(value)
ActiveSupport::JSON.encode(value)
@@ -17,7 +19,8 @@ class MessageVerifierTest < ActiveSupport::TestCase
def setup
@verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!")
- @data = { :some => "data", :now => Time.local(2010) }
+ @data = { some: "data", now: Time.utc(2010) }
+ @secret = SecureRandom.random_bytes(32)
end
def test_valid_message
@@ -49,8 +52,8 @@ class MessageVerifierTest < ActiveSupport::TestCase
def test_alternative_serialization_method
prev = ActiveSupport.use_standard_json_time_format
ActiveSupport.use_standard_json_time_format = true
- verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!", :serializer => JSONSerializer.new)
- message = verifier.generate({ :foo => 123, 'bar' => Time.utc(2010) })
+ verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!", serializer: JSONSerializer.new)
+ message = verifier.generate(:foo => 123, "bar" => Time.utc(2010))
exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00.000Z" }
assert_equal exp, verifier.verified(message)
assert_equal exp, verifier.verify(message)
@@ -81,6 +84,121 @@ class MessageVerifierTest < ActiveSupport::TestCase
exception = assert_raise(ArgumentError) do
ActiveSupport::MessageVerifier.new(nil)
end
- assert_equal exception.message, 'Secret should not be nil.'
+ assert_equal "Secret should not be nil.", exception.message
+ end
+
+ def test_backward_compatibility_messages_signed_without_metadata
+ signed_message = "BAh7BzoJc29tZUkiCWRhdGEGOgZFVDoIbm93SXU6CVRpbWUNIIAbgAAAAAAHOgtvZmZzZXRpADoJem9uZUkiCFVUQwY7BkY=--d03c52c91dfe4ccc5159417c660461bcce005e96"
+ assert_equal @data, @verifier.verify(signed_message)
+ end
+
+ def test_rotating_secret
+ old_message = ActiveSupport::MessageVerifier.new("old", digest: "SHA1").generate("old")
+
+ verifier = ActiveSupport::MessageVerifier.new(@secret, digest: "SHA1")
+ verifier.rotate "old"
+
+ assert_equal "old", verifier.verified(old_message)
end
+
+ def test_multiple_rotations
+ old_message = ActiveSupport::MessageVerifier.new("old", digest: "SHA256").generate("old")
+ older_message = ActiveSupport::MessageVerifier.new("older", digest: "SHA1").generate("older")
+
+ verifier = ActiveSupport::MessageVerifier.new(@secret, digest: "SHA512")
+ verifier.rotate "old", digest: "SHA256"
+ verifier.rotate "older", digest: "SHA1"
+
+ assert_equal "new", verifier.verified(verifier.generate("new"))
+ assert_equal "old", verifier.verified(old_message)
+ assert_equal "older", verifier.verified(older_message)
+ end
+
+ def test_on_rotation_is_called_and_verified_returns_message
+ older_message = ActiveSupport::MessageVerifier.new("older", digest: "SHA1").generate(encoded: "message")
+
+ verifier = ActiveSupport::MessageVerifier.new(@secret, digest: "SHA512")
+ verifier.rotate "old", digest: "SHA256"
+ verifier.rotate "older", digest: "SHA1"
+
+ rotated = false
+ message = verifier.verified(older_message, on_rotation: proc { rotated = true })
+
+ assert_equal({ encoded: "message" }, message)
+ assert rotated
+ end
+
+ def test_rotations_with_metadata
+ old_message = ActiveSupport::MessageVerifier.new("old").generate("old", purpose: :rotation)
+
+ verifier = ActiveSupport::MessageVerifier.new(@secret)
+ verifier.rotate "old"
+
+ assert_equal "old", verifier.verified(old_message, purpose: :rotation)
+ end
+end
+
+class MessageVerifierMetadataTest < ActiveSupport::TestCase
+ include SharedMessageMetadataTests
+
+ setup do
+ @verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!", verifier_options)
+ end
+
+ def test_verify_raises_when_purpose_differs
+ assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @verifier.verify(generate(data, purpose: "payment"), purpose: "shipping")
+ end
+ end
+
+ def test_verify_raises_when_expired
+ signed_message = generate(data, expires_in: 1.month)
+
+ travel 2.months
+ assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @verifier.verify(signed_message)
+ end
+ end
+
+ private
+ def generate(message, **options)
+ @verifier.generate(message, options)
+ end
+
+ def parse(message, **options)
+ @verifier.verified(message, options)
+ end
+
+ def verifier_options
+ Hash.new
+ end
+end
+
+class MessageVerifierMetadataMarshalTest < MessageVerifierMetadataTest
+ private
+ def verifier_options
+ { serializer: Marshal }
+ end
+end
+
+class MessageVerifierMetadataJSONTest < MessageVerifierMetadataTest
+ private
+ def verifier_options
+ { serializer: MessageVerifierTest::JSONSerializer.new }
+ end
+end
+
+class MessageEncryptorMetadataNullSerializerTest < MessageVerifierMetadataTest
+ private
+ def data
+ "string message"
+ end
+
+ def null_serializing?
+ true
+ end
+
+ def verifier_options
+ { serializer: ActiveSupport::MessageEncryptor::NullSerializer }
+ end
end
diff --git a/activesupport/test/messages/rotation_configuration_test.rb b/activesupport/test/messages/rotation_configuration_test.rb
new file mode 100644
index 0000000000..2f6824ed21
--- /dev/null
+++ b/activesupport/test/messages/rotation_configuration_test.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/messages/rotation_configuration"
+
+class MessagesRotationConfiguration < ActiveSupport::TestCase
+ def setup
+ @config = ActiveSupport::Messages::RotationConfiguration.new
+ end
+
+ def test_signed_configurations
+ @config.rotate :signed, "older secret", salt: "salt", digest: "SHA1"
+ @config.rotate :signed, "old secret", salt: "salt", digest: "SHA256"
+
+ assert_equal [
+ [ "older secret", salt: "salt", digest: "SHA1" ],
+ [ "old secret", salt: "salt", digest: "SHA256" ] ], @config.signed
+ end
+
+ def test_encrypted_configurations
+ @config.rotate :encrypted, "old raw key", cipher: "aes-256-gcm"
+
+ assert_equal [ [ "old raw key", cipher: "aes-256-gcm" ] ], @config.encrypted
+ end
+end
diff --git a/activesupport/test/metadata/shared_metadata_tests.rb b/activesupport/test/metadata/shared_metadata_tests.rb
new file mode 100644
index 0000000000..08bb0c648e
--- /dev/null
+++ b/activesupport/test/metadata/shared_metadata_tests.rb
@@ -0,0 +1,93 @@
+# frozen_string_literal: true
+
+module SharedMessageMetadataTests
+ def teardown
+ travel_back
+ super
+ end
+
+ def null_serializing?
+ false
+ end
+
+ def test_encryption_and_decryption_with_same_purpose
+ assert_equal data, parse(generate(data, purpose: "checkout"), purpose: "checkout")
+ assert_equal data, parse(generate(data))
+
+ string_message = "address: #23, main street"
+ assert_equal string_message, parse(generate(string_message, purpose: "shipping"), purpose: "shipping")
+ end
+
+ def test_verifies_array_when_purpose_matches
+ unless null_serializing?
+ data = [ "credit_card_no: 5012-6748-9087-5678", { "card_holder" => "Donald", "issued_on" => Time.local(2017) }, 12345 ]
+ assert_equal data, parse(generate(data, purpose: :registration), purpose: :registration)
+ end
+ end
+
+ def test_encryption_and_decryption_with_different_purposes_returns_nil
+ assert_nil parse(generate(data, purpose: "payment"), purpose: "sign up")
+ assert_nil parse(generate(data, purpose: "payment"))
+ assert_nil parse(generate(data), purpose: "sign up")
+ end
+
+ def test_purpose_using_symbols
+ assert_equal data, parse(generate(data, purpose: :checkout), purpose: :checkout)
+ assert_equal data, parse(generate(data, purpose: :checkout), purpose: "checkout")
+ assert_equal data, parse(generate(data, purpose: "checkout"), purpose: :checkout)
+ end
+
+ def test_passing_expires_at_sets_expiration_date
+ encrypted_message = generate(data, expires_at: 1.hour.from_now)
+
+ travel 59.minutes
+ assert_equal data, parse(encrypted_message)
+
+ travel 2.minutes
+ assert_nil parse(encrypted_message)
+ end
+
+ def test_set_relative_expiration_date_by_passing_expires_in
+ encrypted_message = generate(data, expires_in: 2.hours)
+
+ travel 1.hour
+ assert_equal data, parse(encrypted_message)
+
+ travel 1.hour + 1.second
+ assert_nil parse(encrypted_message)
+ end
+
+ def test_passing_expires_in_less_than_a_second_is_not_expired
+ freeze_time do
+ encrypted_message = generate(data, expires_in: 1.second)
+
+ travel 0.5.seconds
+ assert_equal data, parse(encrypted_message)
+
+ travel 1.second
+ assert_nil parse(encrypted_message)
+ end
+ end
+
+ def test_favor_expires_at_over_expires_in
+ payment_related_message = generate(data, purpose: "payment", expires_at: 2.year.from_now, expires_in: 1.second)
+
+ travel 1.year
+ assert_equal data, parse(payment_related_message, purpose: :payment)
+
+ travel 1.year + 1.day
+ assert_nil parse(payment_related_message, purpose: "payment")
+ end
+
+ def test_skip_expires_at_and_expires_in_to_disable_expiration_check
+ payment_related_message = generate(data, purpose: "payment")
+
+ travel 100.years
+ assert_equal data, parse(payment_related_message, purpose: "payment")
+ end
+
+ private
+ def data
+ { "credit_card_no" => "5012-6784-9087-5678", "card_holder" => { "name" => "Donald" } }
+ end
+end
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
index c1e0b19248..f51fbe2671 100644
--- a/activesupport/test/multibyte_chars_test.rb
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'multibyte_test_helpers'
-require 'active_support/core_ext/string/multibyte'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "multibyte_test_helpers"
+require "active_support/core_ext/string/multibyte"
class MultibyteCharsTest < ActiveSupport::TestCase
include MultibyteTestHelpers
@@ -16,7 +18,7 @@ class MultibyteCharsTest < ActiveSupport::TestCase
end
def test_should_allow_method_calls_to_string
- @chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing; 'result'; end }
+ @chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing; "result"; end }
assert_nothing_raised do
@chars.__method_for_multibyte_testing
@@ -27,14 +29,14 @@ class MultibyteCharsTest < ActiveSupport::TestCase
end
def test_forwarded_method_calls_should_return_new_chars_instance
- @chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing; 'result'; end }
+ @chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing; "result"; end }
assert_kind_of @proxy_class, @chars.__method_for_multibyte_testing
assert_not_equal @chars.object_id, @chars.__method_for_multibyte_testing.object_id
end
def test_forwarded_bang_method_calls_should_return_the_original_chars_instance_when_result_is_not_nil
- @chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing!; 'result'; end }
+ @chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing!; "result"; end }
assert_kind_of @proxy_class, @chars.__method_for_multibyte_testing!
assert_equal @chars.object_id, @chars.__method_for_multibyte_testing!.object_id
@@ -50,8 +52,8 @@ class MultibyteCharsTest < ActiveSupport::TestCase
assert_equal BYTE_STRING.length, BYTE_STRING.mb_chars.length
end
- def test_forwarded_method_with_non_string_result_should_be_returned_vertabim
- str = ''
+ def test_forwarded_method_with_non_string_result_should_be_returned_verbatim
+ str = "".dup
str.singleton_class.class_eval { def __method_for_multibyte_testing_with_integer_result; 1; end }
@chars.wrapped_string.singleton_class.class_eval { def __method_for_multibyte_testing_with_integer_result; 1; end }
@@ -59,15 +61,15 @@ class MultibyteCharsTest < ActiveSupport::TestCase
end
def test_should_concatenate
- mb_a = 'a'.mb_chars
- mb_b = 'b'.mb_chars
- assert_equal 'ab', mb_a + 'b'
- assert_equal 'ab', 'a' + mb_b
- assert_equal 'ab', mb_a + mb_b
+ mb_a = "a".dup.mb_chars
+ mb_b = "b".dup.mb_chars
+ assert_equal "ab", mb_a + "b"
+ assert_equal "ab", "a" + mb_b
+ assert_equal "ab", mb_a + mb_b
- assert_equal 'ab', mb_a << 'b'
- assert_equal 'ab', 'a' << mb_b
- assert_equal 'abb', mb_a << mb_b
+ assert_equal "ab", mb_a << "b"
+ assert_equal "ab", "a".dup << mb_b
+ assert_equal "abb", mb_a << mb_b
end
def test_consumes_utf8_strings
@@ -77,8 +79,8 @@ class MultibyteCharsTest < ActiveSupport::TestCase
end
def test_concatenation_should_return_a_proxy_class_instance
- assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars + 'b').class
- assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars << 'b').class
+ assert_equal ActiveSupport::Multibyte.proxy_class, ("a".mb_chars + "b").class
+ assert_equal ActiveSupport::Multibyte.proxy_class, ("a".dup.mb_chars << "b").class
end
def test_ascii_strings_are_treated_at_utf8_strings
@@ -86,10 +88,10 @@ class MultibyteCharsTest < ActiveSupport::TestCase
end
def test_concatenate_should_return_proxy_instance
- assert(('a'.mb_chars + 'b').kind_of?(@proxy_class))
- assert(('a'.mb_chars + 'b'.mb_chars).kind_of?(@proxy_class))
- assert(('a'.mb_chars << 'b').kind_of?(@proxy_class))
- assert(('a'.mb_chars << 'b'.mb_chars).kind_of?(@proxy_class))
+ assert(("a".mb_chars + "b").kind_of?(@proxy_class))
+ assert(("a".mb_chars + "b".mb_chars).kind_of?(@proxy_class))
+ assert(("a".dup.mb_chars << "b").kind_of?(@proxy_class))
+ assert(("a".dup.mb_chars << "b".mb_chars).kind_of?(@proxy_class))
end
def test_should_return_string_as_json
@@ -115,12 +117,12 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
%w{capitalize downcase lstrip reverse rstrip swapcase upcase}.each do |method|
class_eval(<<-EOTESTS, __FILE__, __LINE__ + 1)
def test_#{method}_bang_should_return_self_when_modifying_wrapped_string
- chars = ' él piDió Un bUen café '
+ chars = ' él piDió Un bUen café '.dup
assert_equal chars.object_id, chars.send("#{method}!").object_id
end
def test_#{method}_bang_should_change_wrapped_string
- original = ' él piDió Un bUen café '
+ original = ' él piDió Un bUen café '.dup
proxy = chars(original.dup)
proxy.send("#{method}!")
assert_not_equal original, proxy.to_s
@@ -133,7 +135,7 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_tidy_bytes_bang_should_change_wrapped_string
- original = " Un bUen café \x92"
+ original = " Un bUen café \x92".dup
proxy = chars(original.dup)
proxy.tidy_bytes!
assert_not_equal original, proxy.to_s
@@ -150,24 +152,24 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_string_methods_are_chainable
- assert chars('').insert(0, '').kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').rjust(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').ljust(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').center(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').rstrip.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').lstrip.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').strip.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').reverse.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars(' ').slice(0).kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').limit(0).kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').upcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').downcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').capitalize.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').normalize.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').decompose.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').compose.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').tidy_bytes.kind_of?(ActiveSupport::Multibyte.proxy_class)
- assert chars('').swapcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("".dup).insert(0, "").kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").rjust(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").ljust(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").center(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").rstrip.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").lstrip.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").strip.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").reverse.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars(" ").slice(0).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").limit(0).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").upcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").downcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").capitalize.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").normalize.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").decompose.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").compose.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").tidy_bytes.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars("").swapcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
end
def test_should_be_equal_to_the_wrapped_string
@@ -176,8 +178,8 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_should_not_be_equal_to_an_other_string
- assert_not_equal @chars, 'other'
- assert_not_equal 'other', @chars
+ assert_not_equal @chars, "other"
+ assert_not_equal "other", @chars
end
def test_sortability
@@ -195,29 +197,29 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_should_use_character_offsets_for_insert_offsets
- assert_equal '', ''.mb_chars.insert(0, '')
- assert_equal 'こわにちわ', @chars.insert(1, 'わ')
- assert_equal 'こわわわにちわ', @chars.insert(2, 'わわ')
- assert_equal 'わこわわわにちわ', @chars.insert(0, 'わ')
- assert_equal 'わこわわわにちわ', @chars.wrapped_string
+ assert_equal "", "".dup.mb_chars.insert(0, "")
+ assert_equal "こわにちわ", @chars.insert(1, "わ")
+ assert_equal "こわわわにちわ", @chars.insert(2, "わわ")
+ assert_equal "わこわわわにちわ", @chars.insert(0, "わ")
+ assert_equal "わこわわわにちわ", @chars.wrapped_string
end
def test_insert_should_be_destructive
- @chars.insert(1, 'わ')
- assert_equal 'こわにちわ', @chars
+ @chars.insert(1, "わ")
+ assert_equal "こわにちわ", @chars
end
def test_insert_throws_index_error
- assert_raise(IndexError) { @chars.insert(-12, 'わ')}
- assert_raise(IndexError) { @chars.insert(12, 'わ') }
+ assert_raise(IndexError) { @chars.insert(-12, "わ") }
+ assert_raise(IndexError) { @chars.insert(12, "わ") }
end
def test_should_know_if_one_includes_the_other
- assert @chars.include?('')
- assert @chars.include?('ち')
- assert @chars.include?('わ')
- assert !@chars.include?('こちわ')
- assert !@chars.include?('a')
+ assert_includes @chars, ""
+ assert_includes @chars, "ち"
+ assert_includes @chars, "わ"
+ assert_not_includes @chars, "こちわ"
+ assert_not_includes @chars, "a"
end
def test_include_raises_when_nil_is_passed
@@ -227,62 +229,62 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_index_should_return_character_offset
- assert_nil @chars.index('u')
- assert_equal 0, @chars.index('こに')
- assert_equal 2, @chars.index('ち')
- assert_equal 2, @chars.index('ち', -2)
- assert_equal nil, @chars.index('ち', -1)
- assert_equal 3, @chars.index('わ')
- assert_equal 5, 'ééxééx'.mb_chars.index('x', 4)
+ assert_nil @chars.index("u")
+ assert_equal 0, @chars.index("こに")
+ assert_equal 2, @chars.index("ち")
+ assert_equal 2, @chars.index("ち", -2)
+ assert_nil @chars.index("ち", -1)
+ assert_equal 3, @chars.index("わ")
+ assert_equal 5, "ééxééx".mb_chars.index("x", 4)
end
def test_rindex_should_return_character_offset
- assert_nil @chars.rindex('u')
- assert_equal 1, @chars.rindex('に')
- assert_equal 2, @chars.rindex('ち', -2)
- assert_nil @chars.rindex('ち', -3)
- assert_equal 6, 'Café périferôl'.mb_chars.rindex('é')
- assert_equal 13, 'Café périferôl'.mb_chars.rindex(/\w/u)
+ assert_nil @chars.rindex("u")
+ assert_equal 1, @chars.rindex("に")
+ assert_equal 2, @chars.rindex("ち", -2)
+ assert_nil @chars.rindex("ち", -3)
+ assert_equal 6, "Café périferôl".mb_chars.rindex("é")
+ assert_equal 13, "Café périferôl".mb_chars.rindex(/\w/u)
end
def test_indexed_insert_should_take_character_offsets
- @chars[2] = 'a'
- assert_equal 'こにaわ', @chars
- @chars[2] = 'ηη'
- assert_equal 'こにηηわ', @chars
- @chars[3, 2] = 'λλλ'
- assert_equal 'こにηλλλ', @chars
+ @chars[2] = "a"
+ assert_equal "こにaわ", @chars
+ @chars[2] = "ηη"
+ assert_equal "こにηηわ", @chars
+ @chars[3, 2] = "λλλ"
+ assert_equal "こにηλλλ", @chars
@chars[1, 0] = "λ"
- assert_equal 'こλにηλλλ', @chars
+ assert_equal "こλにηλλλ", @chars
@chars[4..6] = "ηη"
- assert_equal 'こλにηηη', @chars
+ assert_equal "こλにηηη", @chars
@chars[/ηη/] = "λλλ"
- assert_equal 'こλにλλλη', @chars
+ assert_equal "こλにλλλη", @chars
@chars[/(λλ)(.)/, 2] = "α"
- assert_equal 'こλにλλαη', @chars
+ assert_equal "こλにλλαη", @chars
@chars["α"] = "¢"
- assert_equal 'こλにλλ¢η', @chars
+ assert_equal "こλにλλ¢η", @chars
@chars["λλ"] = "ααα"
- assert_equal 'こλにααα¢η', @chars
+ assert_equal "こλにααα¢η", @chars
end
def test_indexed_insert_should_raise_on_index_overflow
before = @chars.to_s
- assert_raise(IndexError) { @chars[10] = 'a' }
- assert_raise(IndexError) { @chars[10, 4] = 'a' }
- assert_raise(IndexError) { @chars[/ii/] = 'a' }
- assert_raise(IndexError) { @chars[/()/, 10] = 'a' }
+ assert_raise(IndexError) { @chars[10] = "a" }
+ assert_raise(IndexError) { @chars[10, 4] = "a" }
+ assert_raise(IndexError) { @chars[/ii/] = "a" }
+ assert_raise(IndexError) { @chars[/()/, 10] = "a" }
assert_equal before, @chars
end
def test_indexed_insert_should_raise_on_range_overflow
before = @chars.to_s
- assert_raise(RangeError) { @chars[10..12] = 'a' }
+ assert_raise(RangeError) { @chars[10..12] = "a" }
assert_equal before, @chars
end
def test_rjust_should_raise_argument_errors_on_bad_arguments
- assert_raise(ArgumentError) { @chars.rjust(10, '') }
+ assert_raise(ArgumentError) { @chars.rjust(10, "") }
assert_raise(ArgumentError) { @chars.rjust }
end
@@ -292,15 +294,15 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
assert_equal UNICODE_STRING, @chars.rjust(4)
assert_equal " #{UNICODE_STRING}", @chars.rjust(5)
assert_equal " #{UNICODE_STRING}", @chars.rjust(7)
- assert_equal "---#{UNICODE_STRING}", @chars.rjust(7, '-')
- assert_equal "ααα#{UNICODE_STRING}", @chars.rjust(7, 'α')
- assert_equal "aba#{UNICODE_STRING}", @chars.rjust(7, 'ab')
- assert_equal "αηα#{UNICODE_STRING}", @chars.rjust(7, 'αη')
- assert_equal "αηαη#{UNICODE_STRING}", @chars.rjust(8, 'αη')
+ assert_equal "---#{UNICODE_STRING}", @chars.rjust(7, "-")
+ assert_equal "ααα#{UNICODE_STRING}", @chars.rjust(7, "α")
+ assert_equal "aba#{UNICODE_STRING}", @chars.rjust(7, "ab")
+ assert_equal "αηα#{UNICODE_STRING}", @chars.rjust(7, "αη")
+ assert_equal "αηαη#{UNICODE_STRING}", @chars.rjust(8, "αη")
end
def test_ljust_should_raise_argument_errors_on_bad_arguments
- assert_raise(ArgumentError) { @chars.ljust(10, '') }
+ assert_raise(ArgumentError) { @chars.ljust(10, "") }
assert_raise(ArgumentError) { @chars.ljust }
end
@@ -310,15 +312,15 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
assert_equal UNICODE_STRING, @chars.ljust(4)
assert_equal "#{UNICODE_STRING} ", @chars.ljust(5)
assert_equal "#{UNICODE_STRING} ", @chars.ljust(7)
- assert_equal "#{UNICODE_STRING}---", @chars.ljust(7, '-')
- assert_equal "#{UNICODE_STRING}ααα", @chars.ljust(7, 'α')
- assert_equal "#{UNICODE_STRING}aba", @chars.ljust(7, 'ab')
- assert_equal "#{UNICODE_STRING}αηα", @chars.ljust(7, 'αη')
- assert_equal "#{UNICODE_STRING}αηαη", @chars.ljust(8, 'αη')
+ assert_equal "#{UNICODE_STRING}---", @chars.ljust(7, "-")
+ assert_equal "#{UNICODE_STRING}ααα", @chars.ljust(7, "α")
+ assert_equal "#{UNICODE_STRING}aba", @chars.ljust(7, "ab")
+ assert_equal "#{UNICODE_STRING}αηα", @chars.ljust(7, "αη")
+ assert_equal "#{UNICODE_STRING}αηαη", @chars.ljust(8, "αη")
end
def test_center_should_raise_argument_errors_on_bad_arguments
- assert_raise(ArgumentError) { @chars.center(10, '') }
+ assert_raise(ArgumentError) { @chars.center(10, "") }
assert_raise(ArgumentError) { @chars.center }
end
@@ -329,15 +331,15 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
assert_equal "#{UNICODE_STRING} ", @chars.center(5)
assert_equal " #{UNICODE_STRING} ", @chars.center(6)
assert_equal " #{UNICODE_STRING} ", @chars.center(7)
- assert_equal "--#{UNICODE_STRING}--", @chars.center(8, '-')
- assert_equal "--#{UNICODE_STRING}---", @chars.center(9, '-')
- assert_equal "αα#{UNICODE_STRING}αα", @chars.center(8, 'α')
- assert_equal "αα#{UNICODE_STRING}ααα", @chars.center(9, 'α')
- assert_equal "a#{UNICODE_STRING}ab", @chars.center(7, 'ab')
- assert_equal "ab#{UNICODE_STRING}ab", @chars.center(8, 'ab')
- assert_equal "abab#{UNICODE_STRING}abab", @chars.center(12, 'ab')
- assert_equal "α#{UNICODE_STRING}αη", @chars.center(7, 'αη')
- assert_equal "αη#{UNICODE_STRING}αη", @chars.center(8, 'αη')
+ assert_equal "--#{UNICODE_STRING}--", @chars.center(8, "-")
+ assert_equal "--#{UNICODE_STRING}---", @chars.center(9, "-")
+ assert_equal "αα#{UNICODE_STRING}αα", @chars.center(8, "α")
+ assert_equal "αα#{UNICODE_STRING}ααα", @chars.center(9, "α")
+ assert_equal "a#{UNICODE_STRING}ab", @chars.center(7, "ab")
+ assert_equal "ab#{UNICODE_STRING}ab", @chars.center(8, "ab")
+ assert_equal "abab#{UNICODE_STRING}abab", @chars.center(12, "ab")
+ assert_equal "α#{UNICODE_STRING}αη", @chars.center(7, "αη")
+ assert_equal "αη#{UNICODE_STRING}αη", @chars.center(8, "αη")
end
def test_lstrip_strips_whitespace_from_the_left_of_the_string
@@ -367,20 +369,20 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_size_returns_characters_instead_of_bytes
- assert_equal 0, ''.mb_chars.size
+ assert_equal 0, "".mb_chars.size
assert_equal 4, @chars.size
assert_equal 4, @chars.length
assert_equal 5, ASCII_STRING.mb_chars.size
end
def test_reverse_reverses_characters
- assert_equal '', ''.mb_chars.reverse
- assert_equal 'わちにこ', @chars.reverse
+ assert_equal "", "".mb_chars.reverse
+ assert_equal "わちにこ", @chars.reverse
end
def test_reverse_should_work_with_normalized_strings
- str = 'bös'
- reversed_str = 'söb'
+ str = "bös"
+ reversed_str = "söb"
assert_equal chars(reversed_str).normalize(:kc), chars(str).normalize(:kc).reverse
assert_equal chars(reversed_str).normalize(:c), chars(str).normalize(:c).reverse
assert_equal chars(reversed_str).normalize(:d), chars(str).normalize(:d).reverse
@@ -390,45 +392,45 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_slice_should_take_character_offsets
- assert_equal nil, ''.mb_chars.slice(0)
- assert_equal 'こ', @chars.slice(0)
- assert_equal 'わ', @chars.slice(3)
- assert_equal nil, ''.mb_chars.slice(-1..1)
- assert_equal nil, ''.mb_chars.slice(-1, 1)
- assert_equal '', ''.mb_chars.slice(0..10)
- assert_equal 'にちわ', @chars.slice(1..3)
- assert_equal 'にちわ', @chars.slice(1, 3)
- assert_equal 'こ', @chars.slice(0, 1)
- assert_equal 'ちわ', @chars.slice(2..10)
- assert_equal '', @chars.slice(4..10)
- assert_equal 'に', @chars.slice(/に/u)
- assert_equal 'にち', @chars.slice(/に./u)
- assert_equal nil, @chars.slice(/unknown/u)
- assert_equal 'にち', @chars.slice(/(にち)/u, 1)
- assert_equal nil, @chars.slice(/(にち)/u, 2)
- assert_equal nil, @chars.slice(7..6)
+ assert_nil "".mb_chars.slice(0)
+ assert_equal "こ", @chars.slice(0)
+ assert_equal "わ", @chars.slice(3)
+ assert_nil "".mb_chars.slice(-1..1)
+ assert_nil "".mb_chars.slice(-1, 1)
+ assert_equal "", "".mb_chars.slice(0..10)
+ assert_equal "にちわ", @chars.slice(1..3)
+ assert_equal "にちわ", @chars.slice(1, 3)
+ assert_equal "こ", @chars.slice(0, 1)
+ assert_equal "ちわ", @chars.slice(2..10)
+ assert_equal "", @chars.slice(4..10)
+ assert_equal "に", @chars.slice(/に/u)
+ assert_equal "にち", @chars.slice(/に./u)
+ assert_nil @chars.slice(/unknown/u)
+ assert_equal "にち", @chars.slice(/(にち)/u, 1)
+ assert_nil @chars.slice(/(にち)/u, 2)
+ assert_nil @chars.slice(7..6)
end
def test_slice_bang_returns_sliced_out_substring
- assert_equal 'にち', @chars.slice!(1..2)
+ assert_equal "にち", @chars.slice!(1..2)
end
def test_slice_bang_returns_nil_on_out_of_bound_arguments
- assert_equal nil, @chars.mb_chars.slice!(9..10)
+ assert_nil @chars.mb_chars.slice!(9..10)
end
def test_slice_bang_removes_the_slice_from_the_receiver
- chars = 'úüù'.mb_chars
- chars.slice!(0,2)
- assert_equal 'ù', chars
+ chars = "úüù".dup.mb_chars
+ chars.slice!(0, 2)
+ assert_equal "ù", chars
end
def test_slice_bang_returns_nil_and_does_not_modify_receiver_if_out_of_bounds
- string = 'úüù'
+ string = "úüù".dup
chars = string.mb_chars
assert_nil chars.slice!(4, 5)
- assert_equal 'úüù', chars
- assert_equal 'úüù', string
+ assert_equal "úüù", chars
+ assert_equal "úüù", string
end
def test_slice_should_throw_exceptions_on_invalid_arguments
@@ -442,48 +444,48 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_upcase_should_upcase_ascii_characters
- assert_equal '', ''.mb_chars.upcase
- assert_equal 'ABC', 'aBc'.mb_chars.upcase
+ assert_equal "", "".mb_chars.upcase
+ assert_equal "ABC", "aBc".mb_chars.upcase
end
def test_downcase_should_downcase_ascii_characters
- assert_equal '', ''.mb_chars.downcase
- assert_equal 'abc', 'aBc'.mb_chars.downcase
+ assert_equal "", "".mb_chars.downcase
+ assert_equal "abc", "aBc".mb_chars.downcase
end
def test_swapcase_should_swap_ascii_characters
- assert_equal '', ''.mb_chars.swapcase
- assert_equal 'AbC', 'aBc'.mb_chars.swapcase
+ assert_equal "", "".mb_chars.swapcase
+ assert_equal "AbC", "aBc".mb_chars.swapcase
end
def test_capitalize_should_work_on_ascii_characters
- assert_equal '', ''.mb_chars.capitalize
- assert_equal 'Abc', 'abc'.mb_chars.capitalize
+ assert_equal "", "".mb_chars.capitalize
+ assert_equal "Abc", "abc".mb_chars.capitalize
end
def test_titleize_should_work_on_ascii_characters
- assert_equal '', ''.mb_chars.titleize
- assert_equal 'Abc Abc', 'abc abc'.mb_chars.titleize
+ assert_equal "", "".mb_chars.titleize
+ assert_equal "Abc Abc", "abc abc".mb_chars.titleize
end
def test_respond_to_knows_which_methods_the_proxy_responds_to
- assert ''.mb_chars.respond_to?(:slice) # Defined on Chars
- assert ''.mb_chars.respond_to?(:capitalize!) # Defined on Chars
- assert ''.mb_chars.respond_to?(:gsub) # Defined on String
- assert !''.mb_chars.respond_to?(:undefined_method) # Not defined
+ assert "".mb_chars.respond_to?(:slice) # Defined on Chars
+ assert "".mb_chars.respond_to?(:capitalize!) # Defined on Chars
+ assert "".mb_chars.respond_to?(:gsub) # Defined on String
+ assert !"".mb_chars.respond_to?(:undefined_method) # Not defined
end
def test_method_works_for_proxyed_methods
- assert_equal 'll', 'hello'.mb_chars.method(:slice).call(2..3) # Defined on Chars
- chars = 'hello'.mb_chars
- assert_equal 'Hello', chars.method(:capitalize!).call # Defined on Chars
- assert_equal 'Hello', chars
- assert_equal 'jello', 'hello'.mb_chars.method(:gsub).call(/h/, 'j') # Defined on String
- assert_raise(NameError){ ''.mb_chars.method(:undefined_method) } # Not defined
+ assert_equal "ll", "hello".mb_chars.method(:slice).call(2..3) # Defined on Chars
+ chars = "hello".mb_chars
+ assert_equal "Hello", chars.method(:capitalize!).call # Defined on Chars
+ assert_equal "Hello", chars
+ assert_equal "jello", "hello".mb_chars.method(:gsub).call(/h/, "j") # Defined on String
+ assert_raise(NameError) { "".mb_chars.method(:undefined_method) } # Not defined
end
def test_acts_like_string
- assert 'Bambi'.mb_chars.acts_like_string?
+ assert "Bambi".mb_chars.acts_like_string?
end
end
@@ -495,25 +497,25 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
def test_upcase_should_be_unicode_aware
assert_equal "АБВГД\0F", chars("аБвгд\0f").upcase
- assert_equal 'こにちわ', chars('こにちわ').upcase
+ assert_equal "こにちわ", chars("こにちわ").upcase
end
def test_downcase_should_be_unicode_aware
assert_equal "абвгд\0f", chars("аБвгд\0F").downcase
- assert_equal 'こにちわ', chars('こにちわ').downcase
+ assert_equal "こにちわ", chars("こにちわ").downcase
end
def test_swapcase_should_be_unicode_aware
assert_equal "аaéÜ\0f", chars("АAÉü\0F").swapcase
- assert_equal 'こにちわ', chars('こにちわ').swapcase
+ assert_equal "こにちわ", chars("こにちわ").swapcase
end
def test_capitalize_should_be_unicode_aware
- { 'аБвг аБвг' => 'Абвг абвг',
- 'аБвг АБВГ' => 'Абвг абвг',
- 'АБВГ АБВГ' => 'Абвг абвг',
- '' => '' }.each do |f,t|
- assert_equal t, chars(f).capitalize
+ { "аБвг аБвг" => "Абвг абвг",
+ "аБвг АБВГ" => "Абвг абвг",
+ "АБВГ АБВГ" => "Абвг абвг",
+ "" => "" }.each do |f, t|
+ assert_equal t, chars(f).capitalize
end
end
@@ -527,7 +529,7 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
end
def test_limit_should_not_break_on_blank_strings
- example = chars('')
+ example = chars("")
assert_equal example, example.limit(0)
assert_equal example, example.limit(1)
end
@@ -537,23 +539,23 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
bytesize = UNICODE_STRING.bytesize
assert_equal UNICODE_STRING, example.limit(bytesize)
- assert_equal '', example.limit(0)
- assert_equal '', example.limit(1)
- assert_equal 'こ', example.limit(3)
- assert_equal 'こに', example.limit(6)
- assert_equal 'こに', example.limit(8)
- assert_equal 'こにち', example.limit(9)
- assert_equal 'こにちわ', example.limit(50)
+ assert_equal "", example.limit(0)
+ assert_equal "", example.limit(1)
+ assert_equal "こ", example.limit(3)
+ assert_equal "こに", example.limit(6)
+ assert_equal "こに", example.limit(8)
+ assert_equal "こにち", example.limit(9)
+ assert_equal "こにちわ", example.limit(50)
end
def test_limit_should_work_on_an_ascii_string
ascii = chars(ASCII_STRING)
assert_equal ASCII_STRING, ascii.limit(ASCII_STRING.length)
- assert_equal '', ascii.limit(0)
- assert_equal 'o', ascii.limit(1)
- assert_equal 'oh', ascii.limit(2)
- assert_equal 'ohay', ascii.limit(4)
- assert_equal 'ohayo', ascii.limit(50)
+ assert_equal "", ascii.limit(0)
+ assert_equal "o", ascii.limit(1)
+ assert_equal "oh", ascii.limit(2)
+ assert_equal "ohay", ascii.limit(4)
+ assert_equal "ohayo", ascii.limit(50)
end
def test_limit_should_keep_under_the_specified_byte_limit
@@ -565,7 +567,7 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
def test_composition_exclusion_is_set_up_properly
# Normalization of DEVANAGARI LETTER QA breaks when composition exclusion isn't used correctly
- qa = [0x915, 0x93c].pack('U*')
+ qa = [0x915, 0x93c].pack("U*")
assert_equal qa, chars(qa).normalize(:c)
end
@@ -575,7 +577,7 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
[
[0x0B47, 0x0300, 0x0B3E],
[0x1100, 0x0300, 0x1161]
- ].map { |c| c.pack('U*') }.each do |c|
+ ].map { |c| c.pack("U*") }.each do |c|
assert_equal_codepoints c, chars(c).normalize(:c)
end
end
@@ -599,19 +601,19 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
323 # COMBINING DOT BELOW
].pack("U*")
- assert_equal_codepoints '', chars('').normalize
- assert_equal_codepoints [44,105,106,328,323].pack("U*"), chars(comp_str).normalize(:kc).to_s
- assert_equal_codepoints [44,307,328,323].pack("U*"), chars(comp_str).normalize(:c).to_s
- assert_equal_codepoints [44,307,110,780,78,769].pack("U*"), chars(comp_str).normalize(:d).to_s
- assert_equal_codepoints [44,105,106,110,780,78,769].pack("U*"), chars(comp_str).normalize(:kd).to_s
+ assert_equal_codepoints "", chars("").normalize
+ assert_equal_codepoints [44, 105, 106, 328, 323].pack("U*"), chars(comp_str).normalize(:kc).to_s
+ assert_equal_codepoints [44, 307, 328, 323].pack("U*"), chars(comp_str).normalize(:c).to_s
+ assert_equal_codepoints [44, 307, 110, 780, 78, 769].pack("U*"), chars(comp_str).normalize(:d).to_s
+ assert_equal_codepoints [44, 105, 106, 110, 780, 78, 769].pack("U*"), chars(comp_str).normalize(:kd).to_s
end
def test_should_compute_grapheme_length
[
- ['', 0],
- ['abc', 3],
- ['こにちわ', 4],
- [[0x0924, 0x094D, 0x0930].pack('U*'), 2],
+ ["", 0],
+ ["abc", 3],
+ ["こにちわ", 4],
+ [[0x0924, 0x094D, 0x0930].pack("U*"), 2],
# GB3
[%w(cr lf), 1],
# GB4
@@ -664,7 +666,6 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
end
def test_tidy_bytes_should_tidy_bytes
-
single_byte_cases = {
"\x21" => "!", # Valid ASCII byte, low
"\x41" => "A", # Valid ASCII byte, mid
@@ -699,9 +700,9 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
end
byte_string = "\270\236\010\210\245"
- tidy_string = [0xb8, 0x17e, 0x8, 0x2c6, 0xa5].pack('U*')
+ tidy_string = [0xb8, 0x17e, 0x8, 0x2c6, 0xa5].pack("U*")
assert_equal_codepoints tidy_string, chars(byte_string).tidy_bytes
- assert_nothing_raised { chars(byte_string).tidy_bytes.to_s.unpack('U*') }
+ assert_nothing_raised { chars(byte_string).tidy_bytes.to_s.unpack("U*") }
# UTF-8 leading byte followed by too few continuation bytes
assert_equal_codepoints "\xc3\xb0\xc2\xa5\xc2\xa4\x21", chars("\xf0\xa5\xa4\x21").tidy_bytes
@@ -720,16 +721,16 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase
private
- def string_from_classes(classes)
- # Characters from the character classes as described in UAX #29
- character_from_class = {
- :l => 0x1100, :v => 0x1160, :t => 0x11A8, :lv => 0xAC00, :lvt => 0xAC01, :cr => 0x000D, :lf => 0x000A,
- :extend => 0x094D, :n => 0x64, :spacingmark => 0x0903, :r => 0x1F1E6, :control => 0x0001
- }
- classes.collect do |k|
- character_from_class[k.intern]
- end.pack('U*')
- end
+ def string_from_classes(classes)
+ # Characters from the character classes as described in UAX #29
+ character_from_class = {
+ l: 0x1100, v: 0x1160, t: 0x11A8, lv: 0xAC00, lvt: 0xAC01, cr: 0x000D, lf: 0x000A,
+ extend: 0x094D, n: 0x64, spacingmark: 0x0903, r: 0x1F1E6, control: 0x0001
+ }
+ classes.collect do |k|
+ character_from_class[k.intern]
+ end.pack("U*")
+ end
end
class MultibyteInternalsTest < ActiveSupport::TestCase
diff --git a/activesupport/test/multibyte_conformance_test.rb b/activesupport/test/multibyte_conformance_test.rb
index 9fca47a985..748e8d16e1 100644
--- a/activesupport/test/multibyte_conformance_test.rb
+++ b/activesupport/test/multibyte_conformance_test.rb
@@ -1,34 +1,16 @@
-require 'abstract_unit'
-require 'multibyte_test_helpers'
+# frozen_string_literal: true
-require 'fileutils'
-require 'open-uri'
-require 'tmpdir'
+require "abstract_unit"
+require "multibyte_test_helpers"
-class MultibyteConformanceTest < ActiveSupport::TestCase
- class Downloader
- def self.download(from, to)
- unless File.exist?(to)
- unless File.exist?(File.dirname(to))
- system "mkdir -p #{File.dirname(to)}"
- end
- open(from) do |source|
- File.open(to, 'w') do |target|
- source.each_line do |l|
- target.write l
- end
- end
- end
- end
- true
- end
- end
+require "fileutils"
+require "open-uri"
+require "tmpdir"
+class MultibyteConformanceTest < ActiveSupport::TestCase
include MultibyteTestHelpers
- UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
- UNIDATA_FILE = '/NormalizationTest.txt'
- CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
+ UNIDATA_FILE = "/NormalizationTest.txt"
FileUtils.mkdir_p(CACHE_DIR)
RUN_P = begin
Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
@@ -102,19 +84,19 @@ class MultibyteConformanceTest < ActiveSupport::TestCase
end
end
- protected
+ private
def each_line_of_norm_tests(&block)
- File.open(File.join(CACHE_DIR, UNIDATA_FILE), 'r') do | f |
+ File.open(File.join(CACHE_DIR, UNIDATA_FILE), "r") do | f |
until f.eof?
line = f.gets.chomp!
- next if (line.empty? || line =~ /^\#/)
+ next if line.empty? || line.start_with?("#")
cols, comment = line.split("#")
cols = cols.split(";").map(&:strip).reject(&:empty?)
next unless cols.length == 5
# codepoints are in hex in the test suite, pack wants them as integers
- cols.map!{|c| c.split.map{|codepoint| codepoint.to_i(16)}.pack("U*") }
+ cols.map! { |c| c.split.map { |codepoint| codepoint.to_i(16) }.pack("U*") }
cols << comment
yield(*cols)
@@ -123,6 +105,6 @@ class MultibyteConformanceTest < ActiveSupport::TestCase
end
def inspect_codepoints(str)
- str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ')
+ str.to_s.unpack("U*").map { |cp| cp.to_s(16) }.join(" ")
end
end
diff --git a/activesupport/test/multibyte_grapheme_break_conformance_test.rb b/activesupport/test/multibyte_grapheme_break_conformance_test.rb
index 6e2f02abed..fac74cd80f 100644
--- a/activesupport/test/multibyte_grapheme_break_conformance_test.rb
+++ b/activesupport/test/multibyte_grapheme_break_conformance_test.rb
@@ -1,37 +1,23 @@
-# encoding: utf-8
+# frozen_string_literal: true
-require 'abstract_unit'
+require "abstract_unit"
+require "multibyte_test_helpers"
-require 'fileutils'
-require 'open-uri'
-require 'tmpdir'
+require "fileutils"
+require "open-uri"
+require "tmpdir"
class MultibyteGraphemeBreakConformanceTest < ActiveSupport::TestCase
- class Downloader
- def self.download(from, to)
- unless File.exist?(to)
- $stderr.puts "Downloading #{from} to #{to}"
- unless File.exist?(File.dirname(to))
- system "mkdir -p #{File.dirname(to)}"
- end
- open(from) do |source|
- File.open(to, 'w') do |target|
- source.each_line do |l|
- target.write l
- end
- end
- end
- end
- end
- end
+ include MultibyteTestHelpers
- TEST_DATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd/auxiliary"
- TEST_DATA_FILE = '/GraphemeBreakTest.txt'
- CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
+ UNIDATA_FILE = "/auxiliary/GraphemeBreakTest.txt"
+ RUN_P = begin
+ Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
+ rescue
+ end
def setup
- FileUtils.mkdir_p(CACHE_DIR)
- Downloader.download(TEST_DATA_URL + TEST_DATA_FILE, CACHE_DIR + TEST_DATA_FILE)
+ skip "Unable to download test data" unless RUN_P
end
def test_breaks
@@ -42,24 +28,24 @@ class MultibyteGraphemeBreakConformanceTest < ActiveSupport::TestCase
end
end
- protected
+ private
def each_line_of_break_tests(&block)
lines = 0
max_test_lines = 0 # Don't limit below 21, because that's the header of the testfile
- File.open(File.join(CACHE_DIR, TEST_DATA_FILE), 'r') do | f |
- until f.eof? || (max_test_lines > 21 and lines > max_test_lines)
+ File.open(File.join(CACHE_DIR, UNIDATA_FILE), "r") do | f |
+ until f.eof? || (max_test_lines > 21 && lines > max_test_lines)
lines += 1
line = f.gets.chomp!
- next if (line.empty? || line =~ /^\#/)
+ next if line.empty? || line.start_with?("#")
cols, comment = line.split("#")
# Cluster breaks are represented by ÷
- clusters = cols.split("÷").map{|e| e.strip}.reject{|e| e.empty? }
+ clusters = cols.split("÷").map { |e| e.strip }.reject { |e| e.empty? }
clusters = clusters.map do |cluster|
# Codepoints within each cluster are separated by ×
- codepoints = cluster.split("×").map{|e| e.strip}.reject{|e| e.empty? }
+ codepoints = cluster.split("×").map { |e| e.strip }.reject { |e| e.empty? }
# codepoints are in hex in the test suite, pack wants them as integers
- codepoints.map{|codepoint| codepoint.to_i(16)}
+ codepoints.map { |codepoint| codepoint.to_i(16) }
end
# The tests contain a solitary U+D800 <Non Private Use High
diff --git a/activesupport/test/multibyte_normalization_conformance_test.rb b/activesupport/test/multibyte_normalization_conformance_test.rb
index 0d31c9520f..1173a94e81 100644
--- a/activesupport/test/multibyte_normalization_conformance_test.rb
+++ b/activesupport/test/multibyte_normalization_conformance_test.rb
@@ -1,41 +1,24 @@
-# encoding: utf-8
+# frozen_string_literal: true
-require 'abstract_unit'
-require 'multibyte_test_helpers'
+require "abstract_unit"
+require "multibyte_test_helpers"
-require 'fileutils'
-require 'open-uri'
-require 'tmpdir'
+require "fileutils"
+require "open-uri"
+require "tmpdir"
class MultibyteNormalizationConformanceTest < ActiveSupport::TestCase
- class Downloader
- def self.download(from, to)
- unless File.exist?(to)
- $stderr.puts "Downloading #{from} to #{to}"
- unless File.exist?(File.dirname(to))
- system "mkdir -p #{File.dirname(to)}"
- end
- open(from) do |source|
- File.open(to, 'w') do |target|
- source.each_line do |l|
- target.write l
- end
- end
- end
- end
- end
- end
-
include MultibyteTestHelpers
- UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
- UNIDATA_FILE = '/NormalizationTest.txt'
- CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
+ UNIDATA_FILE = "/NormalizationTest.txt"
+ RUN_P = begin
+ Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
+ rescue
+ end
def setup
- FileUtils.mkdir_p(CACHE_DIR)
- Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
@proxy = ActiveSupport::Multibyte::Chars
+ skip "Unable to download test data" unless RUN_P
end
def test_normalizations_C
@@ -100,22 +83,22 @@ class MultibyteNormalizationConformanceTest < ActiveSupport::TestCase
end
end
- protected
+ private
def each_line_of_norm_tests(&block)
lines = 0
max_test_lines = 0 # Don't limit below 38, because that's the header of the testfile
- File.open(File.join(CACHE_DIR, UNIDATA_FILE), 'r') do | f |
- until f.eof? || (max_test_lines > 38 and lines > max_test_lines)
+ File.open(File.join(CACHE_DIR, UNIDATA_FILE), "r") do | f |
+ until f.eof? || (max_test_lines > 38 && lines > max_test_lines)
lines += 1
line = f.gets.chomp!
- next if (line.empty? || line =~ /^\#/)
+ next if line.empty? || line.start_with?("#")
cols, comment = line.split("#")
- cols = cols.split(";").map{|e| e.strip}.reject{|e| e.empty? }
+ cols = cols.split(";").map { |e| e.strip }.reject { |e| e.empty? }
next unless cols.length == 5
# codepoints are in hex in the test suite, pack wants them as integers
- cols.map!{|c| c.split.map{|codepoint| codepoint.to_i(16)}.pack("U*") }
+ cols.map! { |c| c.split.map { |codepoint| codepoint.to_i(16) }.pack("U*") }
cols << comment
yield(*cols)
@@ -124,6 +107,6 @@ class MultibyteNormalizationConformanceTest < ActiveSupport::TestCase
end
def inspect_codepoints(str)
- str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ')
+ str.to_s.unpack("U*").map { |cp| cp.to_s(16) }.join(" ")
end
end
diff --git a/activesupport/test/multibyte_proxy_test.rb b/activesupport/test/multibyte_proxy_test.rb
index 360cf57302..ecedab2569 100644
--- a/activesupport/test/multibyte_proxy_test.rb
+++ b/activesupport/test/multibyte_proxy_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class MultibyteProxyText < ActiveSupport::TestCase
class AsciiOnlyEncoder
@@ -6,7 +8,7 @@ class MultibyteProxyText < ActiveSupport::TestCase
alias to_s wrapped_string
def initialize(string)
- @wrapped_string = string.gsub(/[^\u0000-\u007F]/, '?')
+ @wrapped_string = string.gsub(/[^\u0000-\u007F]/, "?")
end
end
diff --git a/activesupport/test/multibyte_test_helpers.rb b/activesupport/test/multibyte_test_helpers.rb
index 58cf5488cd..f7cf993100 100644
--- a/activesupport/test/multibyte_test_helpers.rb
+++ b/activesupport/test/multibyte_test_helpers.rb
@@ -1,17 +1,41 @@
+# frozen_string_literal: true
+
module MultibyteTestHelpers
- UNICODE_STRING = 'こにちわ'.freeze
- ASCII_STRING = 'ohayo'.freeze
- BYTE_STRING = "\270\236\010\210\245".force_encoding("ASCII-8BIT").freeze
+ class Downloader
+ def self.download(from, to)
+ unless File.exist?(to)
+ unless File.exist?(File.dirname(to))
+ system "mkdir -p #{File.dirname(to)}"
+ end
+ open(from) do |source|
+ File.open(to, "w") do |target|
+ source.each_line do |l|
+ target.write l
+ end
+ end
+ end
+ end
+ true
+ end
+ end
+
+ UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
+ CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}"
+ FileUtils.mkdir_p(CACHE_DIR)
+
+ UNICODE_STRING = "こにちわ".freeze
+ ASCII_STRING = "ohayo".freeze
+ BYTE_STRING = "\270\236\010\210\245".dup.force_encoding("ASCII-8BIT").freeze
def chars(str)
ActiveSupport::Multibyte::Chars.new(str)
end
def inspect_codepoints(str)
- str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ')
+ str.to_s.unpack("U*").map { |cp| cp.to_s(16) }.join(" ")
end
- def assert_equal_codepoints(expected, actual, message=nil)
+ def assert_equal_codepoints(expected, actual, message = nil)
assert_equal(inspect_codepoints(expected), inspect_codepoints(actual), message)
end
end
diff --git a/activesupport/test/multibyte_unicode_database_test.rb b/activesupport/test/multibyte_unicode_database_test.rb
index dd33641ec2..540a34493d 100644
--- a/activesupport/test/multibyte_unicode_database_test.rb
+++ b/activesupport/test/multibyte_unicode_database_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+require "abstract_unit"
class MultibyteUnicodeDatabaseTest < ActiveSupport::TestCase
-
include ActiveSupport::Multibyte::Unicode
def setup
diff --git a/activesupport/test/notifications/evented_notification_test.rb b/activesupport/test/notifications/evented_notification_test.rb
index f690ad43fc..4beb8194b9 100644
--- a/activesupport/test/notifications/evented_notification_test.rb
+++ b/activesupport/test/notifications/evented_notification_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
module ActiveSupport
module Notifications
@@ -7,7 +9,7 @@ module ActiveSupport
attr_reader :events
def initialize
- @events = []
+ @events = []
end
def start(name, id, payload)
@@ -28,26 +30,26 @@ module ActiveSupport
def test_evented_listener
notifier = Fanout.new
listener = Listener.new
- notifier.subscribe 'hi', listener
- notifier.start 'hi', 1, {}
- notifier.start 'hi', 2, {}
- notifier.finish 'hi', 2, {}
- notifier.finish 'hi', 1, {}
+ notifier.subscribe "hi", listener
+ notifier.start "hi", 1, {}
+ notifier.start "hi", 2, {}
+ notifier.finish "hi", 2, {}
+ notifier.finish "hi", 1, {}
assert_equal 4, listener.events.length
assert_equal [
- [:start, 'hi', 1, {}],
- [:start, 'hi', 2, {}],
- [:finish, 'hi', 2, {}],
- [:finish, 'hi', 1, {}],
+ [:start, "hi", 1, {}],
+ [:start, "hi", 2, {}],
+ [:finish, "hi", 2, {}],
+ [:finish, "hi", 1, {}],
], listener.events
end
def test_evented_listener_no_events
notifier = Fanout.new
listener = Listener.new
- notifier.subscribe 'hi', listener
- notifier.start 'world', 1, {}
+ notifier.subscribe "hi", listener
+ notifier.start "world", 1, {}
assert_equal 0, listener.events.length
end
@@ -55,31 +57,31 @@ module ActiveSupport
notifier = Fanout.new
listener = Listener.new
notifier.subscribe nil, listener
- notifier.start 'hello', 1, {}
- notifier.start 'world', 1, {}
- notifier.finish 'world', 1, {}
- notifier.finish 'hello', 1, {}
+ notifier.start "hello", 1, {}
+ notifier.start "world", 1, {}
+ notifier.finish "world", 1, {}
+ notifier.finish "hello", 1, {}
assert_equal 4, listener.events.length
assert_equal [
- [:start, 'hello', 1, {}],
- [:start, 'world', 1, {}],
- [:finish, 'world', 1, {}],
- [:finish, 'hello', 1, {}],
+ [:start, "hello", 1, {}],
+ [:start, "world", 1, {}],
+ [:finish, "world", 1, {}],
+ [:finish, "hello", 1, {}],
], listener.events
end
def test_evented_listener_priority
notifier = Fanout.new
listener = ListenerWithTimedSupport.new
- notifier.subscribe 'hi', listener
+ notifier.subscribe "hi", listener
- notifier.start 'hi', 1, {}
- notifier.finish 'hi', 1, {}
+ notifier.start "hi", 1, {}
+ notifier.finish "hi", 1, {}
assert_equal [
- [:start, 'hi', 1, {}],
- [:finish, 'hi', 1, {}]
+ [:start, "hi", 1, {}],
+ [:finish, "hi", 1, {}]
], listener.events
end
end
diff --git a/activesupport/test/notifications/instrumenter_test.rb b/activesupport/test/notifications/instrumenter_test.rb
index f46e96f636..1d76c91d30 100644
--- a/activesupport/test/notifications/instrumenter_test.rb
+++ b/activesupport/test/notifications/instrumenter_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/notifications/instrumenter'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/notifications/instrumenter"
module ActiveSupport
module Notifications
@@ -22,11 +24,11 @@ module ActiveSupport
super
@notifier = TestNotifier.new
@instrumenter = Instrumenter.new @notifier
- @payload = { :foo => Object.new }
+ @payload = { foo: Object.new }
end
def test_instrument
- called = false
+ called = false
instrumenter.instrument("foo", payload) {
called = true
}
@@ -39,7 +41,7 @@ module ActiveSupport
assert_equal 1, notifier.finishes.size
name, _, payload = notifier.finishes.first
assert_equal "awesome", name
- assert_equal Hash[:result => 2], payload
+ assert_equal Hash[result: 2], payload
end
def test_start
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index 1cb17e6197..5cfbd60131 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/delegation'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/module/delegation"
module Notifications
class TestCase < ActiveSupport::TestCase
@@ -31,7 +33,7 @@ module Notifications
expected = [name, name]
events = []
- callback = lambda {|*_| events << _.first}
+ callback = lambda { |*_| events << _.first }
ActiveSupport::Notifications.subscribed(callback, name) do
ActiveSupport::Notifications.instrument(name)
ActiveSupport::Notifications.instrument(name2)
@@ -49,10 +51,10 @@ module Notifications
old_notifier = ActiveSupport::Notifications.notifier
ActiveSupport::Notifications.notifier = ActiveSupport::Notifications::Fanout.new
- ActiveSupport::Notifications.subscribe('foo', TestSubscriber.new)
+ ActiveSupport::Notifications.subscribe("foo", TestSubscriber.new)
- ActiveSupport::Notifications.instrument('foo') do
- ActiveSupport::Notifications.subscribe('foo') {}
+ ActiveSupport::Notifications.instrument("foo") do
+ ActiveSupport::Notifications.subscribe("foo") {}
end
ensure
ActiveSupport::Notifications.notifier = old_notifier
@@ -141,26 +143,26 @@ module Notifications
def test_log_subscriber_with_string
events = []
- @notifier.subscribe('1') { |*args| events << args }
+ @notifier.subscribe("1") { |*args| events << args }
- @notifier.publish '1'
- @notifier.publish '1.a'
- @notifier.publish 'a.1'
+ @notifier.publish "1"
+ @notifier.publish "1.a"
+ @notifier.publish "a.1"
@notifier.wait
- assert_equal [['1']], events
+ assert_equal [["1"]], events
end
def test_log_subscriber_with_pattern
events = []
@notifier.subscribe(/\d/) { |*args| events << args }
- @notifier.publish '1'
- @notifier.publish 'a.1'
- @notifier.publish '1.a'
+ @notifier.publish "1"
+ @notifier.publish "a.1"
+ @notifier.publish "1.a"
@notifier.wait
- assert_equal [['1'], ['a.1'], ['1.a']], events
+ assert_equal [["1"], ["a.1"], ["1.a"]], events
end
def test_multiple_log_subscribers
@@ -188,7 +190,7 @@ module Notifications
end
class InstrumentationTest < TestCase
- delegate :instrument, :to => ActiveSupport::Notifications
+ delegate :instrument, to: ActiveSupport::Notifications
def test_instrument_returns_block_result
assert_equal 2, instrument(:awesome) { 1 + 1 }
@@ -198,7 +200,7 @@ module Notifications
assert_equal 2, instrument(:awesome) { |p| p[:result] = 1 + 1 }
assert_equal 1, @events.size
assert_equal :awesome, @events.first.name
- assert_equal Hash[:result => 2], @events.first.payload
+ assert_equal Hash[result: 2], @events.first.payload
end
def test_instrumenter_exposes_its_id
@@ -206,24 +208,24 @@ module Notifications
end
def test_nested_events_can_be_instrumented
- instrument(:awesome, :payload => "notifications") do
- instrument(:wot, :payload => "child") do
+ instrument(:awesome, payload: "notifications") do
+ instrument(:wot, payload: "child") do
1 + 1
end
assert_equal 1, @events.size
assert_equal :wot, @events.first.name
- assert_equal Hash[:payload => "child"], @events.first.payload
+ assert_equal Hash[payload: "child"], @events.first.payload
end
assert_equal 2, @events.size
assert_equal :awesome, @events.last.name
- assert_equal Hash[:payload => "notifications"], @events.last.payload
+ assert_equal Hash[payload: "notifications"], @events.last.payload
end
def test_instrument_publishes_when_exception_is_raised
begin
- instrument(:awesome, :payload => "notifications") do
+ instrument(:awesome, payload: "notifications") do
raise "FAIL"
end
rescue RuntimeError => e
@@ -231,15 +233,15 @@ module Notifications
end
assert_equal 1, @events.size
- assert_equal Hash[:payload => "notifications",
- :exception => ["RuntimeError", "FAIL"], :exception_object => e], @events.last.payload
+ assert_equal Hash[payload: "notifications",
+ exception: ["RuntimeError", "FAIL"], exception_object: e], @events.last.payload
end
def test_event_is_pushed_even_without_block
- instrument(:awesome, :payload => "notifications")
+ instrument(:awesome, payload: "notifications")
assert_equal 1, @events.size
assert_equal :awesome, @events.last.name
- assert_equal Hash[:payload => "notifications"], @events.last.payload
+ assert_equal Hash[payload: "notifications"], @events.last.payload
end
end
@@ -254,8 +256,8 @@ module Notifications
end
def test_events_consumes_information_given_as_payload
- event = event(:foo, Time.now, Time.now + 1, random_id, :payload => :bar)
- assert_equal Hash[:payload => :bar], event.payload
+ event = event(:foo, Time.now, Time.now + 1, random_id, payload: :bar)
+ assert_equal Hash[payload: :bar], event.payload
end
def test_event_is_parent_based_on_children
@@ -273,7 +275,7 @@ module Notifications
assert !not_child.parent_of?(parent)
end
- protected
+ private
def random_id
@random_id ||= SecureRandom.hex(10)
end
diff --git a/activesupport/test/number_helper_i18n_test.rb b/activesupport/test/number_helper_i18n_test.rb
index e6925e9083..365fa96f4d 100644
--- a/activesupport/test/number_helper_i18n_test.rb
+++ b/activesupport/test/number_helper_i18n_test.rb
@@ -1,46 +1,49 @@
-require 'abstract_unit'
-require 'active_support/number_helper'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/number_helper"
+require "active_support/core_ext/hash/keys"
module ActiveSupport
class NumberHelperI18nTest < ActiveSupport::TestCase
include ActiveSupport::NumberHelper
def setup
- I18n.backend.store_translations 'ts',
- :number => {
- :format => { :precision => 3, :delimiter => ',', :separator => '.', :significant => false, :strip_insignificant_zeros => false },
- :currency => { :format => { :unit => '&$', :format => '%u - %n', :negative_format => '(%u - %n)', :precision => 2 } },
- :human => {
- :format => {
- :precision => 2,
- :significant => true,
- :strip_insignificant_zeros => true
+ I18n.backend.store_translations "ts",
+ number: {
+ format: { precision: 3, delimiter: ",", separator: ".", significant: false, strip_insignificant_zeros: false },
+ currency: { format: { unit: "&$", format: "%u - %n", negative_format: "(%u - %n)", precision: 2 } },
+ human: {
+ format: {
+ precision: 2,
+ significant: true,
+ strip_insignificant_zeros: true
},
- :storage_units => {
- :format => "%n %u",
- :units => {
- :byte => "b",
- :kb => "k"
+ storage_units: {
+ format: "%n %u",
+ units: {
+ byte: "b",
+ kb: "k"
}
},
- :decimal_units => {
- :format => "%n %u",
- :units => {
- :deci => {:one => "Tenth", :other => "Tenths"},
- :unit => "u",
- :ten => {:one => "Ten", :other => "Tens"},
- :thousand => "t",
- :million => "m",
- :billion =>"b",
- :trillion =>"t" ,
- :quadrillion =>"q"
+ decimal_units: {
+ format: "%n %u",
+ units: {
+ deci: { one: "Tenth", other: "Tenths" },
+ unit: "u",
+ ten: { one: "Ten", other: "Tens" },
+ thousand: "t",
+ million: "m",
+ billion: "b",
+ trillion: "t",
+ quadrillion: "q"
}
}
},
- :percentage => { :format => {:delimiter => '', :precision => 2, :strip_insignificant_zeros => true} },
- :precision => { :format => {:delimiter => '', :significant => true} }
+ percentage: { format: { delimiter: "", precision: 2, strip_insignificant_zeros: true } },
+ precision: { format: { delimiter: "", significant: true } }
},
- :custom_units_for_number_to_human => {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"}
+ custom_units_for_number_to_human: { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
end
def teardown
@@ -48,101 +51,101 @@ module ActiveSupport
end
def test_number_to_i18n_currency
- assert_equal("&$ - 10.00", number_to_currency(10, :locale => 'ts'))
- assert_equal("(&$ - 10.00)", number_to_currency(-10, :locale => 'ts'))
- assert_equal("-10.00 - &$", number_to_currency(-10, :locale => 'ts', :format => "%n - %u"))
+ assert_equal("&$ - 10.00", number_to_currency(10, locale: "ts"))
+ assert_equal("(&$ - 10.00)", number_to_currency(-10, locale: "ts"))
+ assert_equal("-10.00 - &$", number_to_currency(-10, locale: "ts", format: "%n - %u"))
end
def test_number_to_currency_with_empty_i18n_store
- assert_equal("$10.00", number_to_currency(10, :locale => 'empty'))
- assert_equal("-$10.00", number_to_currency(-10, :locale => 'empty'))
+ assert_equal("$10.00", number_to_currency(10, locale: "empty"))
+ assert_equal("-$10.00", number_to_currency(-10, locale: "empty"))
end
def test_locale_default_format_has_precedence_over_helper_defaults
- I18n.backend.store_translations 'ts',
- { :number => { :format => { :separator => ";" } } }
+ I18n.backend.store_translations "ts",
+ number: { format: { separator: ";" } }
- assert_equal("&$ - 10;00", number_to_currency(10, :locale => 'ts'))
+ assert_equal("&$ - 10;00", number_to_currency(10, locale: "ts"))
end
def test_number_to_currency_without_currency_negative_format
- I18n.backend.store_translations 'no_negative_format', :number => {
- :currency => { :format => { :unit => '@', :format => '%n %u' } }
+ I18n.backend.store_translations "no_negative_format", number: {
+ currency: { format: { unit: "@", format: "%n %u" } }
}
- assert_equal("-10.00 @", number_to_currency(-10, :locale => 'no_negative_format'))
+ assert_equal("-10.00 @", number_to_currency(-10, locale: "no_negative_format"))
end
def test_number_with_i18n_precision
- #Delimiter was set to ""
- assert_equal("10000", number_to_rounded(10000, :locale => 'ts'))
+ # Delimiter was set to ""
+ assert_equal("10000", number_to_rounded(10000, locale: "ts"))
- #Precision inherited and significant was set
- assert_equal("1.00", number_to_rounded(1.0, :locale => 'ts'))
+ # Precision inherited and significant was set
+ assert_equal("1.00", number_to_rounded(1.0, locale: "ts"))
end
def test_number_with_i18n_precision_and_empty_i18n_store
- assert_equal("123456789.123", number_to_rounded(123456789.123456789, :locale => 'empty'))
- assert_equal("1.000", number_to_rounded(1.0000, :locale => 'empty'))
+ assert_equal("123456789.123", number_to_rounded(123456789.123456789, locale: "empty"))
+ assert_equal("1.000", number_to_rounded(1.0000, locale: "empty"))
end
def test_number_with_i18n_delimiter
- #Delimiter "," and separator "."
- assert_equal("1,000,000.234", number_to_delimited(1000000.234, :locale => 'ts'))
+ # Delimiter "," and separator "."
+ assert_equal("1,000,000.234", number_to_delimited(1000000.234, locale: "ts"))
end
def test_number_with_i18n_delimiter_and_empty_i18n_store
- assert_equal("1,000,000.234", number_to_delimited(1000000.234, :locale => 'empty'))
+ assert_equal("1,000,000.234", number_to_delimited(1000000.234, locale: "empty"))
end
def test_number_to_i18n_percentage
# to see if strip_insignificant_zeros is true
- assert_equal("1%", number_to_percentage(1, :locale => 'ts'))
+ assert_equal("1%", number_to_percentage(1, locale: "ts"))
# precision is 2, significant should be inherited
- assert_equal("1.24%", number_to_percentage(1.2434, :locale => 'ts'))
+ assert_equal("1.24%", number_to_percentage(1.2434, locale: "ts"))
# no delimiter
- assert_equal("12434%", number_to_percentage(12434, :locale => 'ts'))
+ assert_equal("12434%", number_to_percentage(12434, locale: "ts"))
end
def test_number_to_i18n_percentage_and_empty_i18n_store
- assert_equal("1.000%", number_to_percentage(1, :locale => 'empty'))
- assert_equal("1.243%", number_to_percentage(1.2434, :locale => 'empty'))
- assert_equal("12434.000%", number_to_percentage(12434, :locale => 'empty'))
+ assert_equal("1.000%", number_to_percentage(1, locale: "empty"))
+ assert_equal("1.243%", number_to_percentage(1.2434, locale: "empty"))
+ assert_equal("12434.000%", number_to_percentage(12434, locale: "empty"))
end
def test_number_to_i18n_human_size
- #b for bytes and k for kbytes
- assert_equal("2 k", number_to_human_size(2048, :locale => 'ts'))
- assert_equal("42 b", number_to_human_size(42, :locale => 'ts'))
+ # b for bytes and k for kbytes
+ assert_equal("2 k", number_to_human_size(2048, locale: "ts"))
+ assert_equal("42 b", number_to_human_size(42, locale: "ts"))
end
def test_number_to_i18n_human_size_with_empty_i18n_store
- assert_equal("2 KB", number_to_human_size(2048, :locale => 'empty'))
- assert_equal("42 Bytes", number_to_human_size(42, :locale => 'empty'))
+ assert_equal("2 KB", number_to_human_size(2048, locale: "empty"))
+ assert_equal("42 Bytes", number_to_human_size(42, locale: "empty"))
end
def test_number_to_human_with_default_translation_scope
- #Using t for thousand
- assert_equal "2 t", number_to_human(2000, :locale => 'ts')
- #Significant was set to true with precision 2, using b for billion
- assert_equal "1.2 b", number_to_human(1234567890, :locale => 'ts')
- #Using pluralization (Ten/Tens and Tenth/Tenths)
- assert_equal "1 Tenth", number_to_human(0.1, :locale => 'ts')
- assert_equal "1.3 Tenth", number_to_human(0.134, :locale => 'ts')
- assert_equal "2 Tenths", number_to_human(0.2, :locale => 'ts')
- assert_equal "1 Ten", number_to_human(10, :locale => 'ts')
- assert_equal "1.2 Ten", number_to_human(12, :locale => 'ts')
- assert_equal "2 Tens", number_to_human(20, :locale => 'ts')
+ # Using t for thousand
+ assert_equal "2 t", number_to_human(2000, locale: "ts")
+ # Significant was set to true with precision 2, using b for billion
+ assert_equal "1.2 b", number_to_human(1234567890, locale: "ts")
+ # Using pluralization (Ten/Tens and Tenth/Tenths)
+ assert_equal "1 Tenth", number_to_human(0.1, locale: "ts")
+ assert_equal "1.3 Tenth", number_to_human(0.134, locale: "ts")
+ assert_equal "2 Tenths", number_to_human(0.2, locale: "ts")
+ assert_equal "1 Ten", number_to_human(10, locale: "ts")
+ assert_equal "1.2 Ten", number_to_human(12, locale: "ts")
+ assert_equal "2 Tens", number_to_human(20, locale: "ts")
end
def test_number_to_human_with_empty_i18n_store
- assert_equal "2 Thousand", number_to_human(2000, :locale => 'empty')
- assert_equal "1.23 Billion", number_to_human(1234567890, :locale => 'empty')
+ assert_equal "2 Thousand", number_to_human(2000, locale: "empty")
+ assert_equal "1.23 Billion", number_to_human(1234567890, locale: "empty")
end
def test_number_to_human_with_custom_translation_scope
- #Significant was set to true with precision 2, with custom translated units
- assert_equal "4.3 cm", number_to_human(0.0432, :locale => 'ts', :units => :custom_units_for_number_to_human)
+ # Significant was set to true with precision 2, with custom translated units
+ assert_equal "4.3 cm", number_to_human(0.0432, locale: "ts", units: :custom_units_for_number_to_human)
end
end
end
diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb
index 074c872efc..16ccc5572c 100644
--- a/activesupport/test/number_helper_test.rb
+++ b/activesupport/test/number_helper_test.rb
@@ -1,11 +1,12 @@
-require 'abstract_unit'
-require 'active_support/number_helper'
-require 'active_support/core_ext/string/output_safety'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/number_helper"
+require "active_support/core_ext/string/output_safety"
module ActiveSupport
module NumberHelper
class NumberHelperTest < ActiveSupport::TestCase
-
class TestClassWithInstanceNumberHelpers
include ActiveSupport::NumberHelper
end
@@ -46,17 +47,17 @@ module ActiveSupport
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
assert_equal("555-1234", number_helper.number_to_phone(5551234))
assert_equal("800-555-1212", number_helper.number_to_phone(8005551212))
- assert_equal("(800) 555-1212", number_helper.number_to_phone(8005551212, {:area_code => true}))
- assert_equal("", number_helper.number_to_phone("", {:area_code => true}))
- assert_equal("800 555 1212", number_helper.number_to_phone(8005551212, {:delimiter => " "}))
- assert_equal("(800) 555-1212 x 123", number_helper.number_to_phone(8005551212, {:area_code => true, :extension => 123}))
- assert_equal("800-555-1212", number_helper.number_to_phone(8005551212, :extension => " "))
- assert_equal("555.1212", number_helper.number_to_phone(5551212, :delimiter => '.'))
+ assert_equal("(800) 555-1212", number_helper.number_to_phone(8005551212, area_code: true))
+ assert_equal("", number_helper.number_to_phone("", area_code: true))
+ assert_equal("800 555 1212", number_helper.number_to_phone(8005551212, delimiter: " "))
+ assert_equal("(800) 555-1212 x 123", number_helper.number_to_phone(8005551212, area_code: true, extension: 123))
+ assert_equal("800-555-1212", number_helper.number_to_phone(8005551212, extension: " "))
+ assert_equal("555.1212", number_helper.number_to_phone(5551212, delimiter: "."))
assert_equal("800-555-1212", number_helper.number_to_phone("8005551212"))
- assert_equal("+1-800-555-1212", number_helper.number_to_phone(8005551212, :country_code => 1))
- assert_equal("+18005551212", number_helper.number_to_phone(8005551212, :country_code => 1, :delimiter => ''))
+ assert_equal("+1-800-555-1212", number_helper.number_to_phone(8005551212, country_code: 1))
+ assert_equal("+18005551212", number_helper.number_to_phone(8005551212, country_code: 1, delimiter: ""))
assert_equal("22-555-1212", number_helper.number_to_phone(225551212))
- assert_equal("+45-22-555-1212", number_helper.number_to_phone(225551212, :country_code => 45))
+ assert_equal("+45-22-555-1212", number_helper.number_to_phone(225551212, country_code: 45))
assert_equal("(755) 6123-4567", number_helper.number_to_phone(75561234567, pattern: /(\d{3,4})(\d{4})(\d{4})/, area_code: true))
assert_equal("133-1234-5678", number_helper.number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})/))
end
@@ -67,28 +68,28 @@ module ActiveSupport
assert_equal("$1,234,567,890.50", number_helper.number_to_currency(1234567890.50))
assert_equal("$1,234,567,890.51", number_helper.number_to_currency(1234567890.506))
assert_equal("-$1,234,567,890.50", number_helper.number_to_currency(-1234567890.50))
- assert_equal("-$ 1,234,567,890.50", number_helper.number_to_currency(-1234567890.50, {:format => "%u %n"}))
- assert_equal("($1,234,567,890.50)", number_helper.number_to_currency(-1234567890.50, {:negative_format => "(%u%n)"}))
- assert_equal("$1,234,567,892", number_helper.number_to_currency(1234567891.50, {:precision => 0}))
- assert_equal("$1,234,567,890.5", number_helper.number_to_currency(1234567890.50, {:precision => 1}))
- assert_equal("&pound;1234567890,50", number_helper.number_to_currency(1234567890.50, {:unit => "&pound;", :separator => ",", :delimiter => ""}))
+ assert_equal("-$ 1,234,567,890.50", number_helper.number_to_currency(-1234567890.50, format: "%u %n"))
+ assert_equal("($1,234,567,890.50)", number_helper.number_to_currency(-1234567890.50, negative_format: "(%u%n)"))
+ assert_equal("$1,234,567,892", number_helper.number_to_currency(1234567891.50, precision: 0))
+ assert_equal("$1,234,567,890.5", number_helper.number_to_currency(1234567890.50, precision: 1))
+ assert_equal("&pound;1234567890,50", number_helper.number_to_currency(1234567890.50, unit: "&pound;", separator: ",", delimiter: ""))
assert_equal("$1,234,567,890.50", number_helper.number_to_currency("1234567890.50"))
- assert_equal("1,234,567,890.50 K&#269;", number_helper.number_to_currency("1234567890.50", {:unit => "K&#269;", :format => "%n %u"}))
- assert_equal("1,234,567,890.50 - K&#269;", number_helper.number_to_currency("-1234567890.50", {:unit => "K&#269;", :format => "%n %u", :negative_format => "%n - %u"}))
- assert_equal("0.00", number_helper.number_to_currency(+0.0, {:unit => "", :negative_format => "(%n)"}))
+ assert_equal("1,234,567,890.50 K&#269;", number_helper.number_to_currency("1234567890.50", unit: "K&#269;", format: "%n %u"))
+ assert_equal("1,234,567,890.50 - K&#269;", number_helper.number_to_currency("-1234567890.50", unit: "K&#269;", format: "%n %u", negative_format: "%n - %u"))
+ assert_equal("0.00", number_helper.number_to_currency(+0.0, unit: "", negative_format: "(%n)"))
end
end
def test_number_to_percentage
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
assert_equal("100.000%", number_helper.number_to_percentage(100))
- assert_equal("100%", number_helper.number_to_percentage(100, {:precision => 0}))
- assert_equal("302.06%", number_helper.number_to_percentage(302.0574, {:precision => 2}))
+ assert_equal("100%", number_helper.number_to_percentage(100, precision: 0))
+ assert_equal("302.06%", number_helper.number_to_percentage(302.0574, precision: 2))
assert_equal("100.000%", number_helper.number_to_percentage("100"))
assert_equal("1000.000%", number_helper.number_to_percentage("1000"))
- assert_equal("123.4%", number_helper.number_to_percentage(123.400, :precision => 3, :strip_insignificant_zeros => true))
- assert_equal("1.000,000%", number_helper.number_to_percentage(1000, :delimiter => '.', :separator => ','))
- assert_equal("1000.000 %", number_helper.number_to_percentage(1000, :format => "%n %"))
+ assert_equal("123.4%", number_helper.number_to_percentage(123.400, precision: 3, strip_insignificant_zeros: true))
+ assert_equal("1.000,000%", number_helper.number_to_percentage(1000, delimiter: ".", separator: ","))
+ assert_equal("1000.000 %", number_helper.number_to_percentage(1000, format: "%n %"))
assert_equal("98a%", number_helper.number_to_percentage("98a"))
assert_equal("NaN%", number_helper.number_to_percentage(Float::NAN))
assert_equal("Inf%", number_helper.number_to_percentage(Float::INFINITY))
@@ -122,9 +123,9 @@ module ActiveSupport
def test_to_delimited_with_options_hash
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '12 345 678', number_helper.number_to_delimited(12345678, :delimiter => ' ')
- assert_equal '12,345,678-05', number_helper.number_to_delimited(12345678.05, :separator => '-')
- assert_equal '12.345.678,05', number_helper.number_to_delimited(12345678.05, :separator => ',', :delimiter => '.')
+ assert_equal "12 345 678", number_helper.number_to_delimited(12345678, delimiter: " ")
+ assert_equal "12,345,678-05", number_helper.number_to_delimited(12345678.05, separator: "-")
+ assert_equal "12.345.678,05", number_helper.number_to_delimited(12345678.05, separator: ",", delimiter: ".")
end
end
@@ -132,77 +133,77 @@ module ActiveSupport
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
assert_equal("-111.235", number_helper.number_to_rounded(-111.2346))
assert_equal("111.235", number_helper.number_to_rounded(111.2346))
- assert_equal("31.83", number_helper.number_to_rounded(31.825, :precision => 2))
- assert_equal("111.23", number_helper.number_to_rounded(111.2346, :precision => 2))
- assert_equal("111.00", number_helper.number_to_rounded(111, :precision => 2))
+ assert_equal("31.83", number_helper.number_to_rounded(31.825, precision: 2))
+ assert_equal("111.23", number_helper.number_to_rounded(111.2346, precision: 2))
+ assert_equal("111.00", number_helper.number_to_rounded(111, precision: 2))
assert_equal("111.235", number_helper.number_to_rounded("111.2346"))
- assert_equal("31.83", number_helper.number_to_rounded("31.825", :precision => 2))
- assert_equal("3268", number_helper.number_to_rounded((32.6751 * 100.00), :precision => 0))
- assert_equal("112", number_helper.number_to_rounded(111.50, :precision => 0))
- assert_equal("1234567892", number_helper.number_to_rounded(1234567891.50, :precision => 0))
- assert_equal("0", number_helper.number_to_rounded(0, :precision => 0))
- assert_equal("0.00100", number_helper.number_to_rounded(0.001, :precision => 5))
- assert_equal("0.001", number_helper.number_to_rounded(0.00111, :precision => 3))
- assert_equal("10.00", number_helper.number_to_rounded(9.995, :precision => 2))
- assert_equal("11.00", number_helper.number_to_rounded(10.995, :precision => 2))
- assert_equal("0.00", number_helper.number_to_rounded(-0.001, :precision => 2))
-
- assert_equal("111.23460000000000000000", number_helper.number_to_rounded(111.2346, :precision => 20))
- assert_equal("111.23460000000000000000", number_helper.number_to_rounded(Rational(1112346, 10000), :precision => 20))
- assert_equal("111.23460000000000000000", number_helper.number_to_rounded('111.2346', :precision => 20))
- assert_equal("111.23460000000000000000", number_helper.number_to_rounded(BigDecimal(111.2346, Float::DIG), :precision => 20))
- assert_equal("111.2346" + "0"*96, number_helper.number_to_rounded('111.2346', :precision => 100))
- assert_equal("111.2346", number_helper.number_to_rounded(Rational(1112346, 10000), :precision => 4))
- assert_equal('0.00', number_helper.number_to_rounded(Rational(0, 1), :precision => 2))
+ assert_equal("31.83", number_helper.number_to_rounded("31.825", precision: 2))
+ assert_equal("3268", number_helper.number_to_rounded((32.6751 * 100.00), precision: 0))
+ assert_equal("112", number_helper.number_to_rounded(111.50, precision: 0))
+ assert_equal("1234567892", number_helper.number_to_rounded(1234567891.50, precision: 0))
+ assert_equal("0", number_helper.number_to_rounded(0, precision: 0))
+ assert_equal("0.00100", number_helper.number_to_rounded(0.001, precision: 5))
+ assert_equal("0.001", number_helper.number_to_rounded(0.00111, precision: 3))
+ assert_equal("10.00", number_helper.number_to_rounded(9.995, precision: 2))
+ assert_equal("11.00", number_helper.number_to_rounded(10.995, precision: 2))
+ assert_equal("0.00", number_helper.number_to_rounded(-0.001, precision: 2))
+
+ assert_equal("111.23460000000000000000", number_helper.number_to_rounded(111.2346, precision: 20))
+ assert_equal("111.23460000000000000000", number_helper.number_to_rounded(Rational(1112346, 10000), precision: 20))
+ assert_equal("111.23460000000000000000", number_helper.number_to_rounded("111.2346", precision: 20))
+ assert_equal("111.23460000000000000000", number_helper.number_to_rounded(BigDecimal(111.2346, Float::DIG), precision: 20))
+ assert_equal("111.2346" + "0" * 96, number_helper.number_to_rounded("111.2346", precision: 100))
+ assert_equal("111.2346", number_helper.number_to_rounded(Rational(1112346, 10000), precision: 4))
+ assert_equal("0.00", number_helper.number_to_rounded(Rational(0, 1), precision: 2))
end
end
def test_to_rounded_with_custom_delimiter_and_separator
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '31,83', number_helper.number_to_rounded(31.825, :precision => 2, :separator => ',')
- assert_equal '1.231,83', number_helper.number_to_rounded(1231.825, :precision => 2, :separator => ',', :delimiter => '.')
+ assert_equal "31,83", number_helper.number_to_rounded(31.825, precision: 2, separator: ",")
+ assert_equal "1.231,83", number_helper.number_to_rounded(1231.825, precision: 2, separator: ",", delimiter: ".")
end
end
def test_to_rounded_with_significant_digits
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal "124000", number_helper.number_to_rounded(123987, :precision => 3, :significant => true)
- assert_equal "120000000", number_helper.number_to_rounded(123987876, :precision => 2, :significant => true )
- assert_equal "40000", number_helper.number_to_rounded("43523", :precision => 1, :significant => true )
- assert_equal "9775", number_helper.number_to_rounded(9775, :precision => 4, :significant => true )
- assert_equal "5.4", number_helper.number_to_rounded(5.3923, :precision => 2, :significant => true )
- assert_equal "5", number_helper.number_to_rounded(5.3923, :precision => 1, :significant => true )
- assert_equal "1", number_helper.number_to_rounded(1.232, :precision => 1, :significant => true )
- assert_equal "7", number_helper.number_to_rounded(7, :precision => 1, :significant => true )
- assert_equal "1", number_helper.number_to_rounded(1, :precision => 1, :significant => true )
- assert_equal "53", number_helper.number_to_rounded(52.7923, :precision => 2, :significant => true )
- assert_equal "9775.00", number_helper.number_to_rounded(9775, :precision => 6, :significant => true )
- assert_equal "5.392900", number_helper.number_to_rounded(5.3929, :precision => 7, :significant => true )
- assert_equal "0.0", number_helper.number_to_rounded(0, :precision => 2, :significant => true )
- assert_equal "0", number_helper.number_to_rounded(0, :precision => 1, :significant => true )
- assert_equal "0.0001", number_helper.number_to_rounded(0.0001, :precision => 1, :significant => true )
- assert_equal "0.000100", number_helper.number_to_rounded(0.0001, :precision => 3, :significant => true )
- assert_equal "0.0001", number_helper.number_to_rounded(0.0001111, :precision => 1, :significant => true )
- assert_equal "10.0", number_helper.number_to_rounded(9.995, :precision => 3, :significant => true)
- assert_equal "9.99", number_helper.number_to_rounded(9.994, :precision => 3, :significant => true)
- assert_equal "11.0", number_helper.number_to_rounded(10.995, :precision => 3, :significant => true)
-
- assert_equal "9775.0000000000000000", number_helper.number_to_rounded(9775, :precision => 20, :significant => true )
- assert_equal "9775.0000000000000000", number_helper.number_to_rounded(9775.0, :precision => 20, :significant => true )
- assert_equal "9775.0000000000000000", number_helper.number_to_rounded(Rational(9775, 1), :precision => 20, :significant => true )
- assert_equal "97.750000000000000000", number_helper.number_to_rounded(Rational(9775, 100), :precision => 20, :significant => true )
- assert_equal "9775.0000000000000000", number_helper.number_to_rounded(BigDecimal(9775), :precision => 20, :significant => true )
- assert_equal "9775.0000000000000000", number_helper.number_to_rounded("9775", :precision => 20, :significant => true )
- assert_equal "9775." + "0"*96, number_helper.number_to_rounded("9775", :precision => 100, :significant => true )
- assert_equal("97.7", number_helper.number_to_rounded(Rational(9772, 100), :precision => 3, :significant => true))
+ assert_equal "124000", number_helper.number_to_rounded(123987, precision: 3, significant: true)
+ assert_equal "120000000", number_helper.number_to_rounded(123987876, precision: 2, significant: true)
+ assert_equal "40000", number_helper.number_to_rounded("43523", precision: 1, significant: true)
+ assert_equal "9775", number_helper.number_to_rounded(9775, precision: 4, significant: true)
+ assert_equal "5.4", number_helper.number_to_rounded(5.3923, precision: 2, significant: true)
+ assert_equal "5", number_helper.number_to_rounded(5.3923, precision: 1, significant: true)
+ assert_equal "1", number_helper.number_to_rounded(1.232, precision: 1, significant: true)
+ assert_equal "7", number_helper.number_to_rounded(7, precision: 1, significant: true)
+ assert_equal "1", number_helper.number_to_rounded(1, precision: 1, significant: true)
+ assert_equal "53", number_helper.number_to_rounded(52.7923, precision: 2, significant: true)
+ assert_equal "9775.00", number_helper.number_to_rounded(9775, precision: 6, significant: true)
+ assert_equal "5.392900", number_helper.number_to_rounded(5.3929, precision: 7, significant: true)
+ assert_equal "0.0", number_helper.number_to_rounded(0, precision: 2, significant: true)
+ assert_equal "0", number_helper.number_to_rounded(0, precision: 1, significant: true)
+ assert_equal "0.0001", number_helper.number_to_rounded(0.0001, precision: 1, significant: true)
+ assert_equal "0.000100", number_helper.number_to_rounded(0.0001, precision: 3, significant: true)
+ assert_equal "0.0001", number_helper.number_to_rounded(0.0001111, precision: 1, significant: true)
+ assert_equal "10.0", number_helper.number_to_rounded(9.995, precision: 3, significant: true)
+ assert_equal "9.99", number_helper.number_to_rounded(9.994, precision: 3, significant: true)
+ assert_equal "11.0", number_helper.number_to_rounded(10.995, precision: 3, significant: true)
+
+ assert_equal "9775.0000000000000000", number_helper.number_to_rounded(9775, precision: 20, significant: true)
+ assert_equal "9775.0000000000000000", number_helper.number_to_rounded(9775.0, precision: 20, significant: true)
+ assert_equal "9775.0000000000000000", number_helper.number_to_rounded(Rational(9775, 1), precision: 20, significant: true)
+ assert_equal "97.750000000000000000", number_helper.number_to_rounded(Rational(9775, 100), precision: 20, significant: true)
+ assert_equal "9775.0000000000000000", number_helper.number_to_rounded(BigDecimal(9775), precision: 20, significant: true)
+ assert_equal "9775.0000000000000000", number_helper.number_to_rounded("9775", precision: 20, significant: true)
+ assert_equal "9775." + "0" * 96, number_helper.number_to_rounded("9775", precision: 100, significant: true)
+ assert_equal("97.7", number_helper.number_to_rounded(Rational(9772, 100), precision: 3, significant: true))
end
end
def test_to_rounded_with_strip_insignificant_zeros
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal "9775.43", number_helper.number_to_rounded(9775.43, :precision => 4, :strip_insignificant_zeros => true )
- assert_equal "9775.2", number_helper.number_to_rounded(9775.2, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
- assert_equal "0", number_helper.number_to_rounded(0, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
+ assert_equal "9775.43", number_helper.number_to_rounded(9775.43, precision: 4, strip_insignificant_zeros: true)
+ assert_equal "9775.2", number_helper.number_to_rounded(9775.2, precision: 6, significant: true, strip_insignificant_zeros: true)
+ assert_equal "0", number_helper.number_to_rounded(0, precision: 6, significant: true, strip_insignificant_zeros: true)
end
end
@@ -210,156 +211,145 @@ module ActiveSupport
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
# Zero precision with significant is a mistake (would always return zero),
# so we treat it as if significant was false (increases backwards compatibility for number_to_human_size)
- assert_equal "124", number_helper.number_to_rounded(123.987, :precision => 0, :significant => true)
- assert_equal "12", number_helper.number_to_rounded(12, :precision => 0, :significant => true )
- assert_equal "12", number_helper.number_to_rounded("12.3", :precision => 0, :significant => true )
+ assert_equal "124", number_helper.number_to_rounded(123.987, precision: 0, significant: true)
+ assert_equal "12", number_helper.number_to_rounded(12, precision: 0, significant: true)
+ assert_equal "12", number_helper.number_to_rounded("12.3", precision: 0, significant: true)
end
end
def test_number_number_to_human_size
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '0 Bytes', number_helper.number_to_human_size(0)
- assert_equal '1 Byte', number_helper.number_to_human_size(1)
- assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265)
- assert_equal '123 Bytes', number_helper.number_to_human_size(123.0)
- assert_equal '123 Bytes', number_helper.number_to_human_size(123)
- assert_equal '1.21 KB', number_helper.number_to_human_size(1234)
- assert_equal '12.1 KB', number_helper.number_to_human_size(12345)
- assert_equal '1.18 MB', number_helper.number_to_human_size(1234567)
- assert_equal '1.15 GB', number_helper.number_to_human_size(1234567890)
- assert_equal '1.12 TB', number_helper.number_to_human_size(1234567890123)
- assert_equal '1.1 PB', number_helper.number_to_human_size(1234567890123456)
- assert_equal '1.07 EB', number_helper.number_to_human_size(1234567890123456789)
- assert_equal '1030 EB', number_helper.number_to_human_size(exabytes(1026))
- assert_equal '444 KB', number_helper.number_to_human_size(kilobytes(444))
- assert_equal '1020 MB', number_helper.number_to_human_size(megabytes(1023))
- assert_equal '3 TB', number_helper.number_to_human_size(terabytes(3))
- assert_equal '1.2 MB', number_helper.number_to_human_size(1234567, :precision => 2)
- assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265, :precision => 4)
- assert_equal '123 Bytes', number_helper.number_to_human_size('123')
- assert_equal '1 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 2)
- assert_equal '1.01 KB', number_helper.number_to_human_size(kilobytes(1.0100), :precision => 4)
- assert_equal '10 KB', number_helper.number_to_human_size(kilobytes(10.000), :precision => 4)
- assert_equal '1 Byte', number_helper.number_to_human_size(1.1)
- assert_equal '10 Bytes', number_helper.number_to_human_size(10)
- end
- end
-
- def test_number_to_human_size_with_si_prefix
- assert_deprecated do
- [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265, :prefix => :si)
- assert_equal '123 Bytes', number_helper.number_to_human_size(123.0, :prefix => :si)
- assert_equal '123 Bytes', number_helper.number_to_human_size(123, :prefix => :si)
- assert_equal '1.23 KB', number_helper.number_to_human_size(1234, :prefix => :si)
- assert_equal '12.3 KB', number_helper.number_to_human_size(12345, :prefix => :si)
- assert_equal '1.23 MB', number_helper.number_to_human_size(1234567, :prefix => :si)
- assert_equal '1.23 GB', number_helper.number_to_human_size(1234567890, :prefix => :si)
- assert_equal '1.23 TB', number_helper.number_to_human_size(1234567890123, :prefix => :si)
- assert_equal '1.23 PB', number_helper.number_to_human_size(1234567890123456, :prefix => :si)
- assert_equal '1.23 EB', number_helper.number_to_human_size(1234567890123456789, :prefix => :si)
- end
+ assert_equal "0 Bytes", number_helper.number_to_human_size(0)
+ assert_equal "1 Byte", number_helper.number_to_human_size(1)
+ assert_equal "3 Bytes", number_helper.number_to_human_size(3.14159265)
+ assert_equal "123 Bytes", number_helper.number_to_human_size(123.0)
+ assert_equal "123 Bytes", number_helper.number_to_human_size(123)
+ assert_equal "1.21 KB", number_helper.number_to_human_size(1234)
+ assert_equal "12.1 KB", number_helper.number_to_human_size(12345)
+ assert_equal "1.18 MB", number_helper.number_to_human_size(1234567)
+ assert_equal "1.15 GB", number_helper.number_to_human_size(1234567890)
+ assert_equal "1.12 TB", number_helper.number_to_human_size(1234567890123)
+ assert_equal "1.1 PB", number_helper.number_to_human_size(1234567890123456)
+ assert_equal "1.07 EB", number_helper.number_to_human_size(1234567890123456789)
+ assert_equal "1030 EB", number_helper.number_to_human_size(exabytes(1026))
+ assert_equal "444 KB", number_helper.number_to_human_size(kilobytes(444))
+ assert_equal "1020 MB", number_helper.number_to_human_size(megabytes(1023))
+ assert_equal "3 TB", number_helper.number_to_human_size(terabytes(3))
+ assert_equal "1.2 MB", number_helper.number_to_human_size(1234567, precision: 2)
+ assert_equal "3 Bytes", number_helper.number_to_human_size(3.14159265, precision: 4)
+ assert_equal "123 Bytes", number_helper.number_to_human_size("123")
+ assert_equal "1 KB", number_helper.number_to_human_size(kilobytes(1.0123), precision: 2)
+ assert_equal "1.01 KB", number_helper.number_to_human_size(kilobytes(1.0100), precision: 4)
+ assert_equal "10 KB", number_helper.number_to_human_size(kilobytes(10.000), precision: 4)
+ assert_equal "1 Byte", number_helper.number_to_human_size(1.1)
+ assert_equal "10 Bytes", number_helper.number_to_human_size(10)
end
end
def test_number_to_human_size_with_options_hash
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '1.2 MB', number_helper.number_to_human_size(1234567, :precision => 2)
- assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265, :precision => 4)
- assert_equal '1 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 2)
- assert_equal '1.01 KB', number_helper.number_to_human_size(kilobytes(1.0100), :precision => 4)
- assert_equal '10 KB', number_helper.number_to_human_size(kilobytes(10.000), :precision => 4)
- assert_equal '1 TB', number_helper.number_to_human_size(1234567890123, :precision => 1)
- assert_equal '500 MB', number_helper.number_to_human_size(524288000, :precision=>3)
- assert_equal '10 MB', number_helper.number_to_human_size(9961472, :precision=>0)
- assert_equal '40 KB', number_helper.number_to_human_size(41010, :precision => 1)
- assert_equal '40 KB', number_helper.number_to_human_size(41100, :precision => 2)
- assert_equal '1.0 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 2, :strip_insignificant_zeros => false)
- assert_equal '1.012 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 3, :significant => false)
- assert_equal '1 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 0, :significant => true) #ignores significant it precision is 0
+ assert_equal "1.2 MB", number_helper.number_to_human_size(1234567, precision: 2)
+ assert_equal "3 Bytes", number_helper.number_to_human_size(3.14159265, precision: 4)
+ assert_equal "1 KB", number_helper.number_to_human_size(kilobytes(1.0123), precision: 2)
+ assert_equal "1.01 KB", number_helper.number_to_human_size(kilobytes(1.0100), precision: 4)
+ assert_equal "10 KB", number_helper.number_to_human_size(kilobytes(10.000), precision: 4)
+ assert_equal "1 TB", number_helper.number_to_human_size(1234567890123, precision: 1)
+ assert_equal "500 MB", number_helper.number_to_human_size(524288000, precision: 3)
+ assert_equal "10 MB", number_helper.number_to_human_size(9961472, precision: 0)
+ assert_equal "40 KB", number_helper.number_to_human_size(41010, precision: 1)
+ assert_equal "40 KB", number_helper.number_to_human_size(41100, precision: 2)
+ assert_equal "1.0 KB", number_helper.number_to_human_size(kilobytes(1.0123), precision: 2, strip_insignificant_zeros: false)
+ assert_equal "1.012 KB", number_helper.number_to_human_size(kilobytes(1.0123), precision: 3, significant: false)
+ assert_equal "1 KB", number_helper.number_to_human_size(kilobytes(1.0123), precision: 0, significant: true) # ignores significant it precision is 0
end
end
def test_number_to_human_size_with_custom_delimiter_and_separator
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '1,01 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 3, :separator => ',')
- assert_equal '1,01 KB', number_helper.number_to_human_size(kilobytes(1.0100), :precision => 4, :separator => ',')
- assert_equal '1.000,1 TB', number_helper.number_to_human_size(terabytes(1000.1), :precision => 5, :delimiter => '.', :separator => ',')
+ assert_equal "1,01 KB", number_helper.number_to_human_size(kilobytes(1.0123), precision: 3, separator: ",")
+ assert_equal "1,01 KB", number_helper.number_to_human_size(kilobytes(1.0100), precision: 4, separator: ",")
+ assert_equal "1.000,1 TB", number_helper.number_to_human_size(terabytes(1000.1), precision: 5, delimiter: ".", separator: ",")
end
end
def test_number_to_human
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '-123', number_helper.number_to_human(-123)
- assert_equal '-0.5', number_helper.number_to_human(-0.5)
- assert_equal '0', number_helper.number_to_human(0)
- assert_equal '0.5', number_helper.number_to_human(0.5)
- assert_equal '123', number_helper.number_to_human(123)
- assert_equal '1.23 Thousand', number_helper.number_to_human(1234)
- assert_equal '12.3 Thousand', number_helper.number_to_human(12345)
- assert_equal '1.23 Million', number_helper.number_to_human(1234567)
- assert_equal '1.23 Billion', number_helper.number_to_human(1234567890)
- assert_equal '1.23 Trillion', number_helper.number_to_human(1234567890123)
- assert_equal '1.23 Quadrillion', number_helper.number_to_human(1234567890123456)
- assert_equal '1230 Quadrillion', number_helper.number_to_human(1234567890123456789)
- assert_equal '490 Thousand', number_helper.number_to_human(489939, :precision => 2)
- assert_equal '489.9 Thousand', number_helper.number_to_human(489939, :precision => 4)
- assert_equal '489 Thousand', number_helper.number_to_human(489000, :precision => 4)
- assert_equal '489.0 Thousand', number_helper.number_to_human(489000, :precision => 4, :strip_insignificant_zeros => false)
- assert_equal '1.2346 Million', number_helper.number_to_human(1234567, :precision => 4, :significant => false)
- assert_equal '1,2 Million', number_helper.number_to_human(1234567, :precision => 1, :significant => false, :separator => ',')
- assert_equal '1 Million', number_helper.number_to_human(1234567, :precision => 0, :significant => true, :separator => ',') #significant forced to false
- assert_equal '1 Million', number_helper.number_to_human(999999)
- assert_equal '1 Billion', number_helper.number_to_human(999999999)
+ assert_equal "-123", number_helper.number_to_human(-123)
+ assert_equal "-0.5", number_helper.number_to_human(-0.5)
+ assert_equal "0", number_helper.number_to_human(0)
+ assert_equal "0.5", number_helper.number_to_human(0.5)
+ assert_equal "123", number_helper.number_to_human(123)
+ assert_equal "1.23 Thousand", number_helper.number_to_human(1234)
+ assert_equal "12.3 Thousand", number_helper.number_to_human(12345)
+ assert_equal "1.23 Million", number_helper.number_to_human(1234567)
+ assert_equal "1.23 Billion", number_helper.number_to_human(1234567890)
+ assert_equal "1.23 Trillion", number_helper.number_to_human(1234567890123)
+ assert_equal "1.23 Quadrillion", number_helper.number_to_human(1234567890123456)
+ assert_equal "1230 Quadrillion", number_helper.number_to_human(1234567890123456789)
+ assert_equal "490 Thousand", number_helper.number_to_human(489939, precision: 2)
+ assert_equal "489.9 Thousand", number_helper.number_to_human(489939, precision: 4)
+ assert_equal "489 Thousand", number_helper.number_to_human(489000, precision: 4)
+ assert_equal "489.0 Thousand", number_helper.number_to_human(489000, precision: 4, strip_insignificant_zeros: false)
+ assert_equal "1.2346 Million", number_helper.number_to_human(1234567, precision: 4, significant: false)
+ assert_equal "1,2 Million", number_helper.number_to_human(1234567, precision: 1, significant: false, separator: ",")
+ assert_equal "1 Million", number_helper.number_to_human(1234567, precision: 0, significant: true, separator: ",") # significant forced to false
+ assert_equal "1 Million", number_helper.number_to_human(999999)
+ assert_equal "1 Billion", number_helper.number_to_human(999999999)
end
end
def test_number_to_human_with_custom_units
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- #Only integers
- volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
- assert_equal '123 lt', number_helper.number_to_human(123456, :units => volume)
- assert_equal '12 ml', number_helper.number_to_human(12, :units => volume)
- assert_equal '1.23 m3', number_helper.number_to_human(1234567, :units => volume)
-
- #Including fractionals
- distance = {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"}
- assert_equal '1.23 mm', number_helper.number_to_human(0.00123, :units => distance)
- assert_equal '1.23 cm', number_helper.number_to_human(0.0123, :units => distance)
- assert_equal '1.23 dm', number_helper.number_to_human(0.123, :units => distance)
- assert_equal '1.23 m', number_helper.number_to_human(1.23, :units => distance)
- assert_equal '1.23 dam', number_helper.number_to_human(12.3, :units => distance)
- assert_equal '1.23 hm', number_helper.number_to_human(123, :units => distance)
- assert_equal '1.23 km', number_helper.number_to_human(1230, :units => distance)
- assert_equal '1.23 km', number_helper.number_to_human(1230, :units => distance)
- assert_equal '1.23 km', number_helper.number_to_human(1230, :units => distance)
- assert_equal '12.3 km', number_helper.number_to_human(12300, :units => distance)
-
- #The quantifiers don't need to be a continuous sequence
- gangster = {:hundred => "hundred bucks", :million => "thousand quids"}
- assert_equal '1 hundred bucks', number_helper.number_to_human(100, :units => gangster)
- assert_equal '25 hundred bucks', number_helper.number_to_human(2500, :units => gangster)
- assert_equal '25 thousand quids', number_helper.number_to_human(25000000, :units => gangster)
- assert_equal '12300 thousand quids', number_helper.number_to_human(12345000000, :units => gangster)
-
- #Spaces are stripped from the resulting string
- assert_equal '4', number_helper.number_to_human(4, :units => {:unit => "", :ten => 'tens '})
- assert_equal '4.5 tens', number_helper.number_to_human(45, :units => {:unit => "", :ten => ' tens '})
+ # Only integers
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
+ assert_equal "123 lt", number_helper.number_to_human(123456, units: volume)
+ assert_equal "12 ml", number_helper.number_to_human(12, units: volume)
+ assert_equal "1.23 m3", number_helper.number_to_human(1234567, units: volume)
+
+ # Including fractionals
+ distance = { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
+ assert_equal "1.23 mm", number_helper.number_to_human(0.00123, units: distance)
+ assert_equal "1.23 cm", number_helper.number_to_human(0.0123, units: distance)
+ assert_equal "1.23 dm", number_helper.number_to_human(0.123, units: distance)
+ assert_equal "1.23 m", number_helper.number_to_human(1.23, units: distance)
+ assert_equal "1.23 dam", number_helper.number_to_human(12.3, units: distance)
+ assert_equal "1.23 hm", number_helper.number_to_human(123, units: distance)
+ assert_equal "1.23 km", number_helper.number_to_human(1230, units: distance)
+ assert_equal "1.23 km", number_helper.number_to_human(1230, units: distance)
+ assert_equal "1.23 km", number_helper.number_to_human(1230, units: distance)
+ assert_equal "12.3 km", number_helper.number_to_human(12300, units: distance)
+
+ # The quantifiers don't need to be a continuous sequence
+ gangster = { hundred: "hundred bucks", million: "thousand quids" }
+ assert_equal "1 hundred bucks", number_helper.number_to_human(100, units: gangster)
+ assert_equal "25 hundred bucks", number_helper.number_to_human(2500, units: gangster)
+ assert_equal "1000 hundred bucks", number_helper.number_to_human(100_000, units: gangster)
+ assert_equal "1 thousand quids", number_helper.number_to_human(999_999, units: gangster)
+ assert_equal "1 thousand quids", number_helper.number_to_human(1_000_000, units: gangster)
+ assert_equal "25 thousand quids", number_helper.number_to_human(25000000, units: gangster)
+ assert_equal "12300 thousand quids", number_helper.number_to_human(12345000000, units: gangster)
+
+ # Spaces are stripped from the resulting string
+ assert_equal "4", number_helper.number_to_human(4, units: { unit: "", ten: "tens " })
+ assert_equal "4.5 tens", number_helper.number_to_human(45, units: { unit: "", ten: " tens " })
+
+ # Uses only the provided units and does not try to use larger ones
+ assert_equal "1000 kilometers", number_helper.number_to_human(1_000_000, units: { unit: "meter", thousand: "kilometers" })
end
end
def test_number_to_human_with_custom_units_that_are_missing_the_needed_key
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '123', number_helper.number_to_human(123, units: { thousand: 'k'})
- assert_equal '123', number_helper.number_to_human(123, units: {})
+ assert_equal "123", number_helper.number_to_human(123, units: { thousand: "k" })
+ assert_equal "123", number_helper.number_to_human(123, units: {})
end
end
def test_number_to_human_with_custom_format
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal '123 times Thousand', number_helper.number_to_human(123456, :format => "%n times %u")
- volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
- assert_equal '123.lt', number_helper.number_to_human(123456, :units => volume, :format => "%n.%u")
+ assert_equal "123 times Thousand", number_helper.number_to_human(123456, format: "%n times %u")
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
+ assert_equal "123.lt", number_helper.number_to_human(123456, units: volume, format: "%n.%u")
end
end
@@ -377,34 +367,34 @@ module ActiveSupport
def test_number_helpers_do_not_mutate_options_hash
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- options = { 'raise' => true }
+ options = { "raise" => true }
number_helper.number_to_phone(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
number_helper.number_to_currency(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
number_helper.number_to_percentage(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
number_helper.number_to_delimited(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
number_helper.number_to_rounded(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
number_helper.number_to_human_size(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
number_helper.number_to_human(1, options)
- assert_equal({ 'raise' => true }, options)
+ assert_equal({ "raise" => true }, options)
end
end
def test_number_helpers_should_return_non_numeric_param_unchanged
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal("+1-x x 123", number_helper.number_to_phone("x", :country_code => 1, :extension => 123))
+ assert_equal("+1-x x 123", number_helper.number_to_phone("x", country_code: 1, extension: 123))
assert_equal("x", number_helper.number_to_phone("x"))
assert_equal("$x.", number_helper.number_to_currency("x."))
assert_equal("$x", number_helper.number_to_currency("x"))
@@ -412,11 +402,10 @@ module ActiveSupport
assert_equal("x", number_helper.number_to_delimited("x"))
assert_equal("x.", number_helper.number_to_rounded("x."))
assert_equal("x", number_helper.number_to_rounded("x"))
- assert_equal "x", number_helper.number_to_human_size('x')
- assert_equal "x", number_helper.number_to_human('x')
+ assert_equal "x", number_helper.number_to_human_size("x")
+ assert_equal "x", number_helper.number_to_human("x")
end
end
-
end
end
end
diff --git a/activesupport/test/option_merger_test.rb b/activesupport/test/option_merger_test.rb
index 4c0364e68b..935e2aee63 100644
--- a/activesupport/test/option_merger_test.rb
+++ b/activesupport/test/option_merger_test.rb
@@ -1,13 +1,15 @@
-require 'abstract_unit'
-require 'active_support/core_ext/object/with_options'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/object/with_options"
class OptionMergerTest < ActiveSupport::TestCase
def setup
- @options = {:hello => 'world'}
+ @options = { hello: "world" }
end
def test_method_with_options_merges_options_when_options_are_present
- local_options = {:cool => true}
+ local_options = { cool: true }
with_options(@options) do |o|
assert_equal local_options, method_with_options(local_options)
@@ -24,7 +26,7 @@ class OptionMergerTest < ActiveSupport::TestCase
end
def test_method_with_options_allows_to_overwrite_options
- local_options = {:hello => 'moon'}
+ local_options = { hello: "moon" }
assert_equal @options.keys, local_options.keys
with_options(@options) do |o|
@@ -40,34 +42,34 @@ class OptionMergerTest < ActiveSupport::TestCase
end
def test_nested_method_with_options_containing_hashes_merge
- with_options :conditions => { :method => :get } do |outer|
- outer.with_options :conditions => { :domain => "www" } do |inner|
- expected = { :conditions => { :method => :get, :domain => "www" } }
+ with_options conditions: { method: :get } do |outer|
+ outer.with_options conditions: { domain: "www" } do |inner|
+ expected = { conditions: { method: :get, domain: "www" } }
assert_equal expected, inner.method_with_options
end
end
end
def test_nested_method_with_options_containing_hashes_overwrite
- with_options :conditions => { :method => :get, :domain => "www" } do |outer|
- outer.with_options :conditions => { :method => :post } do |inner|
- expected = { :conditions => { :method => :post, :domain => "www" } }
+ with_options conditions: { method: :get, domain: "www" } do |outer|
+ outer.with_options conditions: { method: :post } do |inner|
+ expected = { conditions: { method: :post, domain: "www" } }
assert_equal expected, inner.method_with_options
end
end
end
def test_nested_method_with_options_containing_hashes_going_deep
- with_options :html => { :class => "foo", :style => { :margin => 0, :display => "block" } } do |outer|
- outer.with_options :html => { :title => "bar", :style => { :margin => "1em", :color => "#fff" } } do |inner|
- expected = { :html => { :class => "foo", :title => "bar", :style => { :margin => "1em", :display => "block", :color => "#fff" } } }
+ with_options html: { class: "foo", style: { margin: 0, display: "block" } } do |outer|
+ outer.with_options html: { title: "bar", style: { margin: "1em", color: "#fff" } } do |inner|
+ expected = { html: { class: "foo", title: "bar", style: { margin: "1em", display: "block", color: "#fff" } } }
assert_equal expected, inner.method_with_options
end
end
end
def test_nested_method_with_options_using_lambda
- local_lambda = lambda { { :lambda => true } }
+ local_lambda = lambda { { lambda: true } }
with_options(@options) do |o|
assert_equal @options.merge(local_lambda.call),
o.method_with_options(local_lambda).call
@@ -76,7 +78,7 @@ class OptionMergerTest < ActiveSupport::TestCase
# Needed when counting objects with the ObjectSpace
def test_option_merger_class_method
- assert_equal ActiveSupport::OptionMerger, ActiveSupport::OptionMerger.new('', '').class
+ assert_equal ActiveSupport::OptionMerger, ActiveSupport::OptionMerger.new("", "").class
end
def test_option_merger_implicit_receiver
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index 460a61613e..c70d3b4c37 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -1,8 +1,10 @@
-require 'abstract_unit'
-require 'active_support/json'
-require 'active_support/core_ext/object/json'
-require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/core_ext/array/extract_options'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/json"
+require "active_support/core_ext/object/json"
+require "active_support/core_ext/hash/indifferent_access"
+require "active_support/core_ext/array/extract_options"
class OrderedHashTest < ActiveSupport::TestCase
def setup
@@ -27,7 +29,7 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_assignment
- key, value = 'purple', '5422a8'
+ key, value = "purple", "5422a8"
@ordered_hash[key] = value
assert_equal @keys.length + 1, @ordered_hash.length
@@ -37,8 +39,8 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_delete
- key, value = 'white', 'ffffff'
- bad_key = 'black'
+ key, value = "white", "ffffff"
+ bad_key = "black"
@ordered_hash[key] = value
assert_equal @keys.length + 1, @ordered_hash.length
@@ -60,22 +62,22 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_has_key
- assert_equal true, @ordered_hash.has_key?('blue')
- assert_equal true, @ordered_hash.key?('blue')
- assert_equal true, @ordered_hash.include?('blue')
- assert_equal true, @ordered_hash.member?('blue')
+ assert_equal true, @ordered_hash.has_key?("blue")
+ assert_equal true, @ordered_hash.key?("blue")
+ assert_equal true, @ordered_hash.include?("blue")
+ assert_equal true, @ordered_hash.member?("blue")
- assert_equal false, @ordered_hash.has_key?('indigo')
- assert_equal false, @ordered_hash.key?('indigo')
- assert_equal false, @ordered_hash.include?('indigo')
- assert_equal false, @ordered_hash.member?('indigo')
+ assert_equal false, @ordered_hash.has_key?("indigo")
+ assert_equal false, @ordered_hash.key?("indigo")
+ assert_equal false, @ordered_hash.include?("indigo")
+ assert_equal false, @ordered_hash.member?("indigo")
end
def test_has_value
- assert_equal true, @ordered_hash.has_value?('000099')
- assert_equal true, @ordered_hash.value?('000099')
- assert_equal false, @ordered_hash.has_value?('ABCABC')
- assert_equal false, @ordered_hash.value?('ABCABC')
+ assert_equal true, @ordered_hash.has_value?("000099")
+ assert_equal true, @ordered_hash.value?("000099")
+ assert_equal false, @ordered_hash.has_value?("ABCABC")
+ assert_equal false, @ordered_hash.value?("ABCABC")
end
def test_each_key
@@ -94,13 +96,13 @@ class OrderedHashTest < ActiveSupport::TestCase
def test_each
values = []
- assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value}
+ assert_equal @ordered_hash, @ordered_hash.each { |key, value| values << value }
assert_equal @values, values
assert_kind_of Enumerator, @ordered_hash.each
end
def test_each_with_index
- @ordered_hash.each_with_index { |pair, index| assert_equal [@keys[index], @values[index]], pair}
+ @ordered_hash.each_with_index { |pair, index| assert_equal [@keys[index], @values[index]], pair }
end
def test_each_pair
@@ -127,24 +129,24 @@ class OrderedHashTest < ActiveSupport::TestCase
def test_delete_if
copy = @ordered_hash.dup
- copy.delete('pink')
- assert_equal copy, @ordered_hash.delete_if { |k, _| k == 'pink' }
- assert !@ordered_hash.keys.include?('pink')
+ copy.delete("pink")
+ assert_equal copy, @ordered_hash.delete_if { |k, _| k == "pink" }
+ assert_not_includes @ordered_hash.keys, "pink"
end
def test_reject!
- (copy = @ordered_hash.dup).delete('pink')
- @ordered_hash.reject! { |k, _| k == 'pink' }
+ (copy = @ordered_hash.dup).delete("pink")
+ @ordered_hash.reject! { |k, _| k == "pink" }
assert_equal copy, @ordered_hash
- assert !@ordered_hash.keys.include?('pink')
+ assert_not_includes @ordered_hash.keys, "pink"
end
def test_reject
copy = @ordered_hash.dup
- new_ordered_hash = @ordered_hash.reject { |k, _| k == 'pink' }
+ new_ordered_hash = @ordered_hash.reject { |k, _| k == "pink" }
assert_equal copy, @ordered_hash
- assert !new_ordered_hash.keys.include?('pink')
- assert @ordered_hash.keys.include?('pink')
+ assert_not_includes new_ordered_hash.keys, "pink"
+ assert_includes @ordered_hash.keys, "pink"
assert_instance_of ActiveSupport::OrderedHash, new_ordered_hash
end
@@ -154,19 +156,19 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_merge
- other_hash = ActiveSupport::OrderedHash.new
- other_hash['purple'] = '800080'
- other_hash['violet'] = 'ee82ee'
+ 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
+ assert_equal @keys + ["purple", "violet"], merged.keys
end
def test_merge_with_block
hash = ActiveSupport::OrderedHash.new
hash[:a] = 0
hash[:b] = 0
- merged = hash.merge(:b => 2, :c => 7) do |key, old_value, new_value|
+ merged = hash.merge(b: 2, c: 7) do |key, old_value, new_value|
new_value + 1
end
@@ -179,7 +181,7 @@ class OrderedHashTest < ActiveSupport::TestCase
hash = ActiveSupport::OrderedHash.new
hash[:a] = 0
hash[:b] = 0
- hash.merge!(:a => 1, :c => 7) do |key, old_value, new_value|
+ hash.merge!(a: 1, c: 7) do |key, old_value, new_value|
new_value + 3
end
@@ -191,7 +193,7 @@ class OrderedHashTest < ActiveSupport::TestCase
def test_shift
pair = @ordered_hash.shift
assert_equal [@keys.first, @values.first], pair
- assert !@ordered_hash.keys.include?(pair.first)
+ assert_not_includes @ordered_hash.keys, pair.first
end
def test_keys
@@ -201,7 +203,7 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_inspect
- assert @ordered_hash.inspect.include?(@hash.inspect)
+ assert_includes @ordered_hash.inspect, @hash.inspect
end
def test_json
@@ -211,7 +213,7 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_alternate_initialization_with_splat
- alternate = ActiveSupport::OrderedHash[1,2,3,4]
+ alternate = ActiveSupport::OrderedHash[1, 2, 3, 4]
assert_kind_of ActiveSupport::OrderedHash, alternate
assert_equal [1, 3], alternate.keys
end
@@ -220,29 +222,29 @@ class OrderedHashTest < ActiveSupport::TestCase
alternate = ActiveSupport::OrderedHash[ [
[1, 2],
[3, 4],
- [ 'missing value' ]
+ [ "missing value" ]
]]
assert_kind_of ActiveSupport::OrderedHash, alternate
- assert_equal [1, 3, 'missing value'], alternate.keys
+ assert_equal [1, 3, "missing value"], alternate.keys
assert_equal [2, 4, nil ], alternate.values
end
def test_alternate_initialization_raises_exception_on_odd_length_args
assert_raises ArgumentError do
- ActiveSupport::OrderedHash[1,2,3,4,5]
+ ActiveSupport::OrderedHash[1, 2, 3, 4, 5]
end
end
def test_replace_updates_keys
- @other_ordered_hash = ActiveSupport::OrderedHash[:black, '000000', :white, '000000']
+ @other_ordered_hash = ActiveSupport::OrderedHash[:black, "000000", :white, "000000"]
original = @ordered_hash.replace(@other_ordered_hash)
assert_same original, @ordered_hash
assert_equal @other_ordered_hash.keys, @ordered_hash.keys
end
def test_nested_under_indifferent_access
- flash = {:a => ActiveSupport::OrderedHash[:b, 1, :c, 2]}.with_indifferent_access
+ flash = { a: ActiveSupport::OrderedHash[:b, 1, :c, 2] }.with_indifferent_access
assert_kind_of ActiveSupport::OrderedHash, flash[:a]
end
@@ -295,17 +297,17 @@ class OrderedHashTest < ActiveSupport::TestCase
def test_psych_serialize_tag
yaml = Psych.dump(@ordered_hash)
- assert_match '!omap', yaml
+ assert_match "!omap", yaml
end
def test_has_yaml_tag
@ordered_hash[:array] = %w(a b c)
- assert_match '!omap', YAML.dump(@ordered_hash)
+ assert_match "!omap", YAML.dump(@ordered_hash)
end
def test_update_sets_keys
@updated_ordered_hash = ActiveSupport::OrderedHash.new
- @updated_ordered_hash.update(:name => "Bob")
+ @updated_ordered_hash.update(name: "Bob")
assert_equal [:name], @updated_ordered_hash.keys
end
diff --git a/activesupport/test/ordered_options_test.rb b/activesupport/test/ordered_options_test.rb
index 18767a3536..2c67bb02ac 100644
--- a/activesupport/test/ordered_options_test.rb
+++ b/activesupport/test/ordered_options_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/ordered_options'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/ordered_options"
class OrderedOptionsTest < ActiveSupport::TestCase
def test_usage
@@ -100,4 +102,17 @@ class OrderedOptionsTest < ActiveSupport::TestCase
end
assert_raises(KeyError) { a.non_existing_key! }
end
+
+ def test_inheritable_options_with_bang
+ a = ActiveSupport::InheritableOptions.new(foo: :bar)
+
+ assert_nothing_raised { a.foo! }
+ assert_equal a.foo, a.foo!
+
+ assert_raises(KeyError) do
+ a.foo = nil
+ a.foo!
+ end
+ assert_raises(KeyError) { a.non_existing_key! }
+ end
end
diff --git a/activesupport/test/reloader_test.rb b/activesupport/test/reloader_test.rb
index 958cb49993..3e4229eaf7 100644
--- a/activesupport/test/reloader_test.rb
+++ b/activesupport/test/reloader_test.rb
@@ -1,13 +1,18 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class ReloaderTest < ActiveSupport::TestCase
def test_prepare_callback
- prepared = false
+ prepared = completed = false
reloader.to_prepare { prepared = true }
+ reloader.to_complete { completed = true }
assert !prepared
+ assert !completed
reloader.prepare!
assert prepared
+ assert !completed
prepared = false
reloader.wrap do
@@ -17,17 +22,26 @@ class ReloaderTest < ActiveSupport::TestCase
assert !prepared
end
+ def test_prepend_prepare_callback
+ i = 10
+ reloader.to_prepare { i += 1 }
+ reloader.to_prepare(prepend: true) { i = 0 }
+
+ reloader.prepare!
+ assert_equal 1, i
+ end
+
def test_only_run_when_check_passes
r = new_reloader { true }
invoked = false
r.to_run { invoked = true }
- r.wrap { }
+ r.wrap {}
assert invoked
r = new_reloader { false }
invoked = false
r.to_run { invoked = true }
- r.wrap { }
+ r.wrap {}
assert !invoked
end
@@ -39,7 +53,7 @@ class ReloaderTest < ActiveSupport::TestCase
reloader.executor.to_run { called << :executor_run }
reloader.executor.to_complete { called << :executor_complete }
- reloader.wrap { }
+ reloader.wrap {}
assert_equal [:executor_run, :reloader_run, :prepare, :reloader_complete, :executor_complete], called
called = []
@@ -49,7 +63,7 @@ class ReloaderTest < ActiveSupport::TestCase
reloader.check = lambda { false }
called = []
- reloader.wrap { }
+ reloader.wrap {}
assert_equal [:executor_run, :executor_complete], called
called = []
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index bd43ad0797..b1b8a25c5b 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -1,9 +1,8 @@
-require 'abstract_unit'
+# frozen_string_literal: true
-class WraithAttack < StandardError
-end
+require "abstract_unit"
-class NuclearExplosion < StandardError
+class WraithAttack < StandardError
end
class MadRonon < StandardError
@@ -19,16 +18,20 @@ module WeirdError
end
class Stargate
+ # Nest this so the 'NuclearExplosion' handler needs a lexical const_get
+ # to find it.
+ class NuclearExplosion < StandardError; end
+
attr_accessor :result
include ActiveSupport::Rescuable
- rescue_from WraithAttack, :with => :sos_first
+ rescue_from WraithAttack, with: :sos_first
- rescue_from WraithAttack, :with => :sos
+ rescue_from WraithAttack, with: :sos
- rescue_from 'NuclearExplosion' do
- @result = 'alldead'
+ rescue_from "NuclearExplosion" do
+ @result = "alldead"
end
rescue_from MadRonon do |e|
@@ -36,13 +39,15 @@ class Stargate
end
rescue_from WeirdError do
- @result = 'weird'
+ @result = "weird"
end
def dispatch(method)
send(method)
rescue Exception => e
- rescue_with_handler(e)
+ unless rescue_with_handler(e)
+ @result = "unhandled"
+ end
end
def attack
@@ -57,6 +62,34 @@ class Stargate
raise MadRonon.new("dex")
end
+ def crash
+ raise "unhandled RuntimeError"
+ end
+
+ def looped_crash
+ ex1 = StandardError.new("error 1")
+ ex2 = StandardError.new("error 2")
+ begin
+ begin
+ raise ex1
+ rescue
+ # sets the cause on ex2 to be ex1
+ raise ex2
+ end
+ rescue
+ # sets the cause on ex1 to be ex2
+ raise ex1
+ end
+ end
+
+ def fall_back_to_cause
+ # This exception is the cause and has a handler.
+ ronanize
+ rescue
+ # This is the exception we'll handle that doesn't have a cause.
+ raise "unhandled RuntimeError with a handleable cause"
+ end
+
def weird
StandardError.new.tap do |exc|
def exc.weird?
@@ -68,13 +101,12 @@ class Stargate
end
def sos
- @result = 'killed'
+ @result = "killed"
end
def sos_first
- @result = 'sos_first'
+ @result = "sos_first"
end
-
end
class CoolStargate < Stargate
@@ -82,14 +114,13 @@ class CoolStargate < Stargate
include ActiveSupport::Rescuable
- rescue_from CoolError, :with => :sos_cool_error
+ rescue_from CoolError, with: :sos_cool_error
def sos_cool_error
- @result = 'sos_cool_error'
+ @result = "sos_cool_error"
end
end
-
class RescuableTest < ActiveSupport::TestCase
def setup
@stargate = Stargate.new
@@ -98,22 +129,22 @@ class RescuableTest < ActiveSupport::TestCase
def test_rescue_from_with_method
@stargate.dispatch :attack
- assert_equal 'killed', @stargate.result
+ assert_equal "killed", @stargate.result
end
def test_rescue_from_with_block
@stargate.dispatch :nuke
- assert_equal 'alldead', @stargate.result
+ assert_equal "alldead", @stargate.result
end
def test_rescue_from_with_block_with_args
@stargate.dispatch :ronanize
- assert_equal 'dex', @stargate.result
+ assert_equal "dex", @stargate.result
end
def test_rescue_from_error_dispatchers_with_case_operator
@stargate.dispatch :weird
- assert_equal 'weird', @stargate.result
+ assert_equal "weird", @stargate.result
end
def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array
@@ -127,4 +158,19 @@ class RescuableTest < ActiveSupport::TestCase
result = @cool_stargate.send(:rescue_handlers).collect(&:first)
assert_equal expected, result
end
+
+ def test_rescue_falls_back_to_exception_cause
+ @stargate.dispatch :fall_back_to_cause
+ assert_equal "dex", @stargate.result
+ end
+
+ def test_unhandled_exceptions
+ @stargate.dispatch(:crash)
+ assert_equal "unhandled", @stargate.result
+ end
+
+ def test_rescue_handles_loops_in_exception_cause_chain
+ @stargate.dispatch :looped_crash
+ assert_equal "unhandled", @stargate.result
+ end
end
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
index 18fb6d2fbf..05c2fb59be 100644
--- a/activesupport/test/safe_buffer_test.rb
+++ b/activesupport/test/safe_buffer_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/core_ext/string/inflections'
-require 'yaml'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/string/inflections"
+require "yaml"
class SafeBufferTest < ActiveSupport::TestCase
def setup
@@ -8,7 +10,7 @@ class SafeBufferTest < ActiveSupport::TestCase
end
def test_titleize
- assert_equal 'Foo', "foo".html_safe.titleize
+ assert_equal "Foo", "foo".html_safe.titleize
end
test "Should look like a string" do
@@ -46,26 +48,26 @@ class SafeBufferTest < ActiveSupport::TestCase
end
test "Should be converted to_yaml" do
- str = 'hello!'
+ str = "hello!"
buf = ActiveSupport::SafeBuffer.new str
yaml = buf.to_yaml
assert_match(/^--- #{str}/, yaml)
- assert_equal 'hello!', YAML.load(yaml)
+ assert_equal "hello!", YAML.load(yaml)
end
test "Should work in nested to_yaml conversion" do
- str = 'hello!'
- data = { 'str' => ActiveSupport::SafeBuffer.new(str) }
+ str = "hello!"
+ data = { "str" => ActiveSupport::SafeBuffer.new(str) }
yaml = YAML.dump data
- assert_equal({'str' => str}, YAML.load(yaml))
+ assert_equal({ "str" => str }, YAML.load(yaml))
end
test "Should work with primitive-like-strings in to_yaml conversion" do
- assert_equal 'true', YAML.load(ActiveSupport::SafeBuffer.new('true').to_yaml)
- assert_equal 'false', YAML.load(ActiveSupport::SafeBuffer.new('false').to_yaml)
- assert_equal '1', YAML.load(ActiveSupport::SafeBuffer.new('1').to_yaml)
- assert_equal '1.1', YAML.load(ActiveSupport::SafeBuffer.new('1.1').to_yaml)
+ assert_equal "true", YAML.load(ActiveSupport::SafeBuffer.new("true").to_yaml)
+ assert_equal "false", YAML.load(ActiveSupport::SafeBuffer.new("false").to_yaml)
+ assert_equal "1", YAML.load(ActiveSupport::SafeBuffer.new("1").to_yaml)
+ assert_equal "1.1", YAML.load(ActiveSupport::SafeBuffer.new("1.1").to_yaml)
end
test "Should work with underscore" do
@@ -74,31 +76,31 @@ class SafeBufferTest < ActiveSupport::TestCase
end
test "Should not return safe buffer from gsub" do
- altered_buffer = @buffer.gsub('', 'asdf')
- assert_equal 'asdf', altered_buffer
+ altered_buffer = @buffer.gsub("", "asdf")
+ assert_equal "asdf", altered_buffer
assert !altered_buffer.html_safe?
end
test "Should not return safe buffer from gsub!" do
- @buffer.gsub!('', 'asdf')
- assert_equal 'asdf', @buffer
+ @buffer.gsub!("", "asdf")
+ assert_equal "asdf", @buffer
assert !@buffer.html_safe?
end
test "Should escape dirty buffers on add" do
clean = "hello".html_safe
- @buffer.gsub!('', '<>')
+ @buffer.gsub!("", "<>")
assert_equal "hello&lt;&gt;", clean + @buffer
end
test "Should concat as a normal string when safe" do
clean = "hello".html_safe
- @buffer.gsub!('', '<>')
+ @buffer.gsub!("", "<>")
assert_equal "<>hello", @buffer + clean
end
test "Should preserve html_safe? status on copy" do
- @buffer.gsub!('', '<>')
+ @buffer.gsub!("", "<>")
assert !@buffer.dup.html_safe?
end
@@ -110,7 +112,7 @@ class SafeBufferTest < ActiveSupport::TestCase
end
test "Should raise an error when safe_concat is called on unsafe buffers" do
- @buffer.gsub!('', '<>')
+ @buffer.gsub!("", "<>")
assert_raise ActiveSupport::SafeBuffer::SafeConcatError do
@buffer.safe_concat "BUSTED"
end
@@ -121,22 +123,22 @@ class SafeBufferTest < ActiveSupport::TestCase
end
test "clone_empty returns an empty buffer" do
- assert_equal '', ActiveSupport::SafeBuffer.new('foo').clone_empty
+ assert_equal "", ActiveSupport::SafeBuffer.new("foo").clone_empty
end
test "clone_empty keeps the original dirtyness" do
assert @buffer.clone_empty.html_safe?
- assert !@buffer.gsub!('', '').clone_empty.html_safe?
+ assert !@buffer.gsub!("", "").clone_empty.html_safe?
end
test "Should be safe when sliced if original value was safe" do
- new_buffer = @buffer[0,0]
+ new_buffer = @buffer[0, 0]
assert_not_nil new_buffer
assert new_buffer.html_safe?, "should be safe"
end
test "Should continue unsafe on slice" do
- x = 'foo'.html_safe.gsub!('f', '<script>alert("lolpwnd");</script>')
+ x = "foo".html_safe.gsub!("f", '<script>alert("lolpwnd");</script>')
# calling gsub! makes the dirty flag true
assert !x.html_safe?, "should not be safe"
@@ -148,33 +150,33 @@ class SafeBufferTest < ActiveSupport::TestCase
assert !y.html_safe?, "should not be safe"
end
- test 'Should work with interpolation (array argument)' do
- x = 'foo %s bar'.html_safe % ['qux']
- assert_equal 'foo qux bar', x
+ test "Should work with interpolation (array argument)" do
+ x = "foo %s bar".html_safe % ["qux"]
+ assert_equal "foo qux bar", x
end
- test 'Should work with interpolation (hash argument)' do
- x = 'foo %{x} bar'.html_safe % { x: 'qux' }
- assert_equal 'foo qux bar', x
+ test "Should work with interpolation (hash argument)" do
+ x = "foo %{x} bar".html_safe % { x: "qux" }
+ assert_equal "foo qux bar", x
end
- test 'Should escape unsafe interpolated args' do
- x = 'foo %{x} bar'.html_safe % { x: '<br/>' }
- assert_equal 'foo &lt;br/&gt; bar', x
+ test "Should escape unsafe interpolated args" do
+ x = "foo %{x} bar".html_safe % { x: "<br/>" }
+ assert_equal "foo &lt;br/&gt; bar", x
end
- test 'Should not escape safe interpolated args' do
- x = 'foo %{x} bar'.html_safe % { x: '<br/>'.html_safe }
- assert_equal 'foo <br/> bar', x
+ test "Should not escape safe interpolated args" do
+ x = "foo %{x} bar".html_safe % { x: "<br/>".html_safe }
+ assert_equal "foo <br/> bar", x
end
- test 'Should interpolate to a safe string' do
- x = 'foo %{x} bar'.html_safe % { x: 'qux' }
- assert x.html_safe?, 'should be safe'
+ test "Should interpolate to a safe string" do
+ x = "foo %{x} bar".html_safe % { x: "qux" }
+ assert x.html_safe?, "should be safe"
end
- test 'Should not affect frozen objects when accessing characters' do
- x = 'Hello'.html_safe
- assert_equal x[/a/, 1], nil
+ test "Should not affect frozen objects when accessing characters" do
+ x = "Hello".html_safe
+ assert_nil x[/a/, 1]
end
end
diff --git a/activesupport/test/security_utils_test.rb b/activesupport/test/security_utils_test.rb
index 08d2e3baa6..0a607594a2 100644
--- a/activesupport/test/security_utils_test.rb
+++ b/activesupport/test/security_utils_test.rb
@@ -1,9 +1,22 @@
-require 'abstract_unit'
-require 'active_support/security_utils'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/security_utils"
class SecurityUtilsTest < ActiveSupport::TestCase
def test_secure_compare_should_perform_string_comparison
- assert ActiveSupport::SecurityUtils.secure_compare('a', 'a')
- assert !ActiveSupport::SecurityUtils.secure_compare('a', 'b')
+ assert ActiveSupport::SecurityUtils.secure_compare("a", "a")
+ assert_not ActiveSupport::SecurityUtils.secure_compare("a", "b")
+ end
+
+ def test_fixed_length_secure_compare_should_perform_string_comparison
+ assert ActiveSupport::SecurityUtils.fixed_length_secure_compare("a", "a")
+ assert !ActiveSupport::SecurityUtils.fixed_length_secure_compare("a", "b")
+ end
+
+ def test_fixed_length_secure_compare_raise_on_length_mismatch
+ assert_raises(ArgumentError, "string length mismatch.") do
+ ActiveSupport::SecurityUtils.fixed_length_secure_compare("a", "ab")
+ end
end
end
diff --git a/activesupport/test/share_lock_test.rb b/activesupport/test/share_lock_test.rb
index acefa185a8..42fd5eefc1 100644
--- a/activesupport/test/share_lock_test.rb
+++ b/activesupport/test/share_lock_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'concurrent/atomic/count_down_latch'
-require 'active_support/concurrency/share_lock'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "concurrent/atomic/count_down_latch"
+require "active_support/concurrency/share_lock"
class ShareLockTest < ActiveSupport::TestCase
def setup
@@ -17,7 +19,7 @@ class ShareLockTest < ActiveSupport::TestCase
def test_sharing_doesnt_block
with_thread_waiting_in_lock_section(:sharing) do |sharing_thread_latch|
- assert_threads_not_stuck(Thread.new {@lock.sharing {} })
+ assert_threads_not_stuck(Thread.new { @lock.sharing {} })
end
end
@@ -489,90 +491,90 @@ class ShareLockTest < ActiveSupport::TestCase
private
- module CustomAssertions
- SUFFICIENT_TIMEOUT = 0.2
+ module CustomAssertions
+ SUFFICIENT_TIMEOUT = 0.2
- private
+ private
- def assert_threads_stuck_but_releasable_by_latch(threads, latch)
- assert_threads_stuck threads
- latch.count_down
- assert_threads_not_stuck threads
- end
+ def assert_threads_stuck_but_releasable_by_latch(threads, latch)
+ assert_threads_stuck threads
+ latch.count_down
+ assert_threads_not_stuck threads
+ end
- def assert_threads_stuck(threads)
- sleep(SUFFICIENT_TIMEOUT) # give threads time to do their business
- assert(Array(threads).all? { |t| t.join(0.001).nil? })
- end
+ def assert_threads_stuck(threads)
+ sleep(SUFFICIENT_TIMEOUT) # give threads time to do their business
+ assert(Array(threads).all? { |t| t.join(0.001).nil? })
+ end
- def assert_threads_not_stuck(threads)
- assert(Array(threads).all? { |t| t.join(SUFFICIENT_TIMEOUT) })
+ def assert_threads_not_stuck(threads)
+ assert(Array(threads).all? { |t| t.join(SUFFICIENT_TIMEOUT) })
+ end
end
- end
- class CustomAssertionsTest < ActiveSupport::TestCase
- include CustomAssertions
+ class CustomAssertionsTest < ActiveSupport::TestCase
+ include CustomAssertions
- def setup
- @latch = Concurrent::CountDownLatch.new
- @thread = Thread.new { @latch.wait }
- end
+ def setup
+ @latch = Concurrent::CountDownLatch.new
+ @thread = Thread.new { @latch.wait }
+ end
- def teardown
- @latch.count_down
- @thread.join
- end
+ def teardown
+ @latch.count_down
+ @thread.join
+ end
- def test_happy_path
- assert_threads_stuck_but_releasable_by_latch @thread, @latch
- end
+ def test_happy_path
+ assert_threads_stuck_but_releasable_by_latch @thread, @latch
+ end
- def test_detects_stuck_thread
- assert_raises(Minitest::Assertion) do
- assert_threads_not_stuck @thread
+ def test_detects_stuck_thread
+ assert_raises(Minitest::Assertion) do
+ assert_threads_not_stuck @thread
+ end
end
- end
- def test_detects_free_thread
- @latch.count_down
- assert_raises(Minitest::Assertion) do
- assert_threads_stuck @thread
+ def test_detects_free_thread
+ @latch.count_down
+ assert_raises(Minitest::Assertion) do
+ assert_threads_stuck @thread
+ end
end
- end
- def test_detects_already_released
- @latch.count_down
- assert_raises(Minitest::Assertion) do
- assert_threads_stuck_but_releasable_by_latch @thread, @latch
+ def test_detects_already_released
+ @latch.count_down
+ assert_raises(Minitest::Assertion) do
+ assert_threads_stuck_but_releasable_by_latch @thread, @latch
+ end
end
- end
- def test_detects_remains_latched
- another_latch = Concurrent::CountDownLatch.new
- assert_raises(Minitest::Assertion) do
- assert_threads_stuck_but_releasable_by_latch @thread, another_latch
+ def test_detects_remains_latched
+ another_latch = Concurrent::CountDownLatch.new
+ assert_raises(Minitest::Assertion) do
+ assert_threads_stuck_but_releasable_by_latch @thread, another_latch
+ end
end
end
- end
- include CustomAssertions
+ include CustomAssertions
- def with_thread_waiting_in_lock_section(lock_section)
- in_section = Concurrent::CountDownLatch.new
- section_release = Concurrent::CountDownLatch.new
+ def with_thread_waiting_in_lock_section(lock_section)
+ in_section = Concurrent::CountDownLatch.new
+ section_release = Concurrent::CountDownLatch.new
- stuck_thread = Thread.new do
- @lock.send(lock_section) do
- in_section.count_down
- section_release.wait
+ stuck_thread = Thread.new do
+ @lock.send(lock_section) do
+ in_section.count_down
+ section_release.wait
+ end
end
- end
- in_section.wait
+ in_section.wait
- yield section_release
- ensure
- section_release.count_down
- stuck_thread.join # clean up
- end
+ yield section_release
+ ensure
+ section_release.count_down
+ stuck_thread.join # clean up
+ end
end
diff --git a/activesupport/test/string_inquirer_test.rb b/activesupport/test/string_inquirer_test.rb
index a2ed577eb0..bf8f878a32 100644
--- a/activesupport/test/string_inquirer_test.rb
+++ b/activesupport/test/string_inquirer_test.rb
@@ -1,8 +1,10 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class StringInquirerTest < ActiveSupport::TestCase
def setup
- @string_inquirer = ActiveSupport::StringInquirer.new('production')
+ @string_inquirer = ActiveSupport::StringInquirer.new("production")
end
def test_match
@@ -20,4 +22,25 @@ class StringInquirerTest < ActiveSupport::TestCase
def test_respond_to
assert_respond_to @string_inquirer, :development?
end
+
+ def test_respond_to_fallback_to_string_respond_to
+ String.class_eval do
+ def respond_to_missing?(name, include_private = false)
+ (name == :bar) || super
+ end
+ end
+ str = ActiveSupport::StringInquirer.new("hello")
+
+ assert_respond_to str, :are_you_ready?
+ assert_respond_to str, :bar
+ assert_not_respond_to str, :nope
+
+ ensure
+ String.class_eval do
+ undef_method :respond_to_missing?
+ def respond_to_missing?(name, include_private = false)
+ super
+ end
+ end
+ end
end
diff --git a/activesupport/test/subscriber_test.rb b/activesupport/test/subscriber_test.rb
index a88d8d9eba..6b012e43af 100644
--- a/activesupport/test/subscriber_test.rb
+++ b/activesupport/test/subscriber_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/subscriber'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/subscriber"
class TestSubscriber < ActiveSupport::Subscriber
attach_to :doodle
@@ -16,9 +18,9 @@ class TestSubscriber < ActiveSupport::Subscriber
private
- def private_party(event)
- events << event
- end
+ def private_party(event)
+ events << event
+ end
end
# Monkey patch subscriber to test that only one subscriber per method is added.
diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb
index 917fa46c96..5fd6a6b316 100644
--- a/activesupport/test/tagged_logging_test.rb
+++ b/activesupport/test/tagged_logging_test.rb
@@ -1,6 +1,8 @@
-require 'abstract_unit'
-require 'active_support/logger'
-require 'active_support/tagged_logging'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/logger"
+require "active_support/tagged_logging"
class TaggedLoggingTest < ActiveSupport::TestCase
class MyLogger < ::ActiveSupport::Logger
@@ -14,7 +16,7 @@ class TaggedLoggingTest < ActiveSupport::TestCase
@logger = ActiveSupport::TaggedLogging.new(MyLogger.new(@output))
end
- test 'sets logger.formatter if missing and extends it with a tagging API' do
+ test "sets logger.formatter if missing and extends it with a tagging API" do
logger = Logger.new(StringIO.new)
assert_nil logger.formatter
ActiveSupport::TaggedLogging.new(logger)
@@ -43,14 +45,14 @@ class TaggedLoggingTest < ActiveSupport::TestCase
end
test "push and pop tags directly" do
- assert_equal %w(A B C), @logger.push_tags('A', ['B', ' ', ['C']])
- @logger.info 'a'
+ assert_equal %w(A B C), @logger.push_tags("A", ["B", " ", ["C"]])
+ @logger.info "a"
assert_equal %w(C), @logger.pop_tags
- @logger.info 'b'
+ @logger.info "b"
assert_equal %w(B), @logger.pop_tags(1)
- @logger.info 'c'
+ @logger.info "c"
assert_equal [], @logger.clear_tags!
- @logger.info 'd'
+ @logger.info "d"
assert_equal "[A] [B] [C] a\n[A] [B] b\n[A] c\nd\n", @output.string
end
diff --git a/activesupport/test/test_case_test.rb b/activesupport/test/test_case_test.rb
index 18228a2ac5..79b75a001a 100644
--- a/activesupport/test/test_case_test.rb
+++ b/activesupport/test/test_case_test.rb
@@ -1,4 +1,6 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
class AssertDifferenceTest < ActiveSupport::TestCase
def setup
@@ -20,21 +22,21 @@ class AssertDifferenceTest < ActiveSupport::TestCase
assert_equal true, assert_not(false)
e = assert_raises(Minitest::Assertion) { assert_not true }
- assert_equal 'Expected true to be nil or false', e.message
+ assert_equal "Expected true to be nil or false", e.message
- e = assert_raises(Minitest::Assertion) { assert_not true, 'custom' }
- assert_equal 'custom', e.message
+ e = assert_raises(Minitest::Assertion) { assert_not true, "custom" }
+ assert_equal "custom", e.message
end
def test_assert_no_difference_pass
- assert_no_difference '@object.num' do
+ assert_no_difference "@object.num" do
# ...
end
end
def test_assert_no_difference_fail
error = assert_raises(Minitest::Assertion) do
- assert_no_difference '@object.num' do
+ assert_no_difference "@object.num" do
@object.increment
end
end
@@ -43,7 +45,7 @@ class AssertDifferenceTest < ActiveSupport::TestCase
def test_assert_no_difference_with_message_fail
error = assert_raises(Minitest::Assertion) do
- assert_no_difference '@object.num', 'Object Changed' do
+ assert_no_difference "@object.num", "Object Changed" do
@object.increment
end
end
@@ -51,13 +53,13 @@ class AssertDifferenceTest < ActiveSupport::TestCase
end
def test_assert_difference
- assert_difference '@object.num', +1 do
+ assert_difference "@object.num", +1 do
@object.increment
end
end
def test_assert_difference_retval
- incremented = assert_difference '@object.num', +1 do
+ incremented = assert_difference "@object.num", +1 do
@object.increment
end
@@ -65,40 +67,41 @@ class AssertDifferenceTest < ActiveSupport::TestCase
end
def test_assert_difference_with_implicit_difference
- assert_difference '@object.num' do
+ assert_difference "@object.num" do
@object.increment
end
end
def test_arbitrary_expression
- assert_difference '@object.num + 1', +2 do
+ assert_difference "@object.num + 1", +2 do
@object.increment
@object.increment
end
end
def test_negative_differences
- assert_difference '@object.num', -1 do
+ assert_difference "@object.num", -1 do
@object.decrement
end
end
def test_expression_is_evaluated_in_the_appropriate_scope
silence_warnings do
- local_scope = local_scope = 'foo'
- assert_difference('local_scope; @object.num') { @object.increment }
+ local_scope = "foo"
+ local_scope = local_scope # to suppress unused variable warning
+ assert_difference("local_scope; @object.num") { @object.increment }
end
end
def test_array_of_expressions
- assert_difference [ '@object.num', '@object.num + 1' ], +1 do
+ assert_difference [ "@object.num", "@object.num + 1" ], +1 do
@object.increment
end
end
def test_array_of_expressions_identify_failure
assert_raises(Minitest::Assertion) do
- assert_difference ['@object.num', '1 + 1'] do
+ assert_difference ["@object.num", "1 + 1"] do
@object.increment
end
end
@@ -106,14 +109,147 @@ class AssertDifferenceTest < ActiveSupport::TestCase
def test_array_of_expressions_identify_failure_when_message_provided
assert_raises(Minitest::Assertion) do
- assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do
+ assert_difference ["@object.num", "1 + 1"], 1, "something went wrong" do
+ @object.increment
+ end
+ end
+ end
+
+ def test_assert_changes_pass
+ assert_changes "@object.num" do
+ @object.increment
+ end
+ end
+
+ def test_assert_changes_pass_with_lambda
+ assert_changes -> { @object.num } do
+ @object.increment
+ end
+ end
+
+ def test_assert_changes_with_from_option
+ assert_changes "@object.num", from: 0 do
+ @object.increment
+ end
+ end
+
+ def test_assert_changes_with_from_option_with_wrong_value
+ assert_raises Minitest::Assertion do
+ assert_changes "@object.num", from: -1 do
+ @object.increment
+ end
+ end
+ end
+
+ def test_assert_changes_with_from_option_with_nil
+ error = assert_raises Minitest::Assertion do
+ assert_changes "@object.num", from: nil do
+ @object.increment
+ end
+ end
+ assert_equal "\"@object.num\" isn't nil", error.message
+ end
+
+ def test_assert_changes_with_to_option
+ assert_changes "@object.num", to: 1 do
+ @object.increment
+ end
+ end
+
+ def test_assert_changes_with_to_option_but_no_change_has_special_message
+ error = assert_raises Minitest::Assertion do
+ assert_changes "@object.num", to: 0 do
+ # no changes
+ end
+ end
+
+ assert_equal "\"@object.num\" didn't change. It was already 0", error.message
+ end
+
+ def test_assert_changes_with_wrong_to_option
+ assert_raises Minitest::Assertion do
+ assert_changes "@object.num", to: 2 do
@object.increment
end
end
end
-end
-class AlsoDoingNothingTest < ActiveSupport::TestCase
+ def test_assert_changes_with_from_option_and_to_option
+ assert_changes "@object.num", from: 0, to: 1 do
+ @object.increment
+ end
+ end
+
+ def test_assert_changes_with_from_and_to_options_and_wrong_to_value
+ assert_raises Minitest::Assertion do
+ assert_changes "@object.num", from: 0, to: 2 do
+ @object.increment
+ end
+ end
+ end
+
+ def test_assert_changes_works_with_any_object
+ # Silences: instance variable @new_object not initialized.
+ retval = silence_warnings do
+ assert_changes :@new_object, from: nil, to: 42 do
+ @new_object = 42
+ end
+ end
+
+ assert_equal 42, retval
+ end
+
+ def test_assert_changes_works_with_nil
+ oldval = @object
+
+ retval = assert_changes :@object, from: oldval, to: nil do
+ @object = nil
+ end
+
+ assert_nil retval
+ end
+
+ def test_assert_changes_with_to_and_case_operator
+ token = nil
+
+ assert_changes -> { token }, to: /\w{32}/ do
+ token = SecureRandom.hex
+ end
+ end
+
+ def test_assert_changes_with_to_and_from_and_case_operator
+ token = SecureRandom.hex
+
+ assert_changes -> { token }, from: /\w{32}/, to: /\w{32}/ do
+ token = SecureRandom.hex
+ end
+ end
+
+ def test_assert_changes_with_message
+ error = assert_raises Minitest::Assertion do
+ assert_changes "@object.num", "@object.num should 1", to: 1 do
+ @object.decrement
+ end
+ end
+
+ assert_equal "@object.num should 1.\n\"@object.num\" didn't change to 1", error.message
+ end
+
+ def test_assert_no_changes_pass
+ assert_no_changes "@object.num" do
+ # ...
+ end
+ end
+
+ def test_assert_no_changes_with_message
+ error = assert_raises Minitest::Assertion do
+ assert_no_changes "@object.num", "@object.num should not change" do
+ @object.increment
+ end
+ end
+
+ assert_equal "@object.num should not change.\n\"@object.num\" did change to 1", error.message
+ end
end
# Setup and teardown callbacks.
@@ -133,7 +269,7 @@ class SetupAndTeardownTest < ActiveSupport::TestCase
def teardown
end
- protected
+ private
def reset_callback_record
@called_back = []
@@ -158,7 +294,7 @@ class SubclassSetupAndTeardownTest < SetupAndTeardownTest
assert_equal [:foo, :sentinel, :bar], self.class._teardown_callbacks.map(&:raw_filter)
end
- protected
+ private
def bar
@called_back << :bar
end
@@ -170,7 +306,7 @@ end
class TestCaseTaggedLoggingTest < ActiveSupport::TestCase
def before_setup
- require 'stringio'
+ require "stringio"
@out = StringIO.new
self.tagged_logger = ActiveSupport::TaggedLogging.new(Logger.new(@out))
super
diff --git a/activesupport/test/testing/constant_lookup_test.rb b/activesupport/test/testing/constant_lookup_test.rb
index 0f16419c8b..37b7822950 100644
--- a/activesupport/test/testing/constant_lookup_test.rb
+++ b/activesupport/test/testing/constant_lookup_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'dependencies_test_helpers'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "dependencies_test_helpers"
class Foo; end
class Bar < Foo
@@ -69,7 +71,7 @@ class ConstantLookupTest < ActiveSupport::TestCase
def test_does_not_swallow_exception_on_no_name_error_within_constant
assert_raises(NameError) do
with_autoloading_fixtures do
- self.class.determine_constant_from_test_name('RaisesNameError')
+ self.class.determine_constant_from_test_name("RaisesNameError")
end
end
end
diff --git a/activesupport/test/testing/file_fixtures_test.rb b/activesupport/test/testing/file_fixtures_test.rb
index 91b8a9071c..35be8f5206 100644
--- a/activesupport/test/testing/file_fixtures_test.rb
+++ b/activesupport/test/testing/file_fixtures_test.rb
@@ -1,12 +1,16 @@
-require 'abstract_unit'
+# frozen_string_literal: true
+
+require "abstract_unit"
+
+require "pathname"
class FileFixturesTest < ActiveSupport::TestCase
- self.file_fixture_path = File.expand_path("../../file_fixtures", __FILE__)
+ self.file_fixture_path = File.expand_path("../file_fixtures", __dir__)
test "#file_fixture returns Pathname to file fixture" do
path = file_fixture("sample.txt")
assert_kind_of Pathname, path
- assert_match %r{activesupport/test/file_fixtures/sample.txt$}, path.to_s
+ assert_match %r{.*/test/file_fixtures/sample\.txt$}, path.to_s
end
test "raises an exception when the fixture file does not exist" do
@@ -18,11 +22,11 @@ class FileFixturesTest < ActiveSupport::TestCase
end
class FileFixturesPathnameDirectoryTest < ActiveSupport::TestCase
- self.file_fixture_path = Pathname.new(File.expand_path("../../file_fixtures", __FILE__))
+ self.file_fixture_path = Pathname.new(File.expand_path("../file_fixtures", __dir__))
test "#file_fixture_path returns Pathname to file fixture" do
path = file_fixture("sample.txt")
assert_kind_of Pathname, path
- assert_match %r{activesupport/test/file_fixtures/sample.txt$}, path.to_s
+ assert_match %r{.*/test/file_fixtures/sample\.txt$}, path.to_s
end
end
diff --git a/activesupport/test/testing/method_call_assertions_test.rb b/activesupport/test/testing/method_call_assertions_test.rb
index 3e5ba7c079..4af000bb7e 100644
--- a/activesupport/test/testing/method_call_assertions_test.rb
+++ b/activesupport/test/testing/method_call_assertions_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/testing/method_call_assertions'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/testing/method_call_assertions"
class MethodCallAssertionsTest < ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions
@@ -51,7 +53,7 @@ class MethodCallAssertionsTest < ActiveSupport::TestCase
def test_assert_called_with_message
error = assert_raises(Minitest::Assertion) do
- assert_called(@object, :increment, 'dang it') do
+ assert_called(@object, :increment, "dang it") do
# Call nothing...
end
end
diff --git a/activesupport/test/time_travel_test.rb b/activesupport/test/time_travel_test.rb
index 59c3e52c2f..9c2c635f43 100644
--- a/activesupport/test/time_travel_test.rb
+++ b/activesupport/test/time_travel_test.rb
@@ -1,20 +1,26 @@
-require 'abstract_unit'
-require 'active_support/core_ext/date_time'
-require 'active_support/core_ext/numeric/time'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/core_ext/date_time"
+require "active_support/core_ext/numeric/time"
class TimeTravelTest < ActiveSupport::TestCase
- teardown do
- travel_back
- end
+ class TimeSubclass < ::Time; end
+ class DateSubclass < ::Date; end
+ class DateTimeSubclass < ::DateTime; end
def test_time_helper_travel
Time.stub(:now, Time.now) do
- expected_time = Time.now + 1.day
- travel 1.day
+ begin
+ expected_time = Time.now + 1.day
+ travel 1.day
- assert_equal expected_time.to_s(:db), Time.now.to_s(:db)
- assert_equal expected_time.to_date, Date.today
- assert_equal expected_time.to_datetime.to_s(:db), DateTime.now.to_s(:db)
+ assert_equal expected_time.to_s(:db), Time.now.to_s(:db)
+ assert_equal expected_time.to_date, Date.today
+ assert_equal expected_time.to_datetime.to_s(:db), DateTime.now.to_s(:db)
+ ensure
+ travel_back
+ end
end
end
@@ -36,12 +42,16 @@ class TimeTravelTest < ActiveSupport::TestCase
def test_time_helper_travel_to
Time.stub(:now, Time.now) do
- expected_time = Time.new(2004, 11, 24, 01, 04, 44)
- travel_to expected_time
+ begin
+ expected_time = Time.new(2004, 11, 24, 01, 04, 44)
+ travel_to expected_time
- assert_equal expected_time, Time.now
- assert_equal Date.new(2004, 11, 24), Date.today
- assert_equal expected_time.to_datetime, DateTime.now
+ assert_equal expected_time, Time.now
+ assert_equal Date.new(2004, 11, 24), Date.today
+ assert_equal expected_time.to_datetime, DateTime.now
+ ensure
+ travel_back
+ end
end
end
@@ -63,17 +73,69 @@ class TimeTravelTest < ActiveSupport::TestCase
def test_time_helper_travel_back
Time.stub(:now, Time.now) do
- expected_time = Time.new(2004, 11, 24, 01, 04, 44)
+ begin
+ expected_time = Time.new(2004, 11, 24, 01, 04, 44)
- travel_to expected_time
- assert_equal expected_time, Time.now
- assert_equal Date.new(2004, 11, 24), Date.today
- assert_equal expected_time.to_datetime, DateTime.now
- travel_back
+ travel_to expected_time
+ assert_equal expected_time, Time.now
+ assert_equal Date.new(2004, 11, 24), Date.today
+ assert_equal expected_time.to_datetime, DateTime.now
+ travel_back
- assert_not_equal expected_time, Time.now
- assert_not_equal Date.new(2004, 11, 24), Date.today
- assert_not_equal expected_time.to_datetime, DateTime.now
+ assert_not_equal expected_time, Time.now
+ assert_not_equal Date.new(2004, 11, 24), Date.today
+ assert_not_equal expected_time.to_datetime, DateTime.now
+ ensure
+ travel_back
+ end
+ end
+ end
+
+ def test_time_helper_travel_to_with_nested_calls_with_blocks
+ Time.stub(:now, Time.now) do
+ outer_expected_time = Time.new(2004, 11, 24, 01, 04, 44)
+ inner_expected_time = Time.new(2004, 10, 24, 01, 04, 44)
+ travel_to outer_expected_time do
+ e = assert_raises(RuntimeError) do
+ travel_to(inner_expected_time) do
+ # noop
+ end
+ end
+ assert_match(/Calling `travel_to` with a block, when we have previously already made a call to `travel_to`, can lead to confusing time stubbing\./, e.message)
+ end
+ end
+ end
+
+ def test_time_helper_travel_to_with_nested_calls
+ Time.stub(:now, Time.now) do
+ outer_expected_time = Time.new(2004, 11, 24, 01, 04, 44)
+ inner_expected_time = Time.new(2004, 10, 24, 01, 04, 44)
+ travel_to outer_expected_time do
+ assert_nothing_raised do
+ travel_to(inner_expected_time)
+
+ assert_equal inner_expected_time, Time.now
+ end
+ end
+ end
+ end
+
+ def test_time_helper_travel_to_with_subsequent_calls
+ Time.stub(:now, Time.now) do
+ begin
+ initial_expected_time = Time.new(2004, 11, 24, 01, 04, 44)
+ subsequent_expected_time = Time.new(2004, 10, 24, 01, 04, 44)
+ assert_nothing_raised do
+ travel_to initial_expected_time
+ travel_to subsequent_expected_time
+
+ assert_equal subsequent_expected_time, Time.now
+
+ travel_back
+ end
+ ensure
+ travel_back
+ end
end
end
@@ -87,4 +149,41 @@ class TimeTravelTest < ActiveSupport::TestCase
end
end
end
+
+ def test_time_helper_travel_with_time_subclass
+ assert_equal TimeSubclass, TimeSubclass.now.class
+ assert_equal DateSubclass, DateSubclass.today.class
+ assert_equal DateTimeSubclass, DateTimeSubclass.now.class
+
+ travel 1.day do
+ assert_equal TimeSubclass, TimeSubclass.now.class
+ assert_equal DateSubclass, DateSubclass.today.class
+ assert_equal DateTimeSubclass, DateTimeSubclass.now.class
+ assert_equal Time.now.to_s, TimeSubclass.now.to_s
+ assert_equal Date.today.to_s, DateSubclass.today.to_s
+ assert_equal DateTime.now.to_s, DateTimeSubclass.now.to_s
+ end
+ end
+
+ def test_time_helper_freeze_time
+ expected_time = Time.now
+ freeze_time
+ sleep(1)
+
+ assert_equal expected_time.to_s(:db), Time.now.to_s(:db)
+ ensure
+ travel_back
+ end
+
+ def test_time_helper_freeze_time_with_block
+ expected_time = Time.now
+
+ freeze_time do
+ sleep(1)
+
+ assert_equal expected_time.to_s(:db), Time.now.to_s(:db)
+ end
+
+ assert_operator expected_time.to_s(:db), :<, Time.now.to_s(:db)
+ end
end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index a15d5c6a0e..405c8f315b 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -1,25 +1,27 @@
-require 'abstract_unit'
-require 'active_support/time'
-require 'time_zone_test_helpers'
-require 'yaml'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/time"
+require "time_zone_test_helpers"
+require "yaml"
class TimeZoneTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
def test_utc_to_local
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
assert_equal Time.utc(1999, 12, 31, 19), zone.utc_to_local(Time.utc(2000, 1)) # standard offset -0500
assert_equal Time.utc(2000, 6, 30, 20), zone.utc_to_local(Time.utc(2000, 7)) # dst offset -0400
end
def test_local_to_utc
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
assert_equal Time.utc(2000, 1, 1, 5), zone.local_to_utc(Time.utc(2000, 1)) # standard offset -0500
assert_equal Time.utc(2000, 7, 1, 4), zone.local_to_utc(Time.utc(2000, 7)) # dst offset -0400
end
def test_period_for_local
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
assert_instance_of TZInfo::TimezonePeriod, zone.period_for_local(Time.utc(2000))
end
@@ -30,6 +32,12 @@ class TimeZoneTest < ActiveSupport::TestCase
end
end
+ def test_period_for_local_with_ambigiuous_time
+ zone = ActiveSupport::TimeZone["Moscow"]
+ period = zone.period_for_local(Time.utc(2015, 1, 1))
+ assert_equal period, zone.period_for_local(Time.utc(2014, 10, 26, 1, 0, 0))
+ end
+
def test_from_integer_to_map
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[-28800] # PST
end
@@ -39,7 +47,7 @@ class TimeZoneTest < ActiveSupport::TestCase
end
ActiveSupport::TimeZone.all.each do |zone|
- name = zone.name.downcase.gsub(/[^a-z]/, '_')
+ name = zone.name.downcase.gsub(/[^a-z]/, "_")
define_method("test_from_#{name}_to_map") do
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[zone.name]
end
@@ -51,86 +59,83 @@ class TimeZoneTest < ActiveSupport::TestCase
end
def test_now
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"].dup
def zone.time_now; Time.local(2000); end
assert_instance_of ActiveSupport::TimeWithZone, zone.now
- assert_equal Time.utc(2000,1,1,5), zone.now.utc
+ assert_equal Time.utc(2000, 1, 1, 5), zone.now.utc
assert_equal Time.utc(2000), zone.now.time
assert_equal zone, zone.now.time_zone
end
end
def test_now_enforces_spring_dst_rules
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"].dup
def zone.time_now
- Time.local(2006,4,2,2) # 2AM springs forward to 3AM
+ Time.local(2006, 4, 2, 2) # 2AM springs forward to 3AM
end
- assert_equal Time.utc(2006,4,2,3), zone.now.time
+ assert_equal Time.utc(2006, 4, 2, 3), zone.now.time
assert_equal true, zone.now.dst?
end
end
def test_now_enforces_fall_dst_rules
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"].dup
def zone.time_now
Time.at(1162098000) # equivalent to 1AM DST
end
- assert_equal Time.utc(2006,10,29,1), zone.now.time
+ assert_equal Time.utc(2006, 10, 29, 1), zone.now.time
assert_equal true, zone.now.dst?
end
end
def test_unknown_timezones_delegation_to_tzinfo
- zone = ActiveSupport::TimeZone['America/Montevideo']
+ zone = ActiveSupport::TimeZone["America/Montevideo"]
assert_equal ActiveSupport::TimeZone, zone.class
- assert_equal zone.object_id, ActiveSupport::TimeZone['America/Montevideo'].object_id
+ assert_equal zone.object_id, ActiveSupport::TimeZone["America/Montevideo"].object_id
assert_equal Time.utc(2010, 1, 31, 22), zone.utc_to_local(Time.utc(2010, 2)) # daylight saving offset -0200
assert_equal Time.utc(2010, 3, 31, 21), zone.utc_to_local(Time.utc(2010, 4)) # standard offset -0300
end
def test_today
travel_to(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
- assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].today
travel_to(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].today
travel_to(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].today
travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
- travel_back
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].today
end
def test_tomorrow
travel_to(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].tomorrow
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].tomorrow
travel_to(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
- assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].tomorrow
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].tomorrow
travel_to(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].tomorrow
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].tomorrow
travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 3), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].tomorrow
- travel_back
+ assert_equal Date.new(2000, 1, 3), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].tomorrow
end
def test_yesterday
travel_to(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
- assert_equal Date.new(1999, 12, 30), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].yesterday
+ assert_equal Date.new(1999, 12, 30), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].yesterday
travel_to(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
- assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].yesterday
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].yesterday
travel_to(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
- assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].yesterday
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].yesterday
travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].yesterday
- travel_back
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].yesterday
end
def test_travel_to_a_date
with_env_tz do
- Time.use_zone('Hawaii') do
+ Time.use_zone("Hawaii") do
date = Date.new(2014, 2, 18)
time = date.midnight
@@ -162,52 +167,57 @@ class TimeZoneTest < ActiveSupport::TestCase
def test_local_with_old_date
time = ActiveSupport::TimeZone["Hawaii"].local(1850, 2, 5, 15, 30, 45)
- assert_equal [45,30,15,5,2,1850], time.to_a[0,6]
+ assert_equal [45, 30, 15, 5, 2, 1850], time.to_a[0, 6]
assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
end
def test_local_enforces_spring_dst_rules
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.local(2006,4,2,1,59,59) # 1 second before DST start
- assert_equal Time.utc(2006,4,2,1,59,59), twz.time
- assert_equal Time.utc(2006,4,2,6,59,59), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.local(2006, 4, 2, 1, 59, 59) # 1 second before DST start
+ assert_equal Time.utc(2006, 4, 2, 1, 59, 59), twz.time
+ assert_equal Time.utc(2006, 4, 2, 6, 59, 59), twz.utc
assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
- twz2 = zone.local(2006,4,2,2) # 2AM does not exist because at 2AM, time springs forward to 3AM
- assert_equal Time.utc(2006,4,2,3), twz2.time # twz is created for 3AM
- assert_equal Time.utc(2006,4,2,7), twz2.utc
+ assert_equal "EST", twz.zone
+ twz2 = zone.local(2006, 4, 2, 2) # 2AM does not exist because at 2AM, time springs forward to 3AM
+ assert_equal Time.utc(2006, 4, 2, 3), twz2.time # twz is created for 3AM
+ assert_equal Time.utc(2006, 4, 2, 7), twz2.utc
assert_equal true, twz2.dst?
- assert_equal 'EDT', twz2.zone
- twz3 = zone.local(2006,4,2,2,30) # 2:30AM does not exist because at 2AM, time springs forward to 3AM
- assert_equal Time.utc(2006,4,2,3,30), twz3.time # twz is created for 3:30AM
- assert_equal Time.utc(2006,4,2,7,30), twz3.utc
+ assert_equal "EDT", twz2.zone
+ twz3 = zone.local(2006, 4, 2, 2, 30) # 2:30AM does not exist because at 2AM, time springs forward to 3AM
+ assert_equal Time.utc(2006, 4, 2, 3, 30), twz3.time # twz is created for 3:30AM
+ assert_equal Time.utc(2006, 4, 2, 7, 30), twz3.utc
assert_equal true, twz3.dst?
- assert_equal 'EDT', twz3.zone
+ assert_equal "EDT", twz3.zone
end
def test_local_enforces_fall_dst_rules
# 1AM during fall DST transition is ambiguous, it could be either DST or non-DST 1AM
# Mirroring Time.local behavior, this method selects the DST time
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.local(2006,10,29,1)
- assert_equal Time.utc(2006,10,29,1), twz.time
- assert_equal Time.utc(2006,10,29,5), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.local(2006, 10, 29, 1)
+ assert_equal Time.utc(2006, 10, 29, 1), twz.time
+ assert_equal Time.utc(2006, 10, 29, 5), twz.utc
assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
+ assert_equal "EDT", twz.zone
+ end
+
+ def test_local_with_ambiguous_time
+ zone = ActiveSupport::TimeZone["Moscow"]
+ assert_equal Time.utc(2014, 10, 25, 22, 0, 0), zone.local(2014, 10, 26, 1, 0, 0)
end
def test_at
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
secs = 946684800.0
twz = zone.at(secs)
- assert_equal Time.utc(1999,12,31,19), twz.time
+ assert_equal Time.utc(1999, 12, 31, 19), twz.time
assert_equal Time.utc(2000), twz.utc
assert_equal zone, twz.time_zone
assert_equal secs, twz.to_f
end
def test_at_with_old_date
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
secs = DateTime.civil(1850).to_f
twz = zone.at(secs)
assert_equal [1850, 1, 1, 0], [twz.utc.year, twz.utc.mon, twz.utc.day, twz.utc.hour]
@@ -215,10 +225,104 @@ class TimeZoneTest < ActiveSupport::TestCase
assert_equal secs, twz.to_f
end
+ def test_iso8601
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("1999-12-31T19:00:00")
+ assert_equal Time.utc(1999, 12, 31, 19), twz.time
+ assert_equal Time.utc(2000), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_iso8601_with_fractional_seconds
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("1999-12-31T19:00:00.750")
+ assert_equal 750000, twz.time.usec
+ assert_equal Time.utc(1999, 12, 31, 19, 0, 0 + Rational(3, 4)), twz.time
+ assert_equal Time.utc(2000, 1, 1, 0, 0, 0 + Rational(3, 4)), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_iso8601_with_zone
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("1999-12-31T14:00:00-10:00")
+ assert_equal Time.utc(1999, 12, 31, 19), twz.time
+ assert_equal Time.utc(2000), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_iso8601_with_invalid_string
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+
+ exception = assert_raises(ArgumentError) do
+ zone.iso8601("foobar")
+ end
+
+ assert_equal "invalid date", exception.message
+ end
+
+ def test_iso8601_with_missing_time_components
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("1999-12-31")
+ assert_equal Time.utc(1999, 12, 31, 0, 0, 0), twz.time
+ assert_equal Time.utc(1999, 12, 31, 5, 0, 0), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_iso8601_with_old_date
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("1883-12-31T19:00:00")
+ assert_equal [0, 0, 19, 31, 12, 1883], twz.to_a[0, 6]
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_iso8601_far_future_date_with_time_zone_offset_in_string
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("2050-12-31T19:00:00-10:00") # i.e., 2050-01-01 05:00:00 UTC
+ assert_equal [0, 0, 0, 1, 1, 2051], twz.to_a[0, 6]
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_iso8601_should_not_black_out_system_timezone_dst_jump
+ with_env_tz("EET") do
+ zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ twz = zone.iso8601("2012-03-25T03:29:00")
+ assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0, 6]
+ end
+ end
+
+ def test_iso8601_should_black_out_app_timezone_dst_jump
+ with_env_tz("EET") do
+ zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ twz = zone.iso8601("2012-03-11T02:29:00")
+ assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0, 6]
+ end
+ end
+
+ def test_iso8601_doesnt_use_local_dst
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["UTC"]
+ twz = zone.iso8601("2013-03-10T02:00:00")
+ assert_equal Time.utc(2013, 3, 10, 2, 0, 0), twz.time
+ end
+ end
+
+ def test_iso8601_handles_dst_jump
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("2013-03-10T02:00:00")
+ assert_equal Time.utc(2013, 3, 10, 3, 0, 0), twz.time
+ end
+ end
+
+ def test_iso8601_with_ambiguous_time
+ zone = ActiveSupport::TimeZone["Moscow"]
+ assert_equal Time.utc(2014, 10, 25, 22, 0, 0), zone.parse("2014-10-26T01:00:00")
+ end
+
def test_parse
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.parse('1999-12-31 19:00:00')
- assert_equal Time.utc(1999,12,31,19), twz.time
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.parse("1999-12-31 19:00:00")
+ assert_equal Time.utc(1999, 12, 31, 19), twz.time
assert_equal Time.utc(2000), twz.utc
assert_equal zone, twz.time_zone
end
@@ -226,183 +330,321 @@ class TimeZoneTest < ActiveSupport::TestCase
def test_parse_string_with_timezone
(-11..13).each do |timezone_offset|
zone = ActiveSupport::TimeZone[timezone_offset]
- twz = zone.parse('1999-12-31 19:00:00')
+ twz = zone.parse("1999-12-31 19:00:00")
assert_equal twz, zone.parse(twz.to_s)
end
end
def test_parse_with_old_date
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.parse('1883-12-31 19:00:00')
- assert_equal [0,0,19,31,12,1883], twz.to_a[0,6]
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.parse("1883-12-31 19:00:00")
+ assert_equal [0, 0, 19, 31, 12, 1883], twz.to_a[0, 6]
assert_equal zone, twz.time_zone
end
def test_parse_far_future_date_with_time_zone_offset_in_string
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.parse('2050-12-31 19:00:00 -10:00') # i.e., 2050-01-01 05:00:00 UTC
- assert_equal [0,0,0,1,1,2051], twz.to_a[0,6]
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.parse("2050-12-31 19:00:00 -10:00") # i.e., 2050-01-01 05:00:00 UTC
+ assert_equal [0, 0, 0, 1, 1, 2051], twz.to_a[0, 6]
assert_equal zone, twz.time_zone
end
def test_parse_returns_nil_when_string_without_date_information_is_passed_in
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_nil zone.parse('foobar')
- assert_nil zone.parse(' ')
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ assert_nil zone.parse("foobar")
+ assert_nil zone.parse(" ")
end
def test_parse_with_incomplete_date
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- zone.stub(:now, zone.local(1999,12,31)) do
- twz = zone.parse('19:00:00')
- assert_equal Time.utc(1999,12,31,19), twz.time
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ zone.stub(:now, zone.local(1999, 12, 31)) do
+ twz = zone.parse("19:00:00")
+ assert_equal Time.utc(1999, 12, 31, 19), twz.time
end
end
def test_parse_with_day_omitted
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_equal Time.local(2000, 2, 1), zone.parse('Feb', Time.local(2000, 1, 1))
- assert_equal Time.local(2005, 2, 1), zone.parse('Feb 2005', Time.local(2000, 1, 1))
- assert_equal Time.local(2005, 2, 2), zone.parse('2 Feb 2005', Time.local(2000, 1, 1))
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ assert_equal Time.local(2000, 2, 1), zone.parse("Feb", Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 1), zone.parse("Feb 2005", Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 2), zone.parse("2 Feb 2005", Time.local(2000, 1, 1))
end
end
def test_parse_should_not_black_out_system_timezone_dst_jump
- with_env_tz('EET') do
- zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)']
- twz = zone.parse('2012-03-25 03:29:00')
- assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0,6]
+ with_env_tz("EET") do
+ zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ twz = zone.parse("2012-03-25 03:29:00")
+ assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0, 6]
end
end
def test_parse_should_black_out_app_timezone_dst_jump
- with_env_tz('EET') do
- zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)']
- twz = zone.parse('2012-03-11 02:29:00')
- assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0,6]
+ with_env_tz("EET") do
+ zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ twz = zone.parse("2012-03-11 02:29:00")
+ assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0, 6]
end
end
def test_parse_with_missing_time_components
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
zone.stub(:now, zone.local(1999, 12, 31, 12, 59, 59)) do
- twz = zone.parse('2012-12-01')
+ twz = zone.parse("2012-12-01")
assert_equal Time.utc(2012, 12, 1), twz.time
end
end
def test_parse_with_javascript_date
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
twz = zone.parse("Mon May 28 2012 00:00:00 GMT-0700 (PDT)")
assert_equal Time.utc(2012, 5, 28, 7, 0, 0), twz.utc
end
def test_parse_doesnt_use_local_dst
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['UTC']
- twz = zone.parse('2013-03-10 02:00:00')
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["UTC"]
+ twz = zone.parse("2013-03-10 02:00:00")
assert_equal Time.utc(2013, 3, 10, 2, 0, 0), twz.time
end
end
def test_parse_handles_dst_jump
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.parse('2013-03-10 02:00:00')
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.parse("2013-03-10 02:00:00")
+ assert_equal Time.utc(2013, 3, 10, 3, 0, 0), twz.time
+ end
+ end
+
+ def test_parse_with_invalid_date
+ zone = ActiveSupport::TimeZone["UTC"]
+
+ exception = assert_raises(ArgumentError) do
+ zone.parse("9000")
+ end
+
+ assert_equal "argument out of range", exception.message
+ end
+
+ def test_parse_with_ambiguous_time
+ zone = ActiveSupport::TimeZone["Moscow"]
+ assert_equal Time.utc(2014, 10, 25, 22, 0, 0), zone.parse("2014-10-26 01:00:00")
+ end
+
+ def test_rfc3339
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.rfc3339("1999-12-31T14:00:00-10:00")
+ assert_equal Time.utc(1999, 12, 31, 19), twz.time
+ assert_equal Time.utc(2000), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_rfc3339_with_fractional_seconds
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("1999-12-31T14:00:00.750-10:00")
+ assert_equal 750000, twz.time.usec
+ assert_equal Time.utc(1999, 12, 31, 19, 0, 0 + Rational(3, 4)), twz.time
+ assert_equal Time.utc(2000, 1, 1, 0, 0, 0 + Rational(3, 4)), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_rfc3339_with_missing_time
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+
+ exception = assert_raises(ArgumentError) do
+ zone.rfc3339("1999-12-31")
+ end
+
+ assert_equal "invalid date", exception.message
+ end
+
+ def test_rfc3339_with_missing_offset
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+
+ exception = assert_raises(ArgumentError) do
+ zone.rfc3339("1999-12-31T19:00:00")
+ end
+
+ assert_equal "invalid date", exception.message
+ end
+
+ def test_rfc3339_with_invalid_string
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+
+ exception = assert_raises(ArgumentError) do
+ zone.rfc3339("foobar")
+ end
+
+ assert_equal "invalid date", exception.message
+ end
+
+ def test_rfc3339_with_old_date
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.rfc3339("1883-12-31T19:00:00-05:00")
+ assert_equal [0, 0, 19, 31, 12, 1883], twz.to_a[0, 6]
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_rfc3339_far_future_date_with_time_zone_offset_in_string
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.rfc3339("2050-12-31T19:00:00-10:00") # i.e., 2050-01-01 05:00:00 UTC
+ assert_equal [0, 0, 0, 1, 1, 2051], twz.to_a[0, 6]
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_rfc3339_should_not_black_out_system_timezone_dst_jump
+ with_env_tz("EET") do
+ zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ twz = zone.rfc3339("2012-03-25T03:29:00-07:00")
+ assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0, 6]
+ end
+ end
+
+ def test_rfc3339_should_black_out_app_timezone_dst_jump
+ with_env_tz("EET") do
+ zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ twz = zone.rfc3339("2012-03-11T02:29:00-08:00")
+ assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0, 6]
+ end
+ end
+
+ def test_rfc3339_doesnt_use_local_dst
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["UTC"]
+ twz = zone.rfc3339("2013-03-10T02:00:00Z")
+ assert_equal Time.utc(2013, 3, 10, 2, 0, 0), twz.time
+ end
+ end
+
+ def test_rfc3339_handles_dst_jump
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.iso8601("2013-03-10T02:00:00-05:00")
assert_equal Time.utc(2013, 3, 10, 3, 0, 0), twz.time
end
end
def test_strptime
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00', '%Y-%m-%d %H:%M:%S')
- assert_equal Time.utc(1999,12,31,17), twz
- assert_equal Time.utc(1999,12,31,12), twz.time
- assert_equal Time.utc(1999,12,31,17), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00", "%Y-%m-%d %H:%M:%S")
+ assert_equal Time.utc(1999, 12, 31, 17), twz
+ assert_equal Time.utc(1999, 12, 31, 12), twz.time
+ assert_equal Time.utc(1999, 12, 31, 17), twz.utc
assert_equal zone, twz.time_zone
end
def test_strptime_with_nondefault_time_zone
- with_tz_default ActiveSupport::TimeZone['Pacific Time (US & Canada)'] do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00', '%Y-%m-%d %H:%M:%S')
- assert_equal Time.utc(1999,12,31,17), twz
- assert_equal Time.utc(1999,12,31,12), twz.time
- assert_equal Time.utc(1999,12,31,17), twz.utc
+ with_tz_default ActiveSupport::TimeZone["Pacific Time (US & Canada)"] do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00", "%Y-%m-%d %H:%M:%S")
+ assert_equal Time.utc(1999, 12, 31, 17), twz
+ assert_equal Time.utc(1999, 12, 31, 12), twz.time
+ assert_equal Time.utc(1999, 12, 31, 17), twz.utc
assert_equal zone, twz.time_zone
end
end
def test_strptime_with_explicit_time_zone_as_abbrev
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00 PST', '%Y-%m-%d %H:%M:%S %Z')
- assert_equal Time.utc(1999,12,31,20), twz
- assert_equal Time.utc(1999,12,31,15), twz.time
- assert_equal Time.utc(1999,12,31,20), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00 PST", "%Y-%m-%d %H:%M:%S %Z")
+ assert_equal Time.utc(1999, 12, 31, 20), twz
+ assert_equal Time.utc(1999, 12, 31, 15), twz.time
+ assert_equal Time.utc(1999, 12, 31, 20), twz.utc
assert_equal zone, twz.time_zone
end
def test_strptime_with_explicit_time_zone_as_h_offset
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00 -08', '%Y-%m-%d %H:%M:%S %:::z')
- assert_equal Time.utc(1999,12,31,20), twz
- assert_equal Time.utc(1999,12,31,15), twz.time
- assert_equal Time.utc(1999,12,31,20), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00 -08", "%Y-%m-%d %H:%M:%S %:::z")
+ assert_equal Time.utc(1999, 12, 31, 20), twz
+ assert_equal Time.utc(1999, 12, 31, 15), twz.time
+ assert_equal Time.utc(1999, 12, 31, 20), twz.utc
assert_equal zone, twz.time_zone
end
def test_strptime_with_explicit_time_zone_as_hm_offset
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00 -08:00', '%Y-%m-%d %H:%M:%S %:z')
- assert_equal Time.utc(1999,12,31,20), twz
- assert_equal Time.utc(1999,12,31,15), twz.time
- assert_equal Time.utc(1999,12,31,20), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00 -08:00", "%Y-%m-%d %H:%M:%S %:z")
+ assert_equal Time.utc(1999, 12, 31, 20), twz
+ assert_equal Time.utc(1999, 12, 31, 15), twz.time
+ assert_equal Time.utc(1999, 12, 31, 20), twz.utc
assert_equal zone, twz.time_zone
end
def test_strptime_with_explicit_time_zone_as_hms_offset
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00 -08:00:00', '%Y-%m-%d %H:%M:%S %::z')
- assert_equal Time.utc(1999,12,31,20), twz
- assert_equal Time.utc(1999,12,31,15), twz.time
- assert_equal Time.utc(1999,12,31,20), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00 -08:00:00", "%Y-%m-%d %H:%M:%S %::z")
+ assert_equal Time.utc(1999, 12, 31, 20), twz
+ assert_equal Time.utc(1999, 12, 31, 15), twz.time
+ assert_equal Time.utc(1999, 12, 31, 20), twz.utc
assert_equal zone, twz.time_zone
end
def test_strptime_with_almost_explicit_time_zone
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.strptime('1999-12-31 12:00:00 %Z', '%Y-%m-%d %H:%M:%S %%Z')
- assert_equal Time.utc(1999,12,31,17), twz
- assert_equal Time.utc(1999,12,31,12), twz.time
- assert_equal Time.utc(1999,12,31,17), twz.utc
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ twz = zone.strptime("1999-12-31 12:00:00 %Z", "%Y-%m-%d %H:%M:%S %%Z")
+ assert_equal Time.utc(1999, 12, 31, 17), twz
+ assert_equal Time.utc(1999, 12, 31, 12), twz.time
+ assert_equal Time.utc(1999, 12, 31, 17), twz.utc
assert_equal zone, twz.time_zone
end
def test_strptime_with_day_omitted
- with_env_tz 'US/Eastern' do
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_equal Time.local(2000, 2, 1), zone.strptime('Feb', '%b', Time.local(2000, 1, 1))
- assert_equal Time.local(2005, 2, 1), zone.strptime('Feb 2005', '%b %Y', Time.local(2000, 1, 1))
- assert_equal Time.local(2005, 2, 2), zone.strptime('2 Feb 2005', '%e %b %Y', Time.local(2000, 1, 1))
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ assert_equal Time.local(2000, 2, 1), zone.strptime("Feb", "%b", Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 1), zone.strptime("Feb 2005", "%b %Y", Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 2), zone.strptime("2 Feb 2005", "%e %b %Y", Time.local(2000, 1, 1))
end
end
+ def test_strptime_with_malformed_string
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ assert_raise(ArgumentError) { zone.strptime("1999-12-31", "%Y/%m/%d") }
+ end
+ end
+
+ def test_strptime_with_timestamp_seconds
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ time_str = "1470272280"
+ time = zone.strptime(time_str, "%s")
+ assert_equal Time.at(1470272280), time
+ end
+ end
+
+ def test_strptime_with_timestamp_milliseconds
+ with_env_tz "US/Eastern" do
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
+ time_str = "1470272280000"
+ time = zone.strptime(time_str, "%Q")
+ assert_equal Time.at(1470272280), time
+ end
+ end
+
+ def test_strptime_with_ambiguous_time
+ zone = ActiveSupport::TimeZone["Moscow"]
+ assert_equal Time.utc(2014, 10, 25, 22, 0, 0), zone.strptime("2014-10-26 01:00:00", "%Y-%m-%d %H:%M:%S")
+ end
+
def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
- tzinfo = TZInfo::Timezone.get('America/New_York')
+ tzinfo = TZInfo::Timezone.get("America/New_York")
zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
- assert_equal nil, zone.instance_variable_get('@utc_offset')
+ assert_nil zone.instance_variable_get("@utc_offset")
assert_equal(-18_000, zone.utc_offset)
end
def test_utc_offset_is_not_cached_when_current_period_gets_stale
- tz = ActiveSupport::TimeZone.create('Moscow')
+ tz = ActiveSupport::TimeZone.create("Moscow")
travel_to(Time.utc(2014, 10, 25, 21)) do # 1 hour before TZ change
- assert_equal 14400, tz.utc_offset, 'utc_offset should be initialized according to current_period'
+ assert_equal 14400, tz.utc_offset, "utc_offset should be initialized according to current_period"
end
travel_to(Time.utc(2014, 10, 25, 22)) do # after TZ change
- assert_equal 10800, tz.utc_offset, 'utc_offset should not be cached when current_period gets stale'
+ assert_equal 10800, tz.utc_offset, "utc_offset should not be cached when current_period gets stale"
end
end
@@ -425,57 +667,64 @@ class TimeZoneTest < ActiveSupport::TestCase
end
def test_formatted_offset_positive
- zone = ActiveSupport::TimeZone['New Delhi']
+ zone = ActiveSupport::TimeZone["New Delhi"]
assert_equal "+05:30", zone.formatted_offset
assert_equal "+0530", zone.formatted_offset(false)
end
def test_formatted_offset_negative
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
assert_equal "-05:00", zone.formatted_offset
assert_equal "-0500", zone.formatted_offset(false)
end
def test_z_format_strings
- zone = ActiveSupport::TimeZone['Tokyo']
+ zone = ActiveSupport::TimeZone["Tokyo"]
twz = zone.now
- assert_equal '+0900', twz.strftime('%z')
- assert_equal '+09:00', twz.strftime('%:z')
- assert_equal '+09:00:00', twz.strftime('%::z')
+ assert_equal "+0900", twz.strftime("%z")
+ assert_equal "+09:00", twz.strftime("%:z")
+ assert_equal "+09:00:00", twz.strftime("%::z")
end
def test_formatted_offset_zero
- zone = ActiveSupport::TimeZone['London']
+ zone = ActiveSupport::TimeZone["London"]
assert_equal "+00:00", zone.formatted_offset
- assert_equal "UTC", zone.formatted_offset(true, 'UTC')
+ assert_equal "UTC", zone.formatted_offset(true, "UTC")
end
def test_zone_compare
- zone1 = ActiveSupport::TimeZone['Central Time (US & Canada)'] # offset -0600
- zone2 = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] # offset -0500
+ zone1 = ActiveSupport::TimeZone["Central Time (US & Canada)"] # offset -0600
+ zone2 = ActiveSupport::TimeZone["Eastern Time (US & Canada)"] # offset -0500
assert zone1 < zone2
assert zone2 > zone1
assert zone1 == zone1
end
def test_zone_match
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
assert zone =~ /Eastern/
assert zone =~ /New_York/
assert zone !~ /Nonexistent_Place/
end
def test_to_s
- assert_equal "(GMT+05:30) New Delhi", ActiveSupport::TimeZone['New Delhi'].to_s
+ assert_equal "(GMT+05:30) New Delhi", ActiveSupport::TimeZone["New Delhi"].to_s
end
def test_all_sorted
all = ActiveSupport::TimeZone.all
- 1.upto( all.length-1 ) do |i|
- assert all[i-1] < all[i]
+ 1.upto(all.length - 1) do |i|
+ assert all[i - 1] < all[i]
end
end
+ def test_all_uninfluenced_by_time_zone_lookups_delegated_to_tzinfo
+ ActiveSupport::TimeZone.clear
+ galapagos = ActiveSupport::TimeZone["Pacific/Galapagos"]
+ all_zones = ActiveSupport::TimeZone.all
+ assert_not_includes all_zones, galapagos
+ end
+
def test_index
assert_nil ActiveSupport::TimeZone["bogus"]
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone["Central Time (US & Canada)"]
@@ -498,13 +747,17 @@ class TimeZoneTest < ActiveSupport::TestCase
end
def test_us_zones
- assert ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Hawaii"])
- assert !ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Kuala Lumpur"])
+ assert_includes ActiveSupport::TimeZone.us_zones, ActiveSupport::TimeZone["Hawaii"]
+ assert_not_includes ActiveSupport::TimeZone.us_zones, ActiveSupport::TimeZone["Kuala Lumpur"]
end
def test_country_zones
- assert ActiveSupport::TimeZone.country_zones("ru").include?(ActiveSupport::TimeZone["Moscow"])
- assert !ActiveSupport::TimeZone.country_zones(:ru).include?(ActiveSupport::TimeZone["Kuala Lumpur"])
+ assert_includes ActiveSupport::TimeZone.country_zones("ru"), ActiveSupport::TimeZone["Moscow"]
+ assert_not_includes ActiveSupport::TimeZone.country_zones(:ru), ActiveSupport::TimeZone["Kuala Lumpur"]
+ end
+
+ def test_country_zones_without_mappings
+ assert_includes ActiveSupport::TimeZone.country_zones(:sv), ActiveSupport::TimeZone["America/El_Salvador"]
end
def test_to_yaml
diff --git a/activesupport/test/time_zone_test_helpers.rb b/activesupport/test/time_zone_test_helpers.rb
index eb6f7d0f85..051703a781 100644
--- a/activesupport/test/time_zone_test_helpers.rb
+++ b/activesupport/test/time_zone_test_helpers.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module TimeZoneTestHelpers
def with_tz_default(tz = nil)
old_tz = Time.zone
@@ -7,11 +9,11 @@ module TimeZoneTestHelpers
Time.zone = old_tz
end
- def with_env_tz(new_tz = 'US/Eastern')
- old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ def with_env_tz(new_tz = "US/Eastern")
+ old_tz, ENV["TZ"] = ENV["TZ"], new_tz
yield
ensure
- old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ old_tz ? ENV["TZ"] = old_tz : ENV.delete("TZ")
end
def with_preserve_timezone(value)
diff --git a/activesupport/test/transliterate_test.rb b/activesupport/test/transliterate_test.rb
index 378421fedd..7d19447598 100644
--- a/activesupport/test/transliterate_test.rb
+++ b/activesupport/test/transliterate_test.rb
@@ -1,5 +1,7 @@
-require 'abstract_unit'
-require 'active_support/inflector/transliterate'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/inflector/transliterate"
class TransliterateTest < ActiveSupport::TestCase
def test_transliterate_should_not_change_ascii_chars
@@ -13,7 +15,7 @@ class TransliterateTest < ActiveSupport::TestCase
# create string with range of Unicode's western characters with
# diacritics, excluding the division and multiplication signs which for
# some reason or other are floating in the middle of all the letters.
- string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include?(c)}.pack("U*")
+ string = (0xC0..0x17E).to_a.reject { |c| [0xD7, 0xF7].include?(c) }.pack("U*")
string.each_char do |char|
assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(char)
end
@@ -21,7 +23,7 @@ class TransliterateTest < ActiveSupport::TestCase
def test_transliterate_should_work_with_custom_i18n_rules_and_uncomposed_utf8
char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS
- I18n.backend.store_translations(:de, :i18n => {:transliterate => {:rule => {"ü" => "ue"}}})
+ I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { "ü" => "ue" } } })
default_locale, I18n.locale = I18n.locale, :de
assert_equal "ue", ActiveSupport::Inflector.transliterate(char)
ensure
@@ -31,4 +33,22 @@ class TransliterateTest < ActiveSupport::TestCase
def test_transliterate_should_allow_a_custom_replacement_char
assert_equal "a*b", ActiveSupport::Inflector.transliterate("a索b", "*")
end
+
+ def test_transliterate_handles_empty_string
+ assert_equal "", ActiveSupport::Inflector.transliterate("")
+ end
+
+ def test_transliterate_handles_nil
+ exception = assert_raises ArgumentError do
+ ActiveSupport::Inflector.transliterate(nil)
+ end
+ assert_equal "Can only transliterate strings. Received NilClass", exception.message
+ end
+
+ def test_transliterate_handles_unknown_object
+ exception = assert_raises ArgumentError do
+ ActiveSupport::Inflector.transliterate(Object.new)
+ end
+ assert_equal "Can only transliterate strings. Received Object", exception.message
+ end
end
diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb
index ed4de8aba2..97a533aafb 100644
--- a/activesupport/test/xml_mini/jdom_engine_test.rb
+++ b/activesupport/test/xml_mini/jdom_engine_test.rb
@@ -1,37 +1,10 @@
-if RUBY_PLATFORM =~ /java/
- require 'abstract_unit'
- require 'active_support/xml_mini'
- require 'active_support/core_ext/hash/conversions'
+# frozen_string_literal: true
+require_relative "xml_mini_engine_test"
- class JDOMEngineTest < ActiveSupport::TestCase
- include ActiveSupport
-
- FILES_DIR = File.dirname(__FILE__) + '/../fixtures/xml'
-
- def setup
- @default_backend = XmlMini.backend
- XmlMini.backend = 'JDOM'
- end
-
- def teardown
- XmlMini.backend = @default_backend
- end
-
- def test_file_from_xml
- hash = Hash.from_xml(<<-eoxml)
- <blog>
- <logo type="file" name="logo.png" content_type="image/png">
- </logo>
- </blog>
- eoxml
- assert hash.has_key?('blog')
- assert hash['blog'].has_key?('logo')
-
- file = hash['blog']['logo']
- assert_equal 'logo.png', file.original_filename
- assert_equal 'image/png', file.content_type
- end
+XMLMiniEngineTest.run_with_platform("java") do
+ class JDOMEngineTest < XMLMiniEngineTest
+ FILES_DIR = File.expand_path("../fixtures/xml", __dir__)
def test_not_allowed_to_expand_entities_to_files
attack_xml = <<-EOT
@@ -40,7 +13,7 @@ if RUBY_PLATFORM =~ /java/
]>
<member>x&a;</member>
EOT
- assert_equal 'x', Hash.from_xml(attack_xml)["member"]
+ assert_equal "x", Hash.from_xml(attack_xml)["member"]
end
def test_not_allowed_to_expand_parameter_entities_to_files
@@ -52,137 +25,29 @@ if RUBY_PLATFORM =~ /java/
<member>x&a;</member>
EOT
assert_raise Java::OrgXmlSax::SAXParseException do
- assert_equal 'x', Hash.from_xml(attack_xml)["member"]
+ assert_equal "x", Hash.from_xml(attack_xml)["member"]
end
end
-
def test_not_allowed_to_load_external_doctypes
attack_xml = <<-EOT
<!DOCTYPE member SYSTEM "file://#{FILES_DIR}/jdom_doctype.dtd">
<member>x&a;</member>
EOT
- assert_equal 'x', Hash.from_xml(attack_xml)["member"]
+ assert_equal "x", Hash.from_xml(attack_xml)["member"]
end
- def test_exception_thrown_on_expansion_attack
- assert_raise Java::OrgXmlSax::SAXParseException do
- attack_xml = <<-EOT
- <!DOCTYPE member [
- <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
- <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
- <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
- <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
- <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
- <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
- <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
- ]>
- <member>
- &a;
- </member>
- EOT
- Hash.from_xml(attack_xml)
+ private
+ def engine
+ "JDOM"
end
- end
-
- def test_setting_JDOM_as_backend
- XmlMini.backend = 'JDOM'
- assert_equal XmlMini_JDOM, XmlMini.backend
- end
-
- def test_blank_returns_empty_hash
- assert_equal({}, XmlMini.parse(nil))
- assert_equal({}, XmlMini.parse(''))
- end
-
- def test_array_type_makes_an_array
- assert_equal_rexml(<<-eoxml)
- <blog>
- <posts type="array">
- <post>a post</post>
- <post>another post</post>
- </posts>
- </blog>
- eoxml
- end
-
- def test_one_node_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products/>
- eoxml
- end
-
- def test_one_node_with_attributes_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products foo="bar"/>
- eoxml
- end
- def test_products_node_with_book_node_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- </products>
- eoxml
- end
-
- def test_products_node_with_two_book_nodes_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- <book name="america" id="67890" />
- </products>
- eoxml
- end
-
- def test_single_node_with_content_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- hello world
- </products>
- eoxml
- end
-
- def test_children_with_children
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <book name="america" id="67890" />
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello everyone
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_non_adjacent_text
- assert_equal_rexml(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- end
+ def expansion_attack_error
+ Java::OrgXmlSax::SAXParseException
+ end
- private
- def assert_equal_rexml(xml)
- parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
- assert_equal(hash, parsed_xml)
+ def extended_engine?
+ false
end
end
-
-else
- # don't run these test because we aren't running in JRuby
end
diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb
index a8df2e1f7b..3eef3946a3 100644
--- a/activesupport/test/xml_mini/libxml_engine_test.rb
+++ b/activesupport/test/xml_mini/libxml_engine_test.rb
@@ -1,204 +1,21 @@
-begin
- require 'libxml'
-rescue LoadError
- # Skip libxml tests
-else
-require 'abstract_unit'
-require 'active_support/xml_mini'
-require 'active_support/core_ext/hash/conversions'
+# frozen_string_literal: true
-class LibxmlEngineTest < ActiveSupport::TestCase
- include ActiveSupport
+require_relative "xml_mini_engine_test"
- def setup
- @default_backend = XmlMini.backend
- XmlMini.backend = 'LibXML'
-
- LibXML::XML::Error.set_handler(&lambda { |error| }) #silence libxml, exceptions will do
- end
-
- def teardown
- XmlMini.backend = @default_backend
- end
-
- def test_exception_thrown_on_expansion_attack
- assert_raise LibXML::XML::Error do
- attack_xml = %{<?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE member [
- <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
- <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
- <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
- <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
- <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
- <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
- <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
- ]>
- <member>
- &a;
- </member>
- }
- Hash.from_xml(attack_xml)
+XMLMiniEngineTest.run_with_gem("libxml") do
+ class LibxmlEngineTest < XMLMiniEngineTest
+ def setup
+ super
+ LibXML::XML::Error.set_handler(&lambda { |error| }) # silence libxml, exceptions will do
end
- end
-
- def test_setting_libxml_as_backend
- XmlMini.backend = 'LibXML'
- assert_equal XmlMini_LibXML, XmlMini.backend
- end
-
- def test_blank_returns_empty_hash
- assert_equal({}, XmlMini.parse(nil))
- assert_equal({}, XmlMini.parse(''))
- end
-
- def test_array_type_makes_an_array
- assert_equal_rexml(<<-eoxml)
- <blog>
- <posts type="array">
- <post>a post</post>
- <post>another post</post>
- </posts>
- </blog>
- eoxml
- end
-
- def test_one_node_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products/>
- eoxml
- end
-
- def test_one_node_with_attributes_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products foo="bar"/>
- eoxml
- end
-
- def test_products_node_with_book_node_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- </products>
- eoxml
- end
-
- def test_products_node_with_two_book_nodes_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- <book name="america" id="67890" />
- </products>
- eoxml
- end
-
- def test_single_node_with_content_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- hello world
- </products>
- eoxml
- end
-
- def test_children_with_children
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <book name="america" id="67890" />
- </products>
- </root>
- eoxml
- end
- def test_children_with_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello everyone
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_non_adjacent_text
- assert_equal_rexml(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- end
+ private
+ def engine
+ "LibXML"
+ end
- def test_parse_from_io
- io = StringIO.new(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- assert_equal_rexml(io)
+ def expansion_attack_error
+ LibXML::XML::Error
+ end
end
-
- def test_children_with_simple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_multiple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text_and_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello <![CDATA[cdatablock]]>
- morning
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products> </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text_and_attribute
- assert_equal_rexml(<<-eoxml)
- <root>
- <products type="file"> </products>
- </root>
- eoxml
- end
-
-
- private
- def assert_equal_rexml(xml)
- parsed_xml = XmlMini.parse(xml)
- xml.rewind if xml.respond_to?(:rewind)
- hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
- assert_equal(hash, parsed_xml)
- end
-end
-
end
diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
index d6d90639e2..8e4a30a48e 100644
--- a/activesupport/test/xml_mini/libxmlsax_engine_test.rb
+++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
@@ -1,195 +1,16 @@
-begin
- require 'libxml'
-rescue LoadError
- # Skip libxml tests
-else
-require 'abstract_unit'
-require 'active_support/xml_mini'
-require 'active_support/core_ext/hash/conversions'
+# frozen_string_literal: true
-class LibXMLSAXEngineTest < ActiveSupport::TestCase
- include ActiveSupport
+require_relative "xml_mini_engine_test"
- def setup
- @default_backend = XmlMini.backend
- XmlMini.backend = 'LibXMLSAX'
- end
-
- def teardown
- XmlMini.backend = @default_backend
- end
-
- def test_exception_thrown_on_expansion_attack
- assert_raise LibXML::XML::Error do
- attack_xml = <<-EOT
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE member [
- <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
- <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
- <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
- <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
- <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
- <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
- <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
- ]>
- <member>
- &a;
- </member>
- EOT
-
- Hash.from_xml(attack_xml)
- end
- end
-
- def test_setting_libxml_as_backend
- XmlMini.backend = 'LibXMLSAX'
- assert_equal XmlMini_LibXMLSAX, XmlMini.backend
- end
-
- def test_blank_returns_empty_hash
- assert_equal({}, XmlMini.parse(nil))
- assert_equal({}, XmlMini.parse(''))
- end
-
- def test_array_type_makes_an_array
- assert_equal_rexml(<<-eoxml)
- <blog>
- <posts type="array">
- <post>a post</post>
- <post>another post</post>
- </posts>
- </blog>
- eoxml
- end
-
- def test_one_node_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products/>
- eoxml
- end
-
- def test_one_node_with_attributes_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products foo="bar"/>
- eoxml
- end
-
- def test_products_node_with_book_node_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- </products>
- eoxml
- end
-
- def test_products_node_with_two_book_nodes_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- <book name="america" id="67890" />
- </products>
- eoxml
- end
+XMLMiniEngineTest.run_with_gem("libxml") do
+ class LibXMLSAXEngineTest < XMLMiniEngineTest
+ private
+ def engine
+ "LibXMLSAX"
+ end
- def test_single_node_with_content_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- hello world
- </products>
- eoxml
+ def expansion_attack_error
+ LibXML::XML::Error
+ end
end
-
- def test_children_with_children
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <book name="america" id="67890" />
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello everyone
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_non_adjacent_text
- assert_equal_rexml(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- end
-
- def test_parse_from_io
- io = StringIO.new(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- assert_equal_rexml(io)
- end
-
- def test_children_with_simple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_multiple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text_and_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello <![CDATA[cdatablock]]>
- morning
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products> </products>
- </root>
- eoxml
- end
-
- private
- def assert_equal_rexml(xml)
- parsed_xml = XmlMini.parse(xml)
- xml.rewind if xml.respond_to?(:rewind)
- hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
- assert_equal(hash, parsed_xml)
- end
-end
-
end
diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb
index 1314c9065a..f1584bcedf 100644
--- a/activesupport/test/xml_mini/nokogiri_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb
@@ -1,215 +1,16 @@
-begin
- require 'nokogiri'
-rescue LoadError
- # Skip nokogiri tests
-else
-require 'abstract_unit'
-require 'active_support/xml_mini'
-require 'active_support/core_ext/hash/conversions'
+# frozen_string_literal: true
-class NokogiriEngineTest < ActiveSupport::TestCase
- def setup
- @default_backend = ActiveSupport::XmlMini.backend
- ActiveSupport::XmlMini.backend = 'Nokogiri'
- end
-
- def teardown
- ActiveSupport::XmlMini.backend = @default_backend
- end
-
- def test_file_from_xml
- hash = Hash.from_xml(<<-eoxml)
- <blog>
- <logo type="file" name="logo.png" content_type="image/png">
- </logo>
- </blog>
- eoxml
- assert hash.has_key?('blog')
- assert hash['blog'].has_key?('logo')
-
- file = hash['blog']['logo']
- assert_equal 'logo.png', file.original_filename
- assert_equal 'image/png', file.content_type
- end
-
- def test_exception_thrown_on_expansion_attack
- assert_raise Nokogiri::XML::SyntaxError do
- attack_xml = <<-EOT
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE member [
- <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
- <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
- <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
- <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
- <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
- <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
- <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
- ]>
- <member>
- &a;
- </member>
- EOT
- Hash.from_xml(attack_xml)
- end
- end
-
- def test_setting_nokogiri_as_backend
- ActiveSupport::XmlMini.backend = 'Nokogiri'
- assert_equal ActiveSupport::XmlMini_Nokogiri, ActiveSupport::XmlMini.backend
- end
-
- def test_blank_returns_empty_hash
- assert_equal({}, ActiveSupport::XmlMini.parse(nil))
- assert_equal({}, ActiveSupport::XmlMini.parse(''))
- end
-
- def test_array_type_makes_an_array
- assert_equal_rexml(<<-eoxml)
- <blog>
- <posts type="array">
- <post>a post</post>
- <post>another post</post>
- </posts>
- </blog>
- eoxml
- end
-
- def test_one_node_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products/>
- eoxml
- end
-
- def test_one_node_with_attributes_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products foo="bar"/>
- eoxml
- end
-
- def test_products_node_with_book_node_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- </products>
- eoxml
- end
-
- def test_products_node_with_two_book_nodes_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- <book name="america" id="67890" />
- </products>
- eoxml
- end
-
- def test_single_node_with_content_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- hello world
- </products>
- eoxml
- end
+require_relative "xml_mini_engine_test"
- def test_children_with_children
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <book name="america" id="67890" />
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello everyone
- </products>
- </root>
- eoxml
- end
+XMLMiniEngineTest.run_with_gem("nokogiri") do
+ class NokogiriEngineTest < XMLMiniEngineTest
+ private
+ def engine
+ "Nokogiri"
+ end
- def test_children_with_non_adjacent_text
- assert_equal_rexml(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
+ def expansion_attack_error
+ Nokogiri::XML::SyntaxError
+ end
end
-
- def test_parse_from_io
- io = StringIO.new(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- assert_equal_rexml(io)
- end
-
- def test_children_with_simple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_multiple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text_and_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello <![CDATA[cdatablock]]>
- morning
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products> </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text_and_attribute
- assert_equal_rexml(<<-eoxml)
- <root>
- <products type="file"> </products>
- </root>
- eoxml
- end
-
- private
- def assert_equal_rexml(xml)
- parsed_xml = ActiveSupport::XmlMini.parse(xml)
- xml.rewind if xml.respond_to?(:rewind)
- hash = ActiveSupport::XmlMini.with_backend('REXML') { ActiveSupport::XmlMini.parse(xml) }
- assert_equal(hash, parsed_xml)
- end
-end
-
end
diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
index 7978a50921..f38a56e83b 100644
--- a/activesupport/test/xml_mini/nokogirisax_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
@@ -1,216 +1,16 @@
-begin
- require 'nokogiri'
-rescue LoadError
- # Skip nokogiri tests
-else
-require 'abstract_unit'
-require 'active_support/xml_mini'
-require 'active_support/core_ext/hash/conversions'
+# frozen_string_literal: true
-class NokogiriSAXEngineTest < ActiveSupport::TestCase
- def setup
- @default_backend = ActiveSupport::XmlMini.backend
- ActiveSupport::XmlMini.backend = 'NokogiriSAX'
- end
-
- def teardown
- ActiveSupport::XmlMini.backend = @default_backend
- end
-
- def test_file_from_xml
- hash = Hash.from_xml(<<-eoxml)
- <blog>
- <logo type="file" name="logo.png" content_type="image/png">
- </logo>
- </blog>
- eoxml
- assert hash.has_key?('blog')
- assert hash['blog'].has_key?('logo')
-
- file = hash['blog']['logo']
- assert_equal 'logo.png', file.original_filename
- assert_equal 'image/png', file.content_type
- end
-
- def test_exception_thrown_on_expansion_attack
- assert_raise RuntimeError do
- attack_xml = <<-EOT
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE member [
- <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
- <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
- <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
- <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
- <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
- <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
- <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
- ]>
- <member>
- &a;
- </member>
- EOT
-
- Hash.from_xml(attack_xml)
- end
- end
-
- def test_setting_nokogirisax_as_backend
- ActiveSupport::XmlMini.backend = 'NokogiriSAX'
- assert_equal ActiveSupport::XmlMini_NokogiriSAX, ActiveSupport::XmlMini.backend
- end
+require_relative "xml_mini_engine_test"
- def test_blank_returns_empty_hash
- assert_equal({}, ActiveSupport::XmlMini.parse(nil))
- assert_equal({}, ActiveSupport::XmlMini.parse(''))
- end
-
- def test_array_type_makes_an_array
- assert_equal_rexml(<<-eoxml)
- <blog>
- <posts type="array">
- <post>a post</post>
- <post>another post</post>
- </posts>
- </blog>
- eoxml
- end
-
- def test_one_node_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products/>
- eoxml
- end
-
- def test_one_node_with_attributes_document_as_hash
- assert_equal_rexml(<<-eoxml)
- <products foo="bar"/>
- eoxml
- end
-
- def test_products_node_with_book_node_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- </products>
- eoxml
- end
-
- def test_products_node_with_two_book_nodes_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- <book name="awesome" id="12345" />
- <book name="america" id="67890" />
- </products>
- eoxml
- end
+XMLMiniEngineTest.run_with_gem("nokogiri") do
+ class NokogiriSAXEngineTest < XMLMiniEngineTest
+ private
+ def engine
+ "NokogiriSAX"
+ end
- def test_single_node_with_content_as_hash
- assert_equal_rexml(<<-eoxml)
- <products>
- hello world
- </products>
- eoxml
+ def expansion_attack_error
+ RuntimeError
+ end
end
-
- def test_children_with_children
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <book name="america" id="67890" />
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello everyone
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_non_adjacent_text
- assert_equal_rexml(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- end
-
- def test_parse_from_io
- io = StringIO.new(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- assert_equal_rexml(io)
- end
-
- def test_children_with_simple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_multiple_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_text_and_cdata
- assert_equal_rexml(<<-eoxml)
- <root>
- <products>
- hello <![CDATA[cdatablock]]>
- morning
- </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text
- assert_equal_rexml(<<-eoxml)
- <root>
- <products> </products>
- </root>
- eoxml
- end
-
- def test_children_with_blank_text_and_attribute
- assert_equal_rexml(<<-eoxml)
- <root>
- <products type="file"> </products>
- </root>
- eoxml
- end
-
- private
- def assert_equal_rexml(xml)
- parsed_xml = ActiveSupport::XmlMini.parse(xml)
- xml.rewind if xml.respond_to?(:rewind)
- hash = ActiveSupport::XmlMini.with_backend('REXML') { ActiveSupport::XmlMini.parse(xml) }
- assert_equal(hash, parsed_xml)
- end
-end
-
end
diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb
index f0067ca656..34bf81fa75 100644
--- a/activesupport/test/xml_mini/rexml_engine_test.rb
+++ b/activesupport/test/xml_mini/rexml_engine_test.rb
@@ -1,35 +1,27 @@
-require 'abstract_unit'
-require 'active_support/xml_mini'
+# frozen_string_literal: true
-class REXMLEngineTest < ActiveSupport::TestCase
+require_relative "xml_mini_engine_test"
+
+class REXMLEngineTest < XMLMiniEngineTest
def test_default_is_rexml
assert_equal ActiveSupport::XmlMini_REXML, ActiveSupport::XmlMini.backend
end
- def test_set_rexml_as_backend
- ActiveSupport::XmlMini.backend = 'REXML'
- assert_equal ActiveSupport::XmlMini_REXML, ActiveSupport::XmlMini.backend
+ def test_parse_from_empty_string
+ assert_equal({}, ActiveSupport::XmlMini.parse(""))
end
- def test_parse_from_io
- ActiveSupport::XmlMini.backend = 'REXML'
- io = StringIO.new(<<-eoxml)
- <root>
- good
- <products>
- hello everyone
- </products>
- morning
- </root>
- eoxml
- assert_equal_rexml(io)
+ def test_parse_from_frozen_string
+ xml_string = "<root></root>".freeze
+ assert_equal({ "root" => {} }, ActiveSupport::XmlMini.parse(xml_string))
end
private
- def assert_equal_rexml(xml)
- parsed_xml = ActiveSupport::XmlMini.parse(xml)
- xml.rewind if xml.respond_to?(:rewind)
- hash = ActiveSupport::XmlMini.with_backend('REXML') { ActiveSupport::XmlMini.parse(xml) }
- assert_equal(hash, parsed_xml)
+ def engine
+ "REXML"
+ end
+
+ def expansion_attack_error
+ RuntimeError
end
end
diff --git a/activesupport/test/xml_mini/xml_mini_engine_test.rb b/activesupport/test/xml_mini/xml_mini_engine_test.rb
new file mode 100644
index 0000000000..5c4c28d9b7
--- /dev/null
+++ b/activesupport/test/xml_mini/xml_mini_engine_test.rb
@@ -0,0 +1,264 @@
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/xml_mini"
+require "active_support/core_ext/hash/conversions"
+
+class XMLMiniEngineTest < ActiveSupport::TestCase
+ def self.run_with_gem(gem_name)
+ require gem_name
+ yield
+ rescue LoadError
+ # Skip tests unless gem is available
+ end
+
+ def self.run_with_platform(platform_name)
+ yield if RUBY_PLATFORM.include?(platform_name)
+ end
+
+ def self.inherited(base)
+ base.include EngineTests
+ super
+ end
+
+ def setup
+ @default_backend = ActiveSupport::XmlMini.backend
+ ActiveSupport::XmlMini.backend = engine
+ super
+ end
+
+ def teardown
+ ActiveSupport::XmlMini.backend = @default_backend
+ super
+ end
+
+ module EngineTests
+ def test_file_from_xml
+ hash = Hash.from_xml(<<-eoxml)
+ <blog>
+ <logo type="file" name="logo.png" content_type="image/png">
+ </logo>
+ </blog>
+ eoxml
+ assert hash.key?("blog")
+ assert hash["blog"].key?("logo")
+
+ file = hash["blog"]["logo"]
+ assert_equal "logo.png", file.original_filename
+ assert_equal "image/png", file.content_type
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise expansion_attack_error do
+ Hash.from_xml(<<-eoxml)
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ eoxml
+ end
+ end
+
+ def test_setting_backend
+ assert_engine_class ActiveSupport::XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, ActiveSupport::XmlMini.parse(nil))
+ assert_equal({}, ActiveSupport::XmlMini.parse(""))
+ end
+
+ def test_parse_from_frozen_string
+ xml_string = "<root/>".freeze
+ assert_equal({ "root" => {} }, ActiveSupport::XmlMini.parse(xml_string))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ skip_unless_extended_engine
+
+ assert_equal_rexml(StringIO.new(<<-eoxml))
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_children_with_simple_cdata
+ skip_unless_extended_engine
+
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ skip_unless_extended_engine
+
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ skip_unless_extended_engine
+
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ skip_unless_extended_engine
+
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text_and_attribute
+ skip_unless_extended_engine
+
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
+ private
+ def engine
+ raise NotImplementedError
+ end
+
+ def assert_engine_class(actual)
+ assert_equal ActiveSupport.const_get("XmlMini_#{engine}"), actual
+ end
+
+ def assert_equal_rexml(xml)
+ parsed_xml = ActiveSupport::XmlMini.parse(xml)
+ xml.rewind if xml.respond_to?(:rewind)
+ hash = ActiveSupport::XmlMini.with_backend("REXML") { ActiveSupport::XmlMini.parse(xml) }
+ assert_equal(hash, parsed_xml)
+ end
+
+ def expansion_attack_error
+ raise NotImplementedError
+ end
+
+ def extended_engine?
+ true
+ end
+
+ def skip_unless_extended_engine
+ skip "#{engine} is not an extended engine" unless extended_engine?
+ end
+ end
+end
diff --git a/activesupport/test/xml_mini_test.rb b/activesupport/test/xml_mini_test.rb
index 55e8181b54..18a3f2ca66 100644
--- a/activesupport/test/xml_mini_test.rb
+++ b/activesupport/test/xml_mini_test.rb
@@ -1,9 +1,11 @@
-require 'abstract_unit'
-require 'active_support/xml_mini'
-require 'active_support/builder'
-require 'active_support/core_ext/hash'
-require 'active_support/core_ext/big_decimal'
-require 'yaml'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "active_support/xml_mini"
+require "active_support/builder"
+require "active_support/core_ext/hash"
+require "active_support/core_ext/big_decimal"
+require "yaml"
module XmlMiniTest
class RenameKeyTest < ActiveSupport::TestCase
@@ -12,23 +14,23 @@ module XmlMiniTest
end
def test_rename_key_dasherizes_with_dasherize_true
- assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true)
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", dasherize: true)
end
def test_rename_key_does_nothing_with_dasherize_false
- assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false)
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", dasherize: false)
end
def test_rename_key_camelizes_with_camelize_true
- assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true)
+ assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", camelize: true)
end
def test_rename_key_lower_camelizes_with_camelize_lower
- assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :lower)
+ assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", camelize: :lower)
end
def test_rename_key_lower_camelizes_with_camelize_upper
- assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :upper)
+ assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", camelize: :upper)
end
def test_rename_key_does_not_dasherize_leading_underscores
@@ -63,16 +65,16 @@ module XmlMiniTest
def setup
@xml = ActiveSupport::XmlMini
- @options = {:skip_instruct => true, :builder => Builder::XmlMarkup.new}
+ @options = { skip_instruct: true, builder: Builder::XmlMarkup.new }
end
test "#to_tag accepts a callable object and passes options with the builder" do
- @xml.to_tag(:some_tag, lambda {|o| o[:builder].br }, @options)
+ @xml.to_tag(:some_tag, lambda { |o| o[:builder].br }, @options)
assert_xml "<br/>"
end
test "#to_tag accepts a callable object and passes options and tag name" do
- @xml.to_tag(:tag, lambda {|o, t| o[:builder].b(t) }, @options)
+ @xml.to_tag(:tag, lambda { |o, t| o[:builder].b(t) }, @options)
assert_xml "<b>tag</b>"
end
@@ -92,58 +94,58 @@ module XmlMiniTest
end
test "#to_tag should use the type value in the options hash" do
- @xml.to_tag(:b, "blue", @options.merge(type: 'color'))
- assert_xml( "<b type=\"color\">blue</b>" )
+ @xml.to_tag(:b, "blue", @options.merge(type: "color"))
+ assert_xml("<b type=\"color\">blue</b>")
end
test "#to_tag accepts symbol types" do
@xml.to_tag(:b, :name, @options)
- assert_xml( "<b type=\"symbol\">name</b>" )
+ assert_xml("<b type=\"symbol\">name</b>")
end
test "#to_tag accepts boolean types" do
@xml.to_tag(:b, true, @options)
- assert_xml( "<b type=\"boolean\">true</b>")
+ assert_xml("<b type=\"boolean\">true</b>")
end
test "#to_tag accepts float types" do
@xml.to_tag(:b, 3.14, @options)
- assert_xml( "<b type=\"float\">3.14</b>")
+ assert_xml("<b type=\"float\">3.14</b>")
end
test "#to_tag accepts decimal types" do
- @xml.to_tag(:b, ::BigDecimal.new("1.2"), @options)
- assert_xml( "<b type=\"decimal\">1.2</b>")
+ @xml.to_tag(:b, BigDecimal("1.2"), @options)
+ assert_xml("<b type=\"decimal\">1.2</b>")
end
test "#to_tag accepts date types" do
- @xml.to_tag(:b, Date.new(2001,2,3), @options)
- assert_xml( "<b type=\"date\">2001-02-03</b>")
+ @xml.to_tag(:b, Date.new(2001, 2, 3), @options)
+ assert_xml("<b type=\"date\">2001-02-03</b>")
end
test "#to_tag accepts datetime types" do
- @xml.to_tag(:b, DateTime.new(2001,2,3,4,5,6,'+7'), @options)
- assert_xml( "<b type=\"dateTime\">2001-02-03T04:05:06+07:00</b>")
+ @xml.to_tag(:b, DateTime.new(2001, 2, 3, 4, 5, 6, "+7"), @options)
+ assert_xml("<b type=\"dateTime\">2001-02-03T04:05:06+07:00</b>")
end
test "#to_tag accepts time types" do
@xml.to_tag(:b, Time.new(1993, 02, 24, 12, 0, 0, "+09:00"), @options)
- assert_xml( "<b type=\"dateTime\">1993-02-24T12:00:00+09:00</b>")
+ assert_xml("<b type=\"dateTime\">1993-02-24T12:00:00+09:00</b>")
end
test "#to_tag accepts array types" do
@xml.to_tag(:b, ["first_name", "last_name"], @options)
- assert_xml( "<b type=\"array\"><b>first_name</b><b>last_name</b></b>" )
+ assert_xml("<b type=\"array\"><b>first_name</b><b>last_name</b></b>")
end
test "#to_tag accepts hash types" do
@xml.to_tag(:b, { first_name: "Bob", last_name: "Marley" }, @options)
- assert_xml( "<b><first-name>Bob</first-name><last-name>Marley</last-name></b>" )
+ assert_xml("<b><first-name>Bob</first-name><last-name>Marley</last-name></b>")
end
test "#to_tag should not add type when skip types option is set" do
@xml.to_tag(:b, "Bob", @options.merge(skip_types: 1))
- assert_xml( "<b>Bob</b>" )
+ assert_xml("<b>Bob</b>")
end
test "#to_tag should dasherize the space when passed a string with spaces as a key" do
@@ -233,62 +235,62 @@ module XmlMiniTest
end
def test_symbol
- parser = @parsing['symbol']
- assert_equal :symbol, parser.call('symbol')
+ parser = @parsing["symbol"]
+ assert_equal :symbol, parser.call("symbol")
assert_equal :symbol, parser.call(:symbol)
assert_equal :'123', parser.call(123)
- assert_raises(ArgumentError) { parser.call(Date.new(2013,11,12,02,11)) }
+ assert_raises(ArgumentError) { parser.call(Date.new(2013, 11, 12, 02, 11)) }
end
def test_date
- parser = @parsing['date']
- assert_equal Date.new(2013,11,12), parser.call("2013-11-12T0211Z")
+ parser = @parsing["date"]
+ assert_equal Date.new(2013, 11, 12), parser.call("2013-11-12T0211Z")
assert_raises(TypeError) { parser.call(1384190018) }
assert_raises(ArgumentError) { parser.call("not really a date") }
end
def test_datetime
- parser = @parsing['datetime']
- assert_equal Time.new(2013,11,12,02,11,00,0), parser.call("2013-11-12T02:11:00Z")
- assert_equal DateTime.new(2013,11,12), parser.call("2013-11-12T0211Z")
- assert_equal DateTime.new(2013,11,12,02,11), parser.call("2013-11-12T02:11Z")
- assert_equal DateTime.new(2013,11,12,02,11), parser.call("2013-11-12T11:11+9")
+ parser = @parsing["datetime"]
+ assert_equal Time.new(2013, 11, 12, 02, 11, 00, 0), parser.call("2013-11-12T02:11:00Z")
+ assert_equal DateTime.new(2013, 11, 12), parser.call("2013-11-12T0211Z")
+ assert_equal DateTime.new(2013, 11, 12, 02, 11), parser.call("2013-11-12T02:11Z")
+ assert_equal DateTime.new(2013, 11, 12, 02, 11), parser.call("2013-11-12T11:11+9")
assert_raises(ArgumentError) { parser.call("1384190018") }
end
def test_integer
- parser = @parsing['integer']
+ parser = @parsing["integer"]
assert_equal 123, parser.call(123)
assert_equal 123, parser.call(123.003)
assert_equal 123, parser.call("123")
assert_equal 0, parser.call("")
- assert_raises(ArgumentError) { parser.call(Date.new(2013,11,12,02,11)) }
+ assert_raises(ArgumentError) { parser.call(Date.new(2013, 11, 12, 02, 11)) }
end
def test_float
- parser = @parsing['float']
+ parser = @parsing["float"]
assert_equal 123, parser.call("123")
assert_equal 123.003, parser.call("123.003")
assert_equal 123.0, parser.call("123,003")
assert_equal 0.0, parser.call("")
assert_equal 123, parser.call(123)
assert_equal 123.05, parser.call(123.05)
- assert_raises(ArgumentError) { parser.call(Date.new(2013,11,12,02,11)) }
+ assert_raises(ArgumentError) { parser.call(Date.new(2013, 11, 12, 02, 11)) }
end
def test_decimal
- parser = @parsing['decimal']
+ parser = @parsing["decimal"]
assert_equal 123, parser.call("123")
assert_equal 123.003, parser.call("123.003")
assert_equal 123.0, parser.call("123,003")
assert_equal 0.0, parser.call("")
assert_equal 123, parser.call(123)
assert_raises(ArgumentError) { parser.call(123.04) }
- assert_raises(ArgumentError) { parser.call(Date.new(2013,11,12,02,11)) }
+ assert_raises(ArgumentError) { parser.call(Date.new(2013, 11, 12, 02, 11)) }
end
def test_boolean
- parser = @parsing['boolean']
+ parser = @parsing["boolean"]
[1, true, "1"].each do |value|
assert parser.call(value)
end
@@ -299,13 +301,13 @@ module XmlMiniTest
end
def test_string
- parser = @parsing['string']
+ parser = @parsing["string"]
assert_equal "123", parser.call(123)
assert_equal "123", parser.call("123")
assert_equal "[]", parser.call("[]")
assert_equal "[]", parser.call([])
assert_equal "{}", parser.call({})
- assert_raises(ArgumentError) { parser.call(Date.new(2013,11,12,02,11)) }
+ assert_raises(ArgumentError) { parser.call(Date.new(2013, 11, 12, 02, 11)) }
end
def test_yaml
@@ -316,14 +318,14 @@ product:
description : Basketball
YAML
expected = {
- "product"=> [
- {"sku"=>"BL394D", "quantity"=>4, "description"=>"Basketball"}
+ "product" => [
+ { "sku" => "BL394D", "quantity" => 4, "description" => "Basketball" }
]
}
- parser = @parsing['yaml']
+ parser = @parsing["yaml"]
assert_equal(expected, parser.call(yaml))
- assert_equal({1 => 'test'}, parser.call({1 => 'test'}))
- assert_equal({"1 => 'test'"=>nil}, parser.call("{1 => 'test'}"))
+ assert_equal({ 1 => "test" }, parser.call(1 => "test"))
+ assert_equal({ "1 => 'test'" => nil }, parser.call("{1 => 'test'}"))
end
def test_base64Binary_and_binary
@@ -341,12 +343,12 @@ in the continued and indefatigable generation of knowledge, exceeds the short
vehemence of any carnal pleasure.
EXPECTED
- parser = @parsing['base64Binary']
- assert_equal expected_base64.gsub(/\n/," ").strip, parser.call(base64)
+ parser = @parsing["base64Binary"]
+ assert_equal expected_base64.gsub(/\n/, " ").strip, parser.call(base64)
parser.call("NON BASE64 INPUT")
- parser = @parsing['binary']
- assert_equal expected_base64.gsub(/\n/," ").strip, parser.call(base64, 'encoding' => 'base64')
+ parser = @parsing["binary"]
+ assert_equal expected_base64.gsub(/\n/, " ").strip, parser.call(base64, "encoding" => "base64")
assert_equal "IGNORED INPUT", parser.call("IGNORED INPUT", {})
end
end