aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile12
-rw-r--r--RELEASING_RAILS.rdoc18
-rw-r--r--actionmailer/CHANGELOG.md518
-rw-r--r--actionmailer/lib/action_mailer.rb8
-rw-r--r--actionmailer/lib/action_mailer/base.rb3
-rw-r--r--actionmailer/lib/action_mailer/railtie.rb1
-rw-r--r--actionmailer/lib/action_mailer/test_case.rb1
-rw-r--r--actionmailer/test/base_test.rb15
-rw-r--r--actionpack/CHANGELOG.md6202
-rw-r--r--actionpack/README.rdoc285
-rw-r--r--actionpack/actionpack.gemspec2
-rw-r--r--actionpack/examples/performance.rb185
-rw-r--r--actionpack/examples/views/_collection.erb3
-rw-r--r--actionpack/examples/views/_hello.erb1
-rw-r--r--actionpack/examples/views/_hundred_partials.erb3
-rw-r--r--actionpack/examples/views/_partial.erb10
-rw-r--r--actionpack/examples/views/_ten_partials.erb10
-rw-r--r--actionpack/examples/views/hashes/_hash.erb3
-rw-r--r--actionpack/examples/views/my_hashes/_my_hash.erb3
-rw-r--r--actionpack/examples/views/template.html.erb1
-rw-r--r--actionpack/lib/abstract_controller.rb5
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb6
-rw-r--r--actionpack/lib/abstract_controller/translation.rb8
-rw-r--r--actionpack/lib/action_controller.rb16
-rw-r--r--actionpack/lib/action_controller/base.rb9
-rw-r--r--actionpack/lib/action_controller/caching.rb25
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb44
-rw-r--r--actionpack/lib/action_controller/caching/sweeping.rb9
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb1
-rw-r--r--actionpack/lib/action_controller/metal.rb4
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb43
-rw-r--r--actionpack/lib/action_controller/metal/data_streaming.rb4
-rw-r--r--actionpack/lib/action_controller/metal/exceptions.rb3
-rw-r--r--actionpack/lib/action_controller/metal/flash.rb6
-rw-r--r--actionpack/lib/action_controller/metal/force_ssl.rb2
-rw-r--r--actionpack/lib/action_controller/metal/head.rb8
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb1
-rw-r--r--actionpack/lib/action_controller/metal/hide_actions.rb1
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb19
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb1
-rw-r--r--actionpack/lib/action_controller/metal/live.rb141
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb9
-rw-r--r--actionpack/lib/action_controller/metal/params_wrapper.rb1
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb2
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb1
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb4
-rw-r--r--actionpack/lib/action_controller/metal/streaming.rb3
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb12
-rw-r--r--actionpack/lib/action_controller/railtie.rb2
-rw-r--r--actionpack/lib/action_controller/record_identifier.rb83
-rw-r--r--actionpack/lib/action_controller/test_case.rb39
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner.rb23
-rw-r--r--actionpack/lib/action_dispatch.rb19
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb31
-rw-r--r--actionpack/lib/action_dispatch/http/filter_parameters.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb21
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb178
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb5
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb22
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb122
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb6
-rw-r--r--actionpack/lib/action_dispatch/middleware/callbacks.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb18
-rw-r--r--actionpack/lib/action_dispatch/middleware/head.rb18
-rw-r--r--actionpack/lib/action_dispatch/middleware/request_id.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb9
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb10
-rw-r--r--actionpack/lib/action_dispatch/railtie.rb9
-rw-r--r--actionpack/lib/action_dispatch/request/session.rb9
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb (renamed from railties/lib/rails/application/routes_inspector.rb)4
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb159
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb94
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb4
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/dom.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb1
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb11
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/tag.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb3
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb1
-rw-r--r--actionpack/lib/action_view.rb11
-rw-r--r--actionpack/lib/action_view/asset_paths.rb3
-rw-r--r--actionpack/lib/action_view/base.rb7
-rw-r--r--actionpack/lib/action_view/context.rb4
-rw-r--r--actionpack/lib/action_view/digestor.rb104
-rw-r--r--actionpack/lib/action_view/helpers/active_model_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb94
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb1
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb16
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb1
-rw-r--r--actionpack/lib/action_view/helpers/cache_helper.rb114
-rw-r--r--actionpack/lib/action_view/helpers/capture_helper.rb11
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb26
-rw-r--r--actionpack/lib/action_view/helpers/debug_helper.rb8
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb35
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb19
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb66
-rw-r--r--actionpack/lib/action_view/helpers/javascript_helper.rb40
-rw-r--r--actionpack/lib/action_view/helpers/record_tag_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/sanitize_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/tag_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/tags/base.rb4
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb174
-rw-r--r--actionpack/lib/action_view/lookup_context.rb10
-rw-r--r--actionpack/lib/action_view/model_naming.rb12
-rw-r--r--actionpack/lib/action_view/railtie.rb2
-rw-r--r--actionpack/lib/action_view/record_identifier.rb84
-rw-r--r--actionpack/lib/action_view/renderer/abstract_renderer.rb6
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb34
-rw-r--r--actionpack/lib/action_view/renderer/streaming_template_renderer.rb2
-rw-r--r--actionpack/lib/action_view/renderer/template_renderer.rb5
-rw-r--r--actionpack/lib/action_view/routing_url_for.rb107
-rw-r--r--actionpack/lib/action_view/template.rb10
-rw-r--r--actionpack/lib/action_view/template/error.rb7
-rw-r--r--actionpack/lib/action_view/template/handlers/builder.rb2
-rw-r--r--actionpack/lib/action_view/template/handlers/erb.rb1
-rw-r--r--actionpack/lib/action_view/template/resolver.rb2
-rw-r--r--actionpack/lib/action_view/template/text.rb12
-rw-r--r--actionpack/lib/action_view/template/types.rb58
-rw-r--r--actionpack/lib/action_view/test_case.rb5
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner.rb20
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner/html/document.rb (renamed from actionpack/lib/action_controller/vendor/html-scanner/html/document.rb)0
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner/html/node.rb (renamed from actionpack/lib/action_controller/vendor/html-scanner/html/node.rb)0
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb (renamed from actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb)1
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner/html/selector.rb (renamed from actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb)0
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb (renamed from actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb)0
-rw-r--r--actionpack/lib/action_view/vendor/html-scanner/html/version.rb (renamed from actionpack/lib/action_controller/vendor/html-scanner/html/version.rb)0
-rw-r--r--actionpack/test/abstract/translation_test.rb13
-rw-r--r--actionpack/test/abstract_unit.rb96
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb288
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb2
-rw-r--r--actionpack/test/controller/base_test.rb41
-rw-r--r--actionpack/test/controller/caching_test.rb63
-rw-r--r--actionpack/test/controller/filters_test.rb11
-rw-r--r--actionpack/test/controller/flash_test.rb1
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb7
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb8
-rw-r--r--actionpack/test/controller/integration_test.rb2
-rw-r--r--actionpack/test/controller/layout_test.rb2
-rw-r--r--actionpack/test/controller/live_stream_test.rb121
-rw-r--r--actionpack/test/controller/mime_responds_test.rb18
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb30
-rw-r--r--actionpack/test/controller/new_base/render_action_test.rb8
-rw-r--r--actionpack/test/controller/new_base/render_streaming_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_template_test.rb4
-rw-r--r--actionpack/test/controller/new_base/render_text_test.rb2
-rw-r--r--actionpack/test/controller/render_test.rb36
-rw-r--r--actionpack/test/controller/resources_test.rb36
-rw-r--r--actionpack/test/controller/routing_test.rb34
-rw-r--r--actionpack/test/controller/selector_test.rb2
-rw-r--r--actionpack/test/controller/send_file_test.rb6
-rw-r--r--actionpack/test/controller/streaming_test.rb26
-rw-r--r--actionpack/test/controller/url_for_test.rb2
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb2
-rw-r--r--actionpack/test/dispatch/cookies_test.rb2
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb11
-rw-r--r--actionpack/test/dispatch/live_response_test.rb83
-rw-r--r--actionpack/test/dispatch/mapper_test.rb9
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb2
-rw-r--r--actionpack/test/dispatch/mount_test.rb9
-rw-r--r--actionpack/test/dispatch/prefix_generation_test.rb18
-rw-r--r--actionpack/test/dispatch/request_test.rb8
-rw-r--r--actionpack/test/dispatch/response_test.rb58
-rw-r--r--actionpack/test/dispatch/routing/concerns_test.rb119
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb170
-rw-r--r--actionpack/test/dispatch/routing_test.rb67
-rw-r--r--actionpack/test/fixtures/digestor/comments/_comment.html.erb1
-rw-r--r--actionpack/test/fixtures/digestor/comments/_comments.html.erb1
-rw-r--r--actionpack/test/fixtures/digestor/events/_event.html.erb0
-rw-r--r--actionpack/test/fixtures/digestor/messages/_form.html.erb0
-rw-r--r--actionpack/test/fixtures/digestor/messages/_header.html.erb0
-rw-r--r--actionpack/test/fixtures/digestor/messages/_message.html.erb1
-rw-r--r--actionpack/test/fixtures/digestor/messages/actions/_move.html.erb0
-rw-r--r--actionpack/test/fixtures/digestor/messages/edit.html.erb5
-rw-r--r--actionpack/test/fixtures/digestor/messages/index.html.erb2
-rw-r--r--actionpack/test/fixtures/digestor/messages/show.html.erb9
-rw-r--r--actionpack/test/fixtures/project.rb2
-rw-r--r--actionpack/test/fixtures/reply.rb4
-rw-r--r--actionpack/test/fixtures/test/_changing_priority.html.erb1
-rw-r--r--actionpack/test/fixtures/test/_changing_priority.json.erb1
-rw-r--r--actionpack/test/fixtures/test/_first_json_partial.json.erb1
-rw-r--r--actionpack/test/fixtures/test/_json_change_priority.json.erb0
-rw-r--r--actionpack/test/fixtures/test/_raise_indentation.html.erb13
-rw-r--r--actionpack/test/fixtures/test/_second_json_partial.json.erb1
-rw-r--r--actionpack/test/fixtures/test/change_priorty.html.erb2
-rw-r--r--actionpack/test/fixtures/test/html_template.html.erb1
-rw-r--r--actionpack/test/template/active_model_helper_test.rb14
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb20
-rw-r--r--actionpack/test/template/capture_helper_test.rb18
-rw-r--r--actionpack/test/template/date_helper_test.rb53
-rw-r--r--actionpack/test/template/digestor_test.rb157
-rw-r--r--actionpack/test/template/erb/helper.rb3
-rw-r--r--actionpack/test/template/erb/tag_helper_test.rb3
-rw-r--r--actionpack/test/template/erb_util_test.rb13
-rw-r--r--actionpack/test/template/form_helper_test.rb29
-rw-r--r--actionpack/test/template/form_options_helper_test.rb47
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb71
-rw-r--r--actionpack/test/template/javascript_helper_test.rb42
-rw-r--r--actionpack/test/template/log_subscriber_test.rb7
-rw-r--r--actionpack/test/template/lookup_context_test.rb11
-rw-r--r--actionpack/test/template/record_identifier_test.rb (renamed from actionpack/test/controller/record_identifier_test.rb)11
-rw-r--r--actionpack/test/template/render_test.rb26
-rw-r--r--actionpack/test/template/sanitize_helper_test.rb4
-rw-r--r--actionpack/test/template/template_test.rb9
-rw-r--r--actionpack/test/template/text_helper_test.rb8
-rw-r--r--actionpack/test/template/url_helper_test.rb107
-rw-r--r--activemodel/CHANGELOG.md209
-rw-r--r--activemodel/lib/active_model.rb17
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb10
-rw-r--r--activemodel/lib/active_model/callbacks.rb11
-rw-r--r--activemodel/lib/active_model/conversion.rb19
-rw-r--r--activemodel/lib/active_model/dirty.rb1
-rw-r--r--activemodel/lib/active_model/errors.rb22
-rw-r--r--activemodel/lib/active_model/mass_assignment_security.rb247
-rw-r--r--activemodel/lib/active_model/mass_assignment_security/sanitizer.rb8
-rw-r--r--activemodel/lib/active_model/naming.rb51
-rw-r--r--activemodel/lib/active_model/observer_array.rb27
-rw-r--r--activemodel/lib/active_model/observing.rb206
-rw-r--r--activemodel/lib/active_model/railtie.rb8
-rw-r--r--activemodel/lib/active_model/secure_password.rb58
-rw-r--r--activemodel/lib/active_model/serialization.rb50
-rw-r--r--activemodel/lib/active_model/serializers/json.rb47
-rwxr-xr-x[-rw-r--r--]activemodel/lib/active_model/serializers/xml.rb40
-rw-r--r--activemodel/lib/active_model/validations.rb162
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb24
-rw-r--r--activemodel/lib/active_model/validations/callbacks.rb87
-rw-r--r--activemodel/lib/active_model/validations/clusivity.rb22
-rw-r--r--activemodel/lib/active_model/validations/confirmation.rb27
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb39
-rw-r--r--activemodel/lib/active_model/validations/format.rb43
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb45
-rw-r--r--activemodel/lib/active_model/validations/length.rb58
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb52
-rw-r--r--activemodel/lib/active_model/validations/presence.rb24
-rw-r--r--activemodel/lib/active_model/validations/validates.rb92
-rw-r--r--activemodel/lib/active_model/validations/with.rb34
-rw-r--r--activemodel/lib/active_model/validator.rb30
-rw-r--r--activemodel/test/cases/mass_assignment_security/sanitizer_test.rb1
-rw-r--r--activemodel/test/cases/mass_assignment_security_test.rb10
-rw-r--r--activemodel/test/cases/secure_password_test.rb8
-rwxr-xr-x[-rw-r--r--]activemodel/test/cases/serializers/xml_serialization_test.rb38
-rw-r--r--activemodel/test/cases/validations/callbacks_test.rb4
-rw-r--r--activemodel/test/cases/validations/exclusion_validation_test.rb35
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb22
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb35
-rw-r--r--activemodel/test/cases/validations_test.rb9
-rw-r--r--activemodel/test/models/oauthed_user.rb11
-rw-r--r--activerecord/CHANGELOG.md7118
-rw-r--r--activerecord/README.rdoc12
-rw-r--r--activerecord/RUNNING_UNIT_TESTS11
-rw-r--r--activerecord/activerecord.gemspec2
-rw-r--r--activerecord/examples/performance.rb69
-rw-r--r--activerecord/lib/active_record.rb78
-rw-r--r--activerecord/lib/active_record/aggregations.rb261
-rw-r--r--activerecord/lib/active_record/associations.rb336
-rw-r--r--activerecord/lib/active_record/associations/association.rb27
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb55
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb5
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb128
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb89
-rw-r--r--activerecord/lib/active_record/associations/builder/collection_association.rb90
-rw-r--r--activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb38
-rw-r--r--activerecord/lib/active_record/associations/builder/has_many.rb61
-rw-r--r--activerecord/lib/active_record/associations/builder/has_one.rb57
-rw-r--r--activerecord/lib/active_record/associations/builder/singular_association.rb26
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb51
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb214
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb30
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb5
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb66
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_association.rb33
-rw-r--r--activerecord/lib/active_record/associations/preloader.rb19
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb55
-rw-r--r--activerecord/lib/active_record/associations/preloader/collection_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many_through.rb2
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_one.rb2
-rw-r--r--activerecord/lib/active_record/associations/preloader/through_association.rb27
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb4
-rw-r--r--activerecord/lib/active_record/associations/through_association.rb2
-rw-r--r--activerecord/lib/active_record/attribute_assignment.rb215
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb1
-rw-r--r--activerecord/lib/active_record/attribute_methods/dirty.rb4
-rw-r--r--activerecord/lib/active_record/attribute_methods/query.rb1
-rw-r--r--activerecord/lib/active_record/attribute_methods/read.rb17
-rw-r--r--activerecord/lib/active_record/attribute_methods/serialization.rb123
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb21
-rw-r--r--activerecord/lib/active_record/attribute_methods/write.rb4
-rw-r--r--activerecord/lib/active_record/autosave_association.rb14
-rw-r--r--activerecord/lib/active_record/base.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb96
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb42
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb7
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb20
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb1
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/column.rb5
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb228
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb20
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb4
-rw-r--r--activerecord/lib/active_record/connection_handling.rb3
-rw-r--r--activerecord/lib/active_record/core.rb25
-rw-r--r--activerecord/lib/active_record/counter_cache.rb2
-rw-r--r--activerecord/lib/active_record/dynamic_matchers.rb12
-rw-r--r--activerecord/lib/active_record/explain.rb1
-rw-r--r--activerecord/lib/active_record/fixtures.rb3
-rw-r--r--activerecord/lib/active_record/inheritance.rb34
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb20
-rw-r--r--activerecord/lib/active_record/migration.rb8
-rw-r--r--activerecord/lib/active_record/migration/join_table.rb6
-rw-r--r--activerecord/lib/active_record/model.rb55
-rw-r--r--activerecord/lib/active_record/model_schema.rb28
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb20
-rw-r--r--activerecord/lib/active_record/null_relation.rb3
-rw-r--r--activerecord/lib/active_record/observer.rb7
-rw-r--r--activerecord/lib/active_record/persistence.rb62
-rw-r--r--activerecord/lib/active_record/query_cache.rb15
-rw-r--r--activerecord/lib/active_record/querying.rb22
-rw-r--r--activerecord/lib/active_record/railtie.rb39
-rw-r--r--activerecord/lib/active_record/railties/databases.rake30
-rw-r--r--activerecord/lib/active_record/readonly_attributes.rb9
-rw-r--r--activerecord/lib/active_record/reflection.rb94
-rw-r--r--activerecord/lib/active_record/relation.rb162
-rw-r--r--activerecord/lib/active_record/relation/batches.rb15
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb1
-rw-r--r--activerecord/lib/active_record/relation/delegation.rb3
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb18
-rw-r--r--activerecord/lib/active_record/relation/merger.rb15
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb165
-rw-r--r--activerecord/lib/active_record/relation/spawn_methods.rb17
-rw-r--r--activerecord/lib/active_record/result.rb4
-rw-r--r--activerecord/lib/active_record/sanitization.rb44
-rw-r--r--activerecord/lib/active_record/schema.rb1
-rw-r--r--activerecord/lib/active_record/schema_migration.rb11
-rw-r--r--activerecord/lib/active_record/scoping.rb1
-rw-r--r--activerecord/lib/active_record/scoping/default.rb10
-rw-r--r--activerecord/lib/active_record/scoping/named.rb22
-rw-r--r--activerecord/lib/active_record/session_store.rb363
-rw-r--r--activerecord/lib/active_record/store.rb26
-rw-r--r--activerecord/lib/active_record/tasks/database_tasks.rb20
-rw-r--r--activerecord/lib/active_record/test_case.rb1
-rw-r--r--activerecord/lib/active_record/timestamp.rb1
-rw-r--r--activerecord/lib/active_record/transactions.rb40
-rw-r--r--activerecord/lib/active_record/validations.rb1
-rw-r--r--activerecord/lib/active_record/validations/associated.rb32
-rw-r--r--activerecord/lib/active_record/validations/presence.rb64
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb78
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/migration_generator.rb31
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/migration.rb26
-rw-r--r--activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb25
-rw-r--r--activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb12
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb12
-rw-r--r--activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql/reserved_word_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb7
-rw-r--r--activerecord/test/cases/adapters/mysql2/reserved_word_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb73
-rw-r--r--activerecord/test/cases/aggregations_test.rb160
-rw-r--r--activerecord/test/cases/associations/association_scope_test.rb15
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb24
-rw-r--r--activerecord/test/cases/associations/cascaded_eager_loading_test.rb44
-rw-r--r--activerecord/test/cases/associations/eager_load_nested_include_test.rb4
-rw-r--r--activerecord/test/cases/associations/eager_singularization_test.rb14
-rw-r--r--activerecord/test/cases/associations/eager_test.rb274
-rw-r--r--activerecord/test/cases/associations/extension_test.rb6
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb53
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb179
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb15
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb71
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb30
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb8
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb24
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb77
-rw-r--r--activerecord/test/cases/associations_test.rb23
-rw-r--r--activerecord/test/cases/attribute_methods/read_test.rb5
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb23
-rw-r--r--activerecord/test/cases/autosave_association_test.rb18
-rw-r--r--activerecord/test/cases/base_test.rb364
-rw-r--r--activerecord/test/cases/calculations_test.rb34
-rw-r--r--activerecord/test/cases/connection_adapters/connection_handler_test.rb15
-rw-r--r--activerecord/test/cases/counter_cache_test.rb11
-rw-r--r--activerecord/test/cases/custom_locking_test.rb2
-rw-r--r--activerecord/test/cases/defaults_test.rb3
-rw-r--r--activerecord/test/cases/deprecated_dynamic_methods_test.rb108
-rw-r--r--activerecord/test/cases/dirty_test.rb42
-rw-r--r--activerecord/test/cases/explain_test.rb16
-rw-r--r--activerecord/test/cases/finder_test.rb245
-rw-r--r--activerecord/test/cases/helper.rb5
-rw-r--r--activerecord/test/cases/inclusion_test.rb26
-rw-r--r--activerecord/test/cases/inheritance_test.rb154
-rw-r--r--activerecord/test/cases/locking_test.rb19
-rw-r--r--activerecord/test/cases/log_subscriber_test.rb12
-rw-r--r--activerecord/test/cases/mass_assignment_security_test.rb2
-rw-r--r--activerecord/test/cases/migration/change_schema_test.rb4
-rw-r--r--activerecord/test/cases/migration/column_attributes_test.rb16
-rw-r--r--activerecord/test/cases/migration/create_join_table_test.rb20
-rw-r--r--activerecord/test/cases/migration/rename_table_test.rb34
-rw-r--r--activerecord/test/cases/modules_test.rb8
-rw-r--r--activerecord/test/cases/multiple_db_test.rb4
-rw-r--r--activerecord/test/cases/named_scope_test.rb56
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb54
-rw-r--r--activerecord/test/cases/persistence_test.rb137
-rw-r--r--activerecord/test/cases/query_cache_test.rb14
-rw-r--r--activerecord/test/cases/readonly_test.rb10
-rw-r--r--activerecord/test/cases/reflection_test.rb110
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb36
-rw-r--r--activerecord/test/cases/relation_test.rb16
-rw-r--r--activerecord/test/cases/relations_test.rb213
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb2
-rw-r--r--activerecord/test/cases/serialization_test.rb13
-rw-r--r--activerecord/test/cases/serialized_attribute_test.rb205
-rw-r--r--activerecord/test/cases/session_store/session_test.rb81
-rw-r--r--activerecord/test/cases/session_store/sql_bypass_test.rb61
-rw-r--r--activerecord/test/cases/store_test.rb5
-rw-r--r--activerecord/test/cases/tasks/database_tasks_test.rb16
-rw-r--r--activerecord/test/cases/tasks/mysql_rake_test.rb6
-rw-r--r--activerecord/test/cases/tasks/sqlite_rake_test.rb8
-rw-r--r--activerecord/test/cases/test_case.rb1
-rw-r--r--activerecord/test/cases/timestamp_test.rb34
-rw-r--r--activerecord/test/cases/transactions_test.rb196
-rw-r--r--activerecord/test/cases/validations/presence_validation_test.rb44
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb18
-rw-r--r--activerecord/test/config.example.yml2
-rw-r--r--activerecord/test/fixtures/companies.yml6
-rw-r--r--activerecord/test/fixtures/friendships.yml4
-rw-r--r--activerecord/test/fixtures/people.yml3
-rw-r--r--activerecord/test/fixtures/topics.yml2
-rw-r--r--activerecord/test/fixtures/vegetables.yml20
-rw-r--r--activerecord/test/models/author.rb74
-rw-r--r--activerecord/test/models/book.rb2
-rw-r--r--activerecord/test/models/bulb.rb2
-rw-r--r--activerecord/test/models/car.rb6
-rw-r--r--activerecord/test/models/category.rb18
-rw-r--r--activerecord/test/models/comment.rb6
-rw-r--r--activerecord/test/models/company.rb104
-rw-r--r--activerecord/test/models/company_in_module.rb12
-rw-r--r--activerecord/test/models/customer.rb7
-rw-r--r--activerecord/test/models/developer.rb36
-rw-r--r--activerecord/test/models/friendship.rb4
-rw-r--r--activerecord/test/models/liquid.rb2
-rw-r--r--activerecord/test/models/member.rb11
-rw-r--r--activerecord/test/models/person.rb14
-rw-r--r--activerecord/test/models/pirate.rb8
-rw-r--r--activerecord/test/models/post.rb45
-rw-r--r--activerecord/test/models/project.rb42
-rw-r--r--activerecord/test/models/reader.rb8
-rw-r--r--activerecord/test/models/sponsor.rb4
-rw-r--r--activerecord/test/models/tagging.rb5
-rw-r--r--activerecord/test/models/topic.rb6
-rw-r--r--activerecord/test/models/vegetables.rb24
-rw-r--r--activerecord/test/schema/schema.rb23
-rw-r--r--activerecord/test/support/connection.rb4
-rw-r--r--activesupport/CHANGELOG.md1739
-rw-r--r--activesupport/lib/active_support.rb3
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb7
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb53
-rw-r--r--activesupport/lib/active_support/callbacks.rb5
-rw-r--r--activesupport/lib/active_support/concurrency/latch.rb27
-rw-r--r--activesupport/lib/active_support/core_ext/date.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb184
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/calculations.rb213
-rw-r--r--activesupport/lib/active_support/core_ext/date_time.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/file/atomic.rb32
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_param.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/string.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/string/indent.rb43
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb22
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb13
-rw-r--r--activesupport/lib/active_support/core_ext/time.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb211
-rw-r--r--activesupport/lib/active_support/core_ext/time/zones.rb11
-rw-r--r--activesupport/lib/active_support/dependencies.rb53
-rw-r--r--activesupport/lib/active_support/dependencies/autoload.rb60
-rw-r--r--activesupport/lib/active_support/duration.rb2
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb121
-rw-r--r--activesupport/lib/active_support/inflections.rb2
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb23
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb22
-rw-r--r--activesupport/lib/active_support/json/encoding.rb64
-rw-r--r--activesupport/lib/active_support/json/variable.rb17
-rw-r--r--activesupport/lib/active_support/locale/en.yml10
-rw-r--r--activesupport/lib/active_support/notifications/fanout.rb6
-rw-r--r--activesupport/lib/active_support/number_helper.rb161
-rw-r--r--activesupport/lib/active_support/rails.rb27
-rw-r--r--activesupport/lib/active_support/railtie.rb2
-rw-r--r--activesupport/lib/active_support/string_inquirer.rb18
-rw-r--r--activesupport/lib/active_support/test_case.rb29
-rw-r--r--activesupport/lib/active_support/testing/declarative.rb40
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb3
-rw-r--r--activesupport/test/abstract_unit.rb10
-rw-r--r--activesupport/test/autoload_test.rb (renamed from activesupport/test/autoload.rb)12
-rw-r--r--activesupport/test/autoloading_fixtures/circular1.rb6
-rw-r--r--activesupport/test/autoloading_fixtures/circular2.rb4
-rw-r--r--activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb2
-rw-r--r--activesupport/test/caching_test.rb102
-rw-r--r--activesupport/test/core_ext/date_and_time_behavior.rb186
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb173
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb143
-rw-r--r--activesupport/test/core_ext/file_test.rb2
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb23
-rw-r--r--activesupport/test/core_ext/module/qualified_const_test.rb29
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb30
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb60
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb182
-rw-r--r--activesupport/test/dependencies_test.rb8
-rw-r--r--activesupport/test/inflector_test.rb35
-rw-r--r--activesupport/test/json/encoding_test.rb7
-rw-r--r--activesupport/test/multibyte_chars_test.rb2
-rw-r--r--activesupport/test/notifications/evented_notification_test.rb20
-rw-r--r--activesupport/test/number_helper_i18n_test.rb42
-rw-r--r--activesupport/test/number_helper_test.rb7
-rw-r--r--activesupport/test/ordered_hash_test.rb6
-rw-r--r--activesupport/test/string_inquirer_test.rb14
-rw-r--r--activesupport/test/tagged_logging_test.rb5
-rw-r--r--activesupport/test/transliterate_test.rb3
-rwxr-xr-xci/travis.rb3
-rw-r--r--guides/code/getting_started/app/views/comments/_comment.html.erb4
-rw-r--r--guides/code/getting_started/app/views/posts/index.html.erb2
-rw-r--r--guides/code/getting_started/config/initializers/session_store.rb5
-rw-r--r--guides/rails_guides/textile_extensions.rb2
-rw-r--r--guides/source/2_2_release_notes.textile4
-rw-r--r--guides/source/2_3_release_notes.textile2
-rw-r--r--guides/source/4_0_release_notes.textile76
-rw-r--r--guides/source/action_controller_overview.textile39
-rw-r--r--guides/source/action_mailer_basics.textile28
-rw-r--r--guides/source/action_view_overview.textile2
-rw-r--r--guides/source/active_model_basics.textile12
-rw-r--r--guides/source/active_record_querying.textile57
-rw-r--r--guides/source/active_record_validations_callbacks.textile14
-rw-r--r--guides/source/active_support_core_extensions.textile67
-rw-r--r--guides/source/ajax_on_rails.textile11
-rw-r--r--guides/source/api_documentation_guidelines.textile2
-rw-r--r--guides/source/asset_pipeline.textile21
-rw-r--r--guides/source/association_basics.textile613
-rw-r--r--guides/source/caching_with_rails.textile4
-rw-r--r--guides/source/command_line.textile49
-rw-r--r--guides/source/configuring.textile42
-rw-r--r--guides/source/contributing_to_ruby_on_rails.textile136
-rw-r--r--guides/source/credits.html.erb2
-rw-r--r--guides/source/debugging_rails_applications.textile6
-rw-r--r--guides/source/engines.textile164
-rw-r--r--guides/source/form_helpers.textile139
-rw-r--r--guides/source/getting_started.textile38
-rw-r--r--guides/source/i18n.textile8
-rw-r--r--guides/source/initialization.textile14
-rw-r--r--guides/source/kindle/KINDLE.md6
-rw-r--r--guides/source/kindle/welcome.html.erb2
-rw-r--r--guides/source/layouts_and_rendering.textile2
-rw-r--r--guides/source/migrations.textile72
-rw-r--r--guides/source/performance_testing.textile229
-rw-r--r--guides/source/plugins.textile18
-rw-r--r--guides/source/rails_application_templates.textile2
-rw-r--r--guides/source/routing.textile30
-rw-r--r--guides/source/security.textile49
-rw-r--r--guides/source/testing.textile88
-rw-r--r--guides/source/upgrading_ruby_on_rails.textile20
-rw-r--r--guides/w3c_validator.rb21
-rw-r--r--rails.gemspec2
-rw-r--r--railties/CHANGELOG.md2500
-rw-r--r--railties/lib/rails/application.rb28
-rw-r--r--railties/lib/rails/application/bootstrap.rb18
-rw-r--r--railties/lib/rails/application/configuration.rb32
-rw-r--r--railties/lib/rails/application/finisher.rb6
-rw-r--r--railties/lib/rails/commands.rb6
-rw-r--r--railties/lib/rails/commands/destroy.rb3
-rw-r--r--railties/lib/rails/commands/generate.rb3
-rw-r--r--railties/lib/rails/commands/server.rb9
-rw-r--r--railties/lib/rails/console/app.rb3
-rw-r--r--railties/lib/rails/engine.rb14
-rw-r--r--railties/lib/rails/engine/commands.rb4
-rw-r--r--railties/lib/rails/generators.rb1
-rw-r--r--railties/lib/rails/generators/app_base.rb13
-rw-r--r--railties/lib/rails/generators/base.rb3
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/index.html.erb2
-rw-r--r--railties/lib/rails/generators/generated_attribute.rb13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb10
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environment.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt7
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt7
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb9
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/locales/en.yml22
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/routes.rb8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt7
-rw-r--r--railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb2
-rw-r--r--railties/lib/rails/generators/rails/controller/USAGE12
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/USAGE7
-rw-r--r--railties/lib/rails/generators/rails/session_migration/USAGE8
-rw-r--r--railties/lib/rails/generators/rails/session_migration/session_migration_generator.rb8
-rw-r--r--railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb2
-rw-r--r--railties/lib/rails/info_controller.rb4
-rw-r--r--railties/lib/rails/queueing.rb27
-rw-r--r--railties/lib/rails/railtie.rb3
-rw-r--r--railties/lib/rails/railtie/configuration.rb10
-rw-r--r--railties/lib/rails/tasks/misc.rake7
-rw-r--r--railties/lib/rails/tasks/routes.rake4
-rw-r--r--railties/lib/rails/tasks/tmp.rake12
-rw-r--r--railties/test/application/assets_test.rb30
-rw-r--r--railties/test/application/configuration_test.rb55
-rw-r--r--railties/test/application/initializers/boot_test.rb2
-rw-r--r--railties/test/application/initializers/frameworks_test.rb20
-rw-r--r--railties/test/application/initializers/hooks_test.rb10
-rw-r--r--railties/test/application/middleware/cache_test.rb2
-rw-r--r--railties/test/application/middleware/exceptions_test.rb14
-rw-r--r--railties/test/application/middleware/remote_ip_test.rb14
-rw-r--r--railties/test/application/middleware_test.rb8
-rw-r--r--railties/test/application/queue_test.rb13
-rw-r--r--railties/test/application/rack/logger_test.rb8
-rw-r--r--railties/test/application/rake_test.rb23
-rw-r--r--railties/test/application/routes_inspect_test.rb168
-rw-r--r--railties/test/generators/app_generator_test.rb11
-rw-r--r--railties/test/generators/migration_generator_test.rb42
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb9
-rw-r--r--railties/test/generators/session_migration_generator_test.rb27
-rw-r--r--railties/test/generators_test.rb2
-rw-r--r--railties/test/isolation/abstract_unit.rb14
-rw-r--r--railties/test/queueing/container_test.rb30
-rw-r--r--railties/test/railties/engine_test.rb48
-rw-r--r--railties/test/railties/mounted_engine_test.rb15
627 files changed, 13042 insertions, 26317 deletions
diff --git a/Gemfile b/Gemfile
index 1c378c7a68..3a446f1c13 100644
--- a/Gemfile
+++ b/Gemfile
@@ -5,7 +5,7 @@ gemspec
if ENV['AREL']
gem 'arel', path: ENV['AREL']
else
- gem 'arel'
+ gem 'arel', github: 'rails/arel'
end
gem 'mocha', '>= 0.11.2', :require => false
@@ -20,9 +20,9 @@ else
end
if ENV['AR_DEPRECATED_FINDERS']
- gem 'active_record_deprecated_finders', path: ENV['AR_DEPRECATED_FINDERS']
+ gem 'activerecord-deprecated_finders', path: ENV['AR_DEPRECATED_FINDERS']
else
- gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders'
+ gem 'activerecord-deprecated_finders', github: 'rails/activerecord-deprecated_finders'
end
# This needs to be with require false to avoid
@@ -40,7 +40,7 @@ group :doc do
end
# AS
-gem 'memcache-client', '>= 1.8.5'
+gem 'dalli'
# Add your own local bundler stuff
local_gemfile = File.dirname(__FILE__) + "/.Gemfile"
@@ -62,7 +62,7 @@ platforms :ruby do
group :db do
gem 'pg', '>= 0.11.0'
- gem 'mysql', '>= 2.8.1'
+ gem 'mysql', '>= 2.8.1' if RUBY_VERSION < '2.0.0'
gem 'mysql2', '>= 0.3.10'
end
end
@@ -96,3 +96,5 @@ end
# A gem necessary for ActiveRecord tests with IBM DB
gem 'ibm_db' if ENV['IBM_DB']
+
+gem 'benchmark-ips'
diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc
index bdf0ffc2d0..af1def223a 100644
--- a/RELEASING_RAILS.rdoc
+++ b/RELEASING_RAILS.rdoc
@@ -25,10 +25,10 @@ for Rails. You can check the status of his tests here:
Do not release with Red AWDwR tests.
-=== Do we have any git dependencies? If so, contact those authors.
+=== Do we have any Git dependencies? If so, contact those authors.
-Having git dependencies indicates that we depend on unreleased code.
-Obviously rails cannot be released when it depends on unreleased code.
+Having Git dependencies indicates that we depend on unreleased code.
+Obviously Rails cannot be released when it depends on unreleased code.
Contact the authors of those particular gems and work out a release date that
suits them.
@@ -115,14 +115,14 @@ what to do in case anything goes wrong:
=== Send Rails release announcements
Write a release announcement that includes the version, changes, and links to
-github where people can find the specific commit list. Here are the mailing
+GitHub where people can find the specific commit list. Here are the mailing
lists where you should announce:
* rubyonrails-core@googlegroups.com
* rubyonrails-talk@googlegroups.com
* ruby-talk@ruby-lang.org
-Use markdown format for your announcement. Remember to ask people to report
+Use Markdown format for your announcement. Remember to ask people to report
issues with the release candidate to the rails-core mailing list.
IMPORTANT: If any users experience regressions when using the release
@@ -131,16 +131,16 @@ break existing applications.
=== Post the announcement to the Rails blog.
-If you used markdown format for your email, you can just paste it in to the
+If you used Markdown format for your email, you can just paste it in to the
blog.
* http://weblog.rubyonrails.org
-=== Post the announcement to the Rails twitter account.
+=== Post the announcement to the Rails Twitter account.
== Time between release candidate and actual release
-Check the rails-core mailing list and the github issue list for regressions in
+Check the rails-core mailing list and the GitHub issue list for regressions in
the RC.
If any regressions are found, fix the regressions and repeat the release
@@ -167,7 +167,7 @@ Today, do this stuff in this order:
* Email security lists
* Email general announcement lists
-=== Emailing the rails security announce list
+=== Emailing the Rails security announce list
Email the security announce list once for each vulnerability fixed.
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
index 96cfb43e0b..c33a24c1ba 100644
--- a/actionmailer/CHANGELOG.md
+++ b/actionmailer/CHANGELOG.md
@@ -6,520 +6,4 @@
* Asynchronously send messages via the Rails Queue *Brian Cardarella*
-## Rails 3.2.5 (Jun 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.4 (May 31, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.3 (March 30, 2012) ##
-
-* Upgrade mail version to 2.4.3 *ML*
-
-
-## Rails 3.2.2 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.1 (January 26, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.0 (January 20, 2012) ##
-
-* Upgrade mail version to 2.4.0 *ML*
-
-* Remove Old ActionMailer API *Josh Kalderimis*
-
-
-## Rails 3.1.3 (November 20, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.2 (November 18, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.1 (October 7, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.0 (August 30, 2011) ##
-
-* No changes
-
-
-## Rails 3.0.11 (November 18, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.10 (August 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.9 (June 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.8 (June 7, 2011) ##
-
-* Mail dependency increased to 2.2.19
-
-
-## Rails 3.0.7 (April 18, 2011) ##
-
-* remove AM delegating register_observer and register_interceptor to Mail *Josh Kalderimis*
-
-
-## Rails 3.0.6 (April 5, 2011) ##
-
-* Don't allow i18n to change the minor version, version now set to ~> 0.5.0 *Santiago Pastorino*
-
-
-## Rails 3.0.5 (February 26, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.4 (February 8, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.3 (November 16, 2010) ##
-
-* No changes.
-
-
-## Rails 3.0.2 (November 15, 2010) ##
-
-* No changes
-
-
-## Rails 3.0.1 (October 15, 2010) ##
-
-* No Changes, just a version bump.
-
-
-## Rails 3.0.0 (August 29, 2010) ##
-
-* subject is automatically looked up on I18n using mailer_name and action_name as scope as in t(".subject") *JK*
-
-* Changed encoding behaviour of mail, so updated tests in actionmailer and bumped mail version to 2.2.1 *ML*
-
-* Added ability to pass Proc objects to the defaults hash *ML*
-
-* Removed all quoting.rb type files from ActionMailer and put Mail 2.2.0 in instead *ML*
-
-* Lot of updates to various test cases that now work better with the new Mail and so have different expectations
-
-* Added interceptors and observers from Mail *ML*
-
- ActionMailer::Base.register_interceptor calls Mail.register_interceptor
- ActionMailer::Base.register_observer calls Mail.register_observer
-
-* Mail::Part now no longer has nil as a default charset, it is always set to something, and defaults to UTF-8
-
-* Added explict setting of charset in set_fields! method to make sure Mail has the user defined default
-
-* Removed quoting.rb and refactored for Mail to take responsibility of all quoting and auto encoding requirements for the header.
-
-* Fixed several tests which had incorrect encoding.
-
-* Changed all utf-8 to UTF-8 for consistency
-
-* Whole new API added with tests. See base.rb for full details. Old API is deprecated.
-
-* The Mail::Message class has helped methods for all the field types that return 'common' defaults for the common use case, so to get the subject, mail.subject will give you a string, mail.date will give you a DateTime object, mail.from will give you an array of address specs (mikel@test.lindsaar.net) etc. If you want to access the field object itself, call mail[:field_name] which will return the field object you want, which you can then chain, like mail[:from].formatted
-
-* Mail#content_type now returns the content_type field as a string. If you want the mime type of a mail, then you call Mail#mime_type (eg, text/plain), if you want the parameters of the content type field, you call Mail#content_type_parameters which gives you a hash, eg {'format' => 'flowed', 'charset' => 'utf-8'}
-
-* ActionMailer::Base :default_implicit_parts_order now is in the sequence of the order you want, no reversing of ordering takes place. The default order now is text/plain, then text/enriched, then text/html and then any other part that is not one of these three.
-
-* Mail does not have "quoted_body", "quoted_subject" etc. All of these are accessed via body.encoded, subject.encoded etc
-
-* Every object in a Mail object returns an object, never a string. So Mail.body returns a Mail::Body class object, need to call #encoded or #decoded to get the string you want.
-
-* Mail::Message#set_content_type does not exist, it is simply Mail::Message#content_type
-
-* Every mail message gets a unique message_id unless you specify one, had to change all the tests that check for equality with expected.encoded == actual.encoded to first replace their message_ids with control values
-
-* Mail now has a proper concept of parts, remove the ActionMailer::Part and ActionMailer::PartContainer classes
-
-* Calling #encoded on any object returns it as a string ready to go into the output stream of an email, this means it includes the \r\n at the end of the lines and the object is pre-wrapped with \r\n\t if it is a header field. Also, the "encoded" value includes the field name if it is a header field.
-
-* Attachments are only the actual attachment, with filename etc. A part contains an attachment. The part has the content_type etc. So attachments.last.content_type is invalid. But parts.last.content_type
-
-* There is no idea of a "sub_head" in Mail. A part is just a Message with some extra functionality, so it just has a "header" like a normal mail message
-
-
-## 2.3.2 Final (March 15, 2009) ##
-
-* Fixed that ActionMailer should send correctly formatted Return-Path in MAIL FROM for SMTP #1842 *Matt Jones*
-
-* Fixed RFC-2045 quoted-printable bug #1421 *squadette*
-
-* Fixed that no body charset would be set when there are attachments present #740 *Paweł Kondzior*
-
-
-## 2.2.1 RC2 (November 14th, 2008) ##
-
-* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 *Grant Hollingworth*
-
-
-## 2.2.0 RC1 (October 24th, 2008) ##
-
-* Add layout functionality to mailers *Pratik Naik*
-
- Mailer layouts behaves just like controller layouts, except layout names need to
- have '_mailer' postfix for them to be automatically picked up.
-
-
-## 2.1.0 (May 31st, 2008) ##
-
-* Fixed that a return-path header would be ignored #7572 *joost*
-
-* Less verbose mail logging: just recipients for :info log level; the whole email for :debug only. #8000 *iaddict, Tarmo Tänav*
-
-* Updated TMail to version 1.2.1 *Mikel Lindsaar*
-
-* Fixed that you don't have to call super in ActionMailer::TestCase#setup #10406 *jamesgolick*
-
-
-## 2.0.2 (December 16th, 2007) ##
-
-* Included in Rails 2.0.2
-
-
-## 2.0.1 (December 7th, 2007) ##
-
-* Update ActionMailer so it treats ActionView the same way that ActionController does. Closes #10244 *Rick Olson*
-
- * Pass the template_root as an array as ActionView's view_path
- * Request templates with the "#{mailer_name}/#{action}" as opposed to just "#{action}"
-
-* Fixed that partials would be broken when using text.plain.erb as the extension #10130 *java*
-
-* Update README to use new smtp settings configuration API. Closes #10060 *psq*
-
-* Allow ActionMailer subclasses to individually set their delivery method (so two subclasses can have different delivery methods) #10033 *Zach Dennis*
-
-* Update TMail to v1.1.0. Use an updated version of TMail if available. *Mikel Lindsaar*
-
-* Introduce a new base test class for testing Mailers. ActionMailer::TestCase *Michael Koziarski*
-
-* Fix silent failure of rxml templates. #9879 *jstewart*
-
-* Fix attachment decoding when using the TMail C extension. #7861 *orangechicken*
-
-* Increase mail delivery test coverage. #8692 *Kamal Fariz Mahyuddin*
-
-* Register alternative template engines using ActionMailer::Base.register_template_extension('haml'). #7534 *cwd, Josh Peek*
-
-* Only load ActionController::UrlWriter if ActionController is present *Rick Olson*
-
-* Make sure parsed emails recognized attachments nested inside multipart parts. #6714 *Jamis Buck*
-
-* Allow mailer actions named send by using __send__ internally. #6467 *iGEL*
-
-* Add assert_emails and assert_no_emails to test the number of emails delivered. #6479 *Jonathan Viney*
- # Assert total number of emails delivered:
- assert_emails 0
- ContactMailer.deliver_contact
- assert_emails 1
-
- # Assert number of emails delivered within a block:
- assert_emails 1 do
- post :signup, :name => 'Jonathan'
- end
-
-
-## 1.3.3 (March 12th, 2007) ##
-
-* Depend on Action Pack 1.13.3
-
-
-## 1.3.2 (February 5th, 2007) ##
-
-* Deprecate server_settings renaming it to smtp_settings, add sendmail_settings to allow you to override the arguments to and location of the sendmail executable. *Michael Koziarski*
-
-
-## 1.3.1 (January 16th, 2007) ##
-
-* Depend on Action Pack 1.13.1
-
-
-## 1.3.0 (January 16th, 2007) ##
-
-* Make mime version default to 1.0. closes #2323 *ror@andreas-s.net*
-
-* Make sure quoted-printable text is decoded correctly when only portions of the text are encoded. closes #3154. *jon@siliconcircus.com*
-
-* Make sure DOS newlines in quoted-printable text are normalized to unix newlines before unquoting. closes #4166 and #4452. *Jamis Buck*
-
-* Fixed that iconv decoding should catch InvalidEncoding #3153 *jon@siliconcircus.com*
-
-* Tighten rescue clauses. #5985 *james@grayproductions.net*
-
-* Automatically included ActionController::UrlWriter, such that URL generation can happen within ActionMailer controllers. *David Heinemeier Hansson*
-
-* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
-
-* Mailer template root applies to a class and its subclasses rather than acting globally. #5555 *somekool@gmail.com*
-
-* Resolve action naming collision. #5520 *ssinghi@kreeti.com*
-
-* ActionMailer::Base documentation rewrite. Closes #4991 *Kevin Clark, Marcel Molina Jr.*
-
-* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
-
-* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
-
-* Correct spurious documentation example code which results in a SyntaxError. *Marcel Molina Jr.*
-
-
-## 1.2.1 (April 6th, 2006) ##
-
-* Be part of Rails 1.1.1
-
-
-## 1.2.0 (March 27th, 2006) ##
-
-* Nil charset caused subject line to be improperly quoted in implicitly multipart messages #2662 *ehalvorsen+rails@runbox.com*
-
-* Parse content-type apart before using it so that sub-parts of the header can be set correctly #2918 *Jamis Buck*
-
-* Make custom headers work in subparts #4034 *elan@bluemandrill.com*
-
-* Template paths with dot chars in them no longer mess up implicit template selection for multipart messages #3332 *Chad Fowler*
-
-* Make sure anything with content-disposition of "attachment" is passed to the attachment presenter when parsing an email body *Jamis Buck*
-
-* Make sure TMail#attachments includes anything with content-disposition of "attachment", regardless of content-type *Jamis Buck*
-
-
-## 1.1.5 (December 13th, 2005) ##
-
-* Become part of Rails 1.0
-
-
-## 1.1.4 (December 7th, 2005) ##
-
-* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
-
-* Stricter matching for implicitly multipart filenames excludes files ending in unsupported extensions (such as foo.rhtml.bak) and without a two-part content type (such as foo.text.rhtml or foo.text.really.plain.rhtml). #2398 *Dave Burt <dave@burt.id.au>, Jeremy Kemper*
-
-
-## 1.1.3 (November 7th, 2005) ##
-
-* Allow Mailers to have custom initialize methods that set default instance variables for all mail actions #2563 *mrj@bigpond.net.au*
-
-
-## 1.1.2 (October 26th, 2005) ##
-
-* Upgraded to Action Pack 1.10.2
-
-
-## 1.1.1 (October 19th, 2005) ##
-
-* Upgraded to Action Pack 1.10.1
-
-
-## 1.1.0 (October 16th, 2005) ##
-
-* Update and extend documentation (rdoc)
-
-* Minero Aoki made TMail available to Rails/ActionMailer under the MIT license (instead of LGPL) *RubyConf '05*
-
-* Austin Ziegler made Text::Simple available to Rails/ActionMailer under a MIT-like licens *See rails ML, subject "Text::Format Licence Exception" on Oct 15, 2005*
-
-* Fix vendor require paths to prevent files being required twice
-
-* Don't add charset to content-type header for a part that contains subparts (for AOL compatibility) #2013 *John Long*
-
-* Preserve underscores when unquoting message bodies #1930
-
-* Encode multibyte characters correctly #1894
-
-* Multipart messages specify a MIME-Version header automatically #2003 *John Long*
-
-* Add a unified render method to ActionMailer (delegates to ActionView::Base#render)
-
-* Move mailer initialization to a separate (overridable) method, so that subclasses may alter the various defaults #1727
-
-* Look at content-location header (if available) to determine filename of attachments #1670
-
-* ActionMailer::Base.deliver(email) had been accidentally removed, but was documented in the Rails book #1849
-
-* Fix problem with sendmail delivery where headers should be delimited by \n characters instead of \r\n, which confuses some mail readers #1742 *Kent Sibilev*
-
-
-## 1.0.1 (11 July, 2005) ##
-
-* Bind to Action Pack 1.9.1
-
-
-## 1.0.0 (6 July, 2005) ##
-
-* Avoid adding nil header values #1392
-
-* Better multipart support with implicit multipart/alternative and sorting of subparts *John Long*
-
-* Allow for nested parts in multipart mails #1570 *Flurin Egger*
-
-* Normalize line endings in outgoing mail bodies to "\n" #1536 *John Long*
-
-* Allow template to be explicitly specified #1448 *tuxie@dekadance.se*
-
-* Allow specific "multipart/xxx" content-type to be set on multipart messages #1412 *Flurin Egger*
-
-* Unquoted @ characters in headers are now accepted in spite of RFC 822 #1206
-
-* Helper support (borrowed from ActionPack)
-
-* Silently ignore Errno::EINVAL errors when converting text.
-
-* Don't cause an error when parsing an encoded attachment name #1340 *lon@speedymac.com*
-
-* Nested multipart message parts are correctly processed in TMail::Mail#body
-
-* BCC headers are removed when sending via SMTP #1402
-
-* Added 'content_type' accessor, to allow content type to be set on a per-message basis. content_type defaults to "text/plain".
-
-* Silently ignore Iconv::IllegalSequence errors when converting text #1341 *lon@speedymac.com*
-
-* Support attachments and multipart messages.
-
-* Added new accessors for the various mail properties.
-
-* Fix to only perform the charset conversion if a 'from' and a 'to' charset are given (make no assumptions about what the charset was) #1276 *Jamis Buck*
-
-* Fix attachments and content-type problems #1276 *Jamis Buck*
-
-* Fixed the TMail#body method to look at the content-transfer-encoding header and unquote the body according to the rules it specifies #1265 *Jamis Buck*
-
-* Added unquoting even if the iconv lib can't be loaded--in that case, only the charset conversion is skipped #1265 *Jamis Buck*
-
-* Added automatic decoding of base64 bodies #1214 *Jamis Buck*
-
-* Added that delivery errors are caught in a way so the mail is still returned whether the delivery was successful or not
-
-* Fixed that email address like "Jamis Buck, M.D." <wild.medicine@example.net> would cause the quoter to generate emails resulting in "bad address" errors from the mail server #1220 *Jamis Buck*
-
-
-## 0.9.1 (20th April, 2005) ##
-
-* Depend on Action Pack 1.8.1
-
-
-## 0.9.0 (19th April, 2005) ##
-
-* Added that deliver_* will now return the email that was sent
-
-* Added that quoting to UTF-8 only happens if the characters used are in that range #955 *Jamis Buck*
-
-* Fixed quoting for all address headers, not just to #955 *Jamis Buck*
-
-* Fixed unquoting of emails that doesn't have an explicit charset #1036 *wolfgang@stufenlos.net*
-
-
-## 0.8.1 (27th March, 2005) ##
-
-* Fixed that if charset was found that the end of a mime part declaration TMail would throw an error #919 *lon@speedymac.com*
-
-* Fixed that TMail::Unquoter would fail to recognize quoting method if it was in lowercase #919 *lon@speedymac.com*
-
-* Fixed that TMail::Encoder would fail when it attempts to parse e-mail addresses which are encoded using something other than the messages encoding method #919 *lon@speedymac.com*
-
-* Added rescue for missing iconv library and throws warnings if subject/body is called on a TMail object without it instead
-
-
-## 0.8.0 (22th March, 2005) ##
-
-* Added framework support for processing incoming emails with an Action Mailer class. See example in README.
-
-
-## 0.7.1 (7th March, 2005) ##
-
-* Bind to newest Action Pack (1.5.1)
-
-
-## 0.7.0 (24th February, 2005) ##
-
-* Added support for charsets for both subject and body. The default charset is now UTF-8 #673 [Jamis Buck]. Examples:
-
- def iso_charset(recipient)
- @recipients = recipient
- @subject = "testing iso charsets"
- @from = "system@loudthinking.com"
- @body = "Nothing to see here."
- @charset = "iso-8859-1"
- end
-
- def unencoded_subject(recipient)
- @recipients = recipient
- @subject = "testing unencoded subject"
- @from = "system@loudthinking.com"
- @body = "Nothing to see here."
- @encode_subject = false
- @charset = "iso-8859-1"
- end
-
-
-## 0.6.1 (January 18th, 2005) ##
-
-* Fixed sending of emails to use Tmail#from not the deprecated Tmail#from_address
-
-
-## 0.6 (January 17th, 2005) ##
-
-* Fixed that bcc and cc should be settable through @bcc and @cc -- not just @headers["Bcc"] and @headers["Cc"] #453 *Eric Hodel*
-
-* Fixed Action Mailer to be "warnings safe" so you can run with ruby -w and not get framework warnings #453 *Eric Hodel*
-
-
-## 0.5 ##
-
-* Added access to custom headers, like cc, bcc, and reply-to #268 [Andreas Schwarz]. Example:
-
- def post_notification(recipients, post)
- @recipients = recipients
- @from = post.author.email_address_with_name
- @headers["bcc"] = SYSTEM_ADMINISTRATOR_EMAIL
- @headers["reply-to"] = "notifications@example.com"
- @subject = "[#{post.account.name} #{post.title}]"
- @body["post"] = post
- end
-
-## 0.4 (5) ##
-
-* Consolidated the server configuration options into Base#server_settings= and expanded that with controls for authentication and more *Marten*
- NOTE: This is an API change that could potentially break your application if you used the old application form. Please do change!
-
-* Added Base#deliveries as an accessor for an array of emails sent out through that ActionMailer class when using the :test delivery option. *Jeremy Kemper*
-
-* Added Base#perform_deliveries= which can be set to false to turn off the actual delivery of the email through smtp or sendmail.
- This is especially useful for functional testing that shouldn't send off real emails, but still trigger delivery_* methods.
-
-* Added option to specify delivery method with Base#delivery_method=. Default is :smtp and :sendmail is currently the only other option.
- Sendmail is assumed to be present at "/usr/sbin/sendmail" if that option is used. *Kent Sibilev*
-
-* Dropped "include TMail" as it added to much baggage into the default namespace (like Version) *Chad Fowler*
-
-
-## 0.3 ##
-
-* First release
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/actionmailer/CHANGELOG.md) for previous changes.
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
index e45a1cd5ff..cfbe2f1cbd 100644
--- a/actionmailer/lib/action_mailer.rb
+++ b/actionmailer/lib/action_mailer.rb
@@ -26,17 +26,19 @@ require 'action_view'
require 'action_mailer/version'
# Common Active Support usage in Action Mailer
+require 'active_support/rails'
require 'active_support/core_ext/class'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/string/inflections'
require 'active_support/lazy_load_hooks'
module ActionMailer
extend ::ActiveSupport::Autoload
- autoload :Collector
+ eager_autoload do
+ autoload :Collector
+ end
+
autoload :Base
autoload :DeliveryMethods
autoload :MailHelper
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 150d435140..f5c325179f 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -1,6 +1,5 @@
require 'mail'
require 'action_mailer/collector'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/anonymous'
@@ -757,7 +756,7 @@ module ActionMailer #:nodoc:
responses << {
:body => render(:template => template),
- :content_type => template.mime_type.to_s
+ :content_type => template.type.to_s
}
end
end
diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb
index 5c03a29f0f..8679096735 100644
--- a/actionmailer/lib/action_mailer/railtie.rb
+++ b/actionmailer/lib/action_mailer/railtie.rb
@@ -5,6 +5,7 @@ require "abstract_controller/railties/routes_helpers"
module ActionMailer
class Railtie < Rails::Railtie
config.action_mailer = ActiveSupport::OrderedOptions.new
+ config.eager_load_namespaces << ActionMailer
initializer "action_mailer.logger" do
ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
index 529140dfad..108969ed4c 100644
--- a/actionmailer/lib/action_mailer/test_case.rb
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -1,5 +1,4 @@
require 'active_support/test_case'
-require 'active_support/core_ext/class/attribute'
module ActionMailer
class NonInferrableMailerError < ::StandardError
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index 4ed332d13d..c7b8f47d89 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -2,6 +2,7 @@
require 'abstract_unit'
require 'set'
+require 'action_dispatch'
require 'active_support/time'
require 'mailers/base_mailer'
@@ -493,14 +494,18 @@ class BaseTest < ActiveSupport::TestCase
end
test "assets tags should use a Mailer's asset_host settings when available" do
- ActionMailer::Base.config.asset_host = "global.com"
- ActionMailer::Base.config.assets_dir = "global/"
+ begin
+ ActionMailer::Base.config.asset_host = "http://global.com"
+ ActionMailer::Base.config.assets_dir = "global/"
- AssetMailer.asset_host = "http://local.com"
+ AssetMailer.asset_host = "http://local.com"
- mail = AssetMailer.welcome
+ mail = AssetMailer.welcome
- assert_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip)
+ assert_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip)
+ ensure
+ AssetMailer.asset_host = ActionMailer::Base.config.asset_host
+ end
end
# Before and After hooks
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 67c9e04ab2..1232370439 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,12 +1,173 @@
## Rails 4.0.0 (unreleased) ##
+* Added controller-level etag additions that will be part of the action etag computation *Jeremy Kemper/DHH*
+
+ class InvoicesController < ApplicationController
+ etag { current_user.try :id }
+
+ def show
+ # Etag will differ even for the same invoice when it's viewed by a different current_user
+ @invoice = Invoice.find(params[:id])
+ fresh_when(@invoice)
+ end
+ end
+
+* Add automatic template digests to all CacheHelper#cache calls (originally spiked in the cache_digests plugin) *DHH*
+
+* When building a URL fails, add missing keys provided by Journey. Failed URL
+ generation now returns a 500 status instead of a 404.
+
+ *Richard Schneeman*
+
+* Deprecate availbility of ActionView::RecordIdentifier in controllers by default.
+ It's view specific and can be easily included in controller manually if someone
+ really needs it. RecordIdentifier will be removed from ActionController::Base
+ in Rails 4.1 *Piotr Sarnacki*
+
+* Fix ActionView::RecordIdentifier to work as a singleton *Piotr Sarnacki*
+
+* Deprecate Template#mime_type, it will be removed in Rails 4.1 in favor of #type.
+ *Piotr Sarnacki*
+
+* Move vendored html-scanner from action_controller to action_view directory. If you
+ require it directly, please use 'action_view/vendor/html-scanner', reference to
+ 'action_controller/vendor/html-scanner' will be removed in Rails 4.1 *Piot Sarnacki*
+
+* Fix handling of date selects when using both disabled and discard options.
+ Fixes #7431.
+
+ *Vasiliy Ermolovich*
+
+* `ActiveRecord::SessionStore` is extracted out of Rails into a gem `activerecord-session_store`.
+ Setting `config.session_store` to `:active_record_store` will no longer work and will break
+ if the `activerecord-session_store` gem isn't available. *Prem Sichanugrist*
+
+* Fix select_tag when option_tags is nil.
+ Fixes #7404.
+
+ *Sandeep Ravichandran*
+
+* Add Request#formats=(extensions) that lets you set multiple formats directly in a prioritized order *DHH*
+
+ Example of using this for custom iphone views with an HTML fallback:
+
+ class ApplicationController < ActionController::Base
+ before_filter :adjust_format_for_iphone_with_html_fallback
+
+ private
+ def adjust_format_for_iphone_with_html_fallback
+ request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
+ end
+ end
+
+
+* Add Routing Concerns to declare common routes that can be reused inside
+ others resources and routes.
+
+ Code before:
+
+ resources :messages do
+ resources :comments
+ end
+
+ resources :posts do
+ resources :comments
+ resources :images, only: :index
+ end
+
+ Code after:
+
+ concern :commentable do
+ resources :comments
+ end
+
+ concern :image_attachable do
+ resources :images, only: :index
+ end
+
+ resources :messages, concerns: :commentable
+
+ resources :posts, concerns: [:commentable, :image_attachable]
+
+ *DHH + Rafael Mendonça França*
+
+* Add start_hour and end_hour options to the select_hour helper. *Evan Tann*
+
+* Raises an ArgumentError when the first argument in `form_for` contain `nil`
+ or is empty.
+
+ *Richard Schneeman*
+
+* Add 'X-Frame-Options' => 'SAMEORIGIN'
+ 'X-XSS-Protection' => '1; mode=block' and
+ 'X-Content-Type-Options' => 'nosniff'
+ as default headers.
+
+ *Egor Homakov*
+
+* Allow data attributes to be set as a first-level option for form_for, so you can write `form_for @record, data: { behavior: 'autosave' }` instead of `form_for @record, html: { data: { behavior: 'autosave' } }` *DHH*
+
+* Deprecate `button_to_function` and `link_to_function` helpers.
+
+ We recommend the use of Unobtrusive JavaScript instead. For example:
+
+ link_to "Greeting", "#", :class => "nav_link"
+
+ $(function() {
+ $('.nav_link').click(function() {
+ // Some complex code
+
+ return false;
+ });
+ });
+
+ or
+
+ link_to "Greeting", '#', onclick: "alert('Hello world!'); return false", class: "nav_link"
+
+ for simple cases.
+
+ *Rafael Mendonça França*
+
+* `javascript_include_tag :all` will now not include `application.js` if the file does not exists. *Prem Sichanugrist*
+
+* Send an empty response body when call `head` with status between 100 and 199, 204, 205 or 304.
+
+ *Armand du Plessis*
+
+* Fixed issue with where Digest authentication would not work behind a proxy. *Arthur Smith*
+
+* Added ActionController::Live. Mix it in to your controller and you can
+ stream data to the client live. For example:
+
+ class FooController < ActionController::Base
+ include ActionController::Live
+
+ def index
+ 100.times {
+ # Client will see this as it's written
+ response.stream.write "hello world\n"
+ sleep 1
+ }
+ response.stream.close
+ end
+ end
+
+* Remove ActionDispatch::Head middleware in favor of Rack::Head. *Santiago Pastorino*
+
+* Deprecate `:confirm` in favor of `:data => { :confirm => "Text" }` option for `button_to`, `button_tag`, `image_submit_tag`, `link_to` and `submit_tag` helpers.
+
+ *Carlos Galdino + Rafael Mendonça França*
+
+* Show routes in exception page while debugging a `RoutingError` in development. *Richard Schneeman and Mattt Thompson*
+
* Add `ActionController::Flash.add_flash_types` method to allow people to register their own flash types. e.g.:
class ApplicationController
add_flash_types :error, :warning
end
- If you add the above code, you can use `<%= error %>` in an erb, and `rediect_to /foo, :error => 'message'` in a controller.
+ If you add the above code, you can use `<%= error %>` in an erb, and `redirect_to /foo, :error => 'message'` in a controller.
*kennyj*
@@ -89,7 +250,7 @@
* Templates without a handler extension now raises a deprecation warning but still
defaults to ERb. In future releases, it will simply return the template contents. *Steve Klabnik*
-* Remove `:disable_with` in favor of `'data-disable-with'` option from `submit_tag`, `button_tag` and `button_to` helpers.
+* Deprecate `:disable_with` in favor of `:data => { :disable_with => "Text" }` option from `submit_tag`, `button_tag` and `button_to` helpers.
*Carlos Galdino + Rafael Mendonça França*
@@ -114,8 +275,6 @@
* Replace `include_seconds` boolean argument with `:include_seconds => true` option
in `distance_of_time_in_words` and `time_ago_in_words` signature. *Dmitriy Kiriyenko*
-* Remove `button_to_function` and `link_to_function` helpers. *Rafael Mendonça França*
-
* Make current object and counter (when it applies) variables accessible when
rendering templates with :object / :collection. *Carlos Antonio da Silva*
@@ -201,13 +360,13 @@
* Add `collection_check_boxes` form helper, similar to `collection_select`:
Example:
- collection_check_boxes :post, :author_ids, Author.all, :id, :name
- # Outputs something like:
- <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" />
- <label for="post_author_ids_1">D. Heinemeier Hansson</label>
- <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
- <label for="post_author_ids_2">D. Thomas</label>
- <input name="post[author_ids][]" type="hidden" value="" />
+ collection_check_boxes :post, :author_ids, Author.all, :id, :name
+ # Outputs something like:
+ <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" />
+ <label for="post_author_ids_1">D. Heinemeier Hansson</label>
+ <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
+ <label for="post_author_ids_2">D. Thomas</label>
+ <input name="post[author_ids][]" type="hidden" value="" />
The label/check_box pairs can be customized with a block.
@@ -216,12 +375,12 @@
* Add `collection_radio_buttons` form helper, similar to `collection_select`:
Example:
- collection_radio_buttons :post, :author_id, Author.all, :id, :name
- # Outputs something like:
- <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" />
- <label for="post_author_id_1">D. Heinemeier Hansson</label>
- <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
- <label for="post_author_id_2">D. Thomas</label>
+ collection_radio_buttons :post, :author_id, Author.all, :id, :name
+ # Outputs something like:
+ <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" />
+ <label for="post_author_id_1">D. Heinemeier Hansson</label>
+ <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
+ <label for="post_author_id_2">D. Thomas</label>
The label/radio_button pairs can be customized with a block.
@@ -264,6011 +423,4 @@
* `ActionView::Helpers::TextHelper#highlight` now defaults to the
HTML5 `mark` element. *Brian Cardarella*
-
-## Rails 3.2.5 (Jun 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.4 (May 31, 2012) ##
-
-* Deprecate old APIs for highlight, excerpt and word_wrap *Jeremy Walker*
-
-* Deprecate `:disable_with` in favor of `'data-disable-with'` option for `button_to`, `button_tag` and `submit_tag` helpers.
-
- *Carlos Galdino + Rafael Mendonça França*
-
-* Deprecate `:mouseover` option for `image_tag` helper. *Rafael Mendonça França*
-
-* Deprecate `button_to_function` and `link_to_function` helpers. *Rafael Mendonça França*
-
-* Don't break Haml with textarea newline fix. GH #393, #4000, #5190, #5191
-
-* Fix options handling on labels. GH #2492, #5614
-
-* Added config.action_view.embed_authenticity_token_in_remote_forms to deal
- with regression from 16ee611fa
-
-* Set rendered_format when doing render :inline. GH #5632
-
-* Fix the redirect when it receive blocks with arity of 1. Closes #5677
-
-* Strip [nil] from parameters hash. Thanks to Ben Murphy for
- reporting this! CVE-2012-2660
-
-
-## Rails 3.2.3 (March 30, 2012) ##
-
-* Add `config.action_view.embed_authenticity_token_in_remote_forms` (defaults to true) which allows to set if authenticity token will be included by default in remote forms. If you change it to false, you can still force authenticity token by passing `:authenticity_token => true` in form options *Piotr Sarnacki*
-
-* Do not include the authenticity token in forms where remote: true as ajax forms use the meta-tag value *DHH*
-
-* Upgrade rack-cache to 1.2. *José Valim*
-
-* ActionController::SessionManagement is removed. *Santiago Pastorino*
-
-* Since the router holds references to many parts of the system like engines, controllers and the application itself, inspecting the route set can actually be really slow, therefore we default alias inspect to to_s. *José Valim*
-
-* Add a new line after the textarea opening tag. Closes #393 *Rafael Mendonça França*
-
-* Always pass a respond block from to responder. We should let the responder decide what to do with the given overridden response block, and not short circuit it. *Prem Sichanugrist*
-
-* Fixes layout rendering regression from 3.2.2. *José Valim*
-
-
-## Rails 3.2.2 (March 1, 2012) ##
-
-* Format lookup for partials is derived from the format in which the template is being rendered. Closes #5025 part 2 *Santiago Pastorino*
-
-* Use the right format when a partial is missing. Closes #5025. *Santiago Pastorino*
-
-* Default responder will now always use your overridden block in `respond_with` to render your response. *Prem Sichanugrist*
-
-* check_box helper with :disabled => true will generate a disabled hidden field to conform with the HTML convention where disabled fields are not submitted with the form.
- This is a behavior change, previously the hidden tag had a value of the disabled checkbox.
- *Tadas Tamosauskas*
-
-
-## Rails 3.2.1 (January 26, 2012) ##
-
-* Documentation improvements.
-
-* Allow `form.select` to accept ranges (regression). *Jeremy Walker*
-
-* `datetime_select` works with -/+ infinity dates. *Joe Van Dyk*
-
-
-## Rails 3.2.0 (January 20, 2012) ##
-
-* Add `config.action_dispatch.default_charset` to configure default charset for ActionDispatch::Response. *Carlos Antonio da Silva*
-
-* Deprecate setting default charset at controller level, use the new `config.action_dispatch.default_charset` instead. *Carlos Antonio da Silva*
-
-* Deprecate ActionController::UnknownAction in favour of AbstractController::ActionNotFound. *Carlos Antonio da Silva*
-
-* Deprecate ActionController::DoubleRenderError in favour of AbstractController::DoubleRenderError. *Carlos Antonio da Silva*
-
-* Deprecate method_missing handling for not found actions, use action_missing instead. *Carlos Antonio da Silva*
-
-* Deprecate ActionController#rescue_action, ActionController#initialize_template_class, and ActionController#assign_shortcuts.
- These methods were not being used internally anymore and are going to be removed in Rails 4. *Carlos Antonio da Silva*
-
-* Use a BodyProxy instead of including a Module that responds to
- close. Closes #4441 if Active Record is disabled assets are delivered
- correctly *Santiago Pastorino*
-
-* Rails initialization with initialize_on_precompile = false should set assets_dir *Santiago Pastorino*
-
-* Add font_path helper method *Santiago Pastorino*
-
-* Depends on rack ~> 1.4.0 *Santiago Pastorino*
-
-* Add :gzip option to `caches_page`. The default option can be configured globally using `page_cache_compression` *Andrey Sitnik*
-
-* The ShowExceptions middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the PATH_INFO rewritten to the status code. *José Valim*
-
-* Add `button_tag` support to ActionView::Helpers::FormBuilder.
-
- This support mimics the default behavior of `submit_tag`.
-
- Example:
-
- <%= form_for @post do |f| %>
- <%= f.button %>
- <% end %>
-
-* Date helpers accept a new option, `:use_two_digit_numbers = true`, that renders select boxes for months and days with a leading zero without changing the respective values.
- For example, this is useful for displaying ISO8601-style dates such as '2011-08-01'. *Lennart Fridén and Kim Persson*
-
-* Make ActiveSupport::Benchmarkable a default module for ActionController::Base, so the #benchmark method is once again available in the controller context like it used to be *DHH*
-
-* Deprecated implied layout lookup in controllers whose parent had a explicit layout set:
-
- class ApplicationController
- layout "application"
- end
-
- class PostsController < ApplicationController
- end
-
- In the example above, Posts controller will no longer automatically look up for a posts layout.
-
- If you need this functionality you could either remove `layout "application"` from ApplicationController or explicitly set it to nil in PostsController. *José Valim*
-
-* Rails will now use your default layout (such as "layouts/application") when you specify a layout with `:only` and `:except` condition, and those conditions fail. *Prem Sichanugrist*
-
- For example, consider this snippet:
-
- class CarsController
- layout 'single_car', :only => :show
- end
-
- Rails will use 'layouts/single_car' when a request comes in `:show` action, and use 'layouts/application' (or 'layouts/cars', if exists) when a request comes in for any other actions.
-
-* form_for with +:as+ option uses "#{action}_#{as}" as css class and id:
-
- Before:
-
- form_for(@user, :as => 'client') # => "<form class="client_new">..."
-
- Now:
-
- form_for(@user, :as => 'client') # => "<form class="new_client">..."
-
- *Vasiliy Ermolovich*
-
-* Allow rescue responses to be configured through a railtie as in `config.action_dispatch.rescue_responses`. Please look at ActiveRecord::Railtie for an example *José Valim*
-
-* Allow fresh_when/stale? to take a record instead of an options hash *DHH*
-
-* Assets should use the request protocol by default or default to relative if no request is available *Jonathan del Strother*
-
-* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts *José Valim*
-
-* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements.
- The namespace attribute will be prefixed with underscore on the generate HTML id. *Vasiliy Ermolovich*
-
- Example:
-
- <%= form_for(@offer, :namespace => 'namespace') do |f| %>
- <%= f.label :version, 'Version' %>:
- <%= f.text_field :version %>
- <% end %>
-
-* Refactor ActionDispatch::ShowExceptions. The controller is responsible for choosing to show exceptions when `consider_all_requests_local` is false.
-
- It's possible to override `show_detailed_exceptions?` in controllers to specify which requests should provide debugging information on errors. The default value is now false, meaning local requests in production will no longer show the detailed exceptions page unless `show_detailed_exceptions?` is overridden and set to `request.local?`.
-
-* Responders now return 204 No Content for API requests without a response body (as in the new scaffold) *José Valim*
-
-* Added ActionDispatch::RequestId middleware that'll make a unique X-Request-Id header available to the response and enables the ActionDispatch::Request#uuid method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog *DHH*
-
-* Limit the number of options for select_year to 1000.
-
- Pass the :max_years_allowed option to set your own limit.
-
- *Libo Cannici*
-
-* Passing formats or handlers to render :template and friends is deprecated. For example: *Nick Sutterer & José Valim*
-
- render :template => "foo.html.erb"
-
- Instead, you can provide :handlers and :formats directly as option:
- render :template => "foo", :formats => [:html, :js], :handlers => :erb
-
-* Changed log level of warning for missing CSRF token from :debug to :warn. *Mike Dillon*
-
-* content_tag_for and div_for can now take the collection of records. It will also yield the record as the first argument if you set a receiving argument in your block *Prem Sichanugrist*
-
- So instead of having to do this:
-
- @items.each do |item|
- content_tag_for(:li, item) do
- Title: <%= item.title %>
- end
- end
-
- You can now do this:
-
- content_tag_for(:li, @items) do |item|
- Title: <%= item.title %>
- end
-
-* send_file now guess the mime type *Esad Hajdarevic*
-
-* Mime type entries for PDF, ZIP and other formats were added *Esad Hajdarevic*
-
-* Generate hidden input before select with :multiple option set to true.
- This is useful when you rely on the fact that when no options is set,
- the state of select will be sent to rails application. Without hidden field
- nothing is sent according to HTML spec *Bogdan Gusiev*
-
-* Refactor ActionController::TestCase cookies *Andrew White*
-
- Assigning cookies for test cases should now use cookies[], e.g:
-
- cookies[:email] = 'user@example.com'
- get :index
- assert_equal 'user@example.com', cookies[:email]
-
- To clear the cookies, use clear, e.g:
-
- cookies.clear
- get :index
- assert_nil cookies[:email]
-
- We now no longer write out HTTP_COOKIE and the cookie jar is
- persistent between requests so if you need to manipulate the environment
- for your test you need to do it before the cookie jar is created.
-
-* ActionController::ParamsWrapper on ActiveRecord models now only wrap
- attr_accessible attributes if they were set, if not, only the attributes
- returned by the class method attribute_names will be wrapped. This fixes
- the wrapping of nested attributes by adding them to attr_accessible.
-
-
-## Rails 3.1.4 (March 1, 2012) ##
-
-* Skip assets group in Gemfile and all assets configurations options
- when the application is generated with --skip-sprockets option.
-
- *Guillermo Iguaran*
-
-* Use ProcessedAsset#pathname in Sprockets helpers when debugging is on. Closes #3333 #3348 #3361.
-
- *Guillermo Iguaran*
-
-* Allow to use asset_path on named_routes aliasing RailsHelper's
- asset_path to path_to_asset *Adrian Pike*
-
-* Assets should use the request protocol by default or default to relative if no request is available *Jonathan del Strother*
-
-
-## Rails 3.1.3 (November 20, 2011) ##
-
-* Downgrade sprockets to ~> 2.0.3. Using 2.1.0 caused regressions.
-
-* Fix using `translate` helper with a html translation which uses the `:count` option for
- pluralization.
-
- *Jon Leighton*
-
-
-## Rails 3.1.2 (November 18, 2011) ##
-
-* Fix XSS security vulnerability in the `translate` helper method. When using interpolation
- in combination with HTML-safe translations, the interpolated input would not get HTML
- escaped. *GH 3664*
-
- Before:
-
- translate('foo_html', :something => '<script>') # => "...<script>..."
-
- After:
-
- translate('foo_html', :something => '<script>') # => "...&lt;script&gt;..."
-
- *Sergey Nartimov*
-
-* Upgrade sprockets dependency to ~> 2.1.0
-
-* Ensure that the format isn't applied twice to the cache key, else it becomes impossible
- to target with expire_action.
-
- *Christopher Meiklejohn*
-
-* Swallow error when can't unmarshall object from session.
-
- *Bruno Zanchet*
-
-* Implement a workaround for a bug in ruby-1.9.3p0 where an error would be raised
- while attempting to convert a template from one encoding to another.
-
- Please see http://redmine.ruby-lang.org/issues/5564 for details of the bug.
-
- The workaround is to load all conversions into memory ahead of time, and will
- only happen if the ruby version is *exactly* 1.9.3p0. The hope is obviously that
- the underlying problem will be resolved in the next patchlevel release of
- 1.9.3.
-
- *Jon Leighton*
-
-* Ensure users upgrading from 3.0.x to 3.1.x will properly upgrade their flash object in session (issues #3298 and #2509)
-
-
-## Rails 3.1.1 (October 07, 2011) ##
-
-* javascript_path and stylesheet_path now refer to /assets if asset pipelining
- is on. *Santiago Pastorino*
-
-* button_to support form option. Now you're able to pass for example
- 'data-type' => 'json'. *ihower*
-
-* image_path and image_tag should use /assets if asset pipelining is turned
- on. Closes #3126 *Santiago Pastorino and christos*
-
-* Avoid use of existing precompiled assets during rake assets:precompile run.
- Closes #3119 *Guillermo Iguaran*
-
-* Copy assets to nondigested filenames too *Santiago Pastorino*
-
-* Give precedence to `config.digest = false` over the existence of
- manifest.yml asset digests *christos*
-
-* escape options for the stylesheet_link_tag method *Alexey Vakhov*
-
-* Re-launch assets:precompile task using (Rake.)ruby instead of Kernel.exec so
- it works on Windows *cablegram*
-
-* env var passed to process shouldn't be modified in process method. *Santiago
- Pastorino*
-
-* `rake assets:precompile` loads the application but does not initialize
- it.
- To the app developer, this means configuration add in
- config/initializers/* will not be executed.
- Plugins developers need to special case their initializers that are
- meant to be run in the assets group by adding :group => :assets. *José Valim*
-
-* Sprockets uses config.assets.prefix for asset_path *asee*
-
-* FileStore key_file_path properly limit filenames to 255 characters. *phuibonhoa*
-
-* Fix Hash#to_query edge case with html_safe strings. *brainopia*
-
-* Allow asset tag helper methods to accept :digest => false option in order to completely avoid the digest generation.
- Useful for linking assets from static html files or from emails when the user could probably look at an older html email with an older asset. *Santiago Pastorino*
-
-* Don't mount Sprockets server at config.assets.prefix if config.assets.compile is false. *Mark J. Titorenko*
-
-* Set relative url root in assets when controller isn't available for Sprockets (eg. Sass files using asset_path). Fixes #2435 *Guillermo Iguaran*
-
-* Fix basic auth credential generation to not make newlines. GH #2882
-
-* Fixed the behavior of asset pipeline when config.assets.digest and config.assets.compile are false and requested asset isn't precompiled.
- Before the requested asset were compiled anyway ignoring that the config.assets.compile flag is false. *Guillermo Iguaran*
-
-* CookieJar is now Enumerable. Fixes #2795
-
-* Fixed AssetNotPrecompiled error raised when rake assets:precompile is compiling certain .erb files. See GH #2763 #2765 #2805 *Guillermo Iguaran*
-
-* Manifest is correctly placed in assets path when default assets prefix is changed. Fixes #2776 *Guillermo Iguaran*
-
-* Fixed stylesheet_link_tag and javascript_include_tag to respect additional options passed by the users when debug is on. *Guillermo Iguaran*
-
-
-## Rails 3.1.0 (August 30, 2011) ##
-
-* Param values are `paramified` in controller tests. *David Chelimsky*
-
-* x_sendfile_header now defaults to nil and config/environments/production.rb doesn't set a particular value for it. This allows servers to set it through X-Sendfile-Type. *Santiago Pastorino*
-
-* The submit form helper does not generate an id "object_name_id" anymore. *fbrusatti*
-
-* Make sure respond_with with :js tries to render a template in all cases *José Valim*
-
-* json_escape will now return a SafeBuffer string if it receives SafeBuffer string *tenderlove*
-
-* Make sure escape_js returns SafeBuffer string if it receives SafeBuffer string *Prem Sichanugrist*
-
-* Fix escape_js to work correctly with the new SafeBuffer restriction *Paul Gallagher*
-
-* Brought back alternative convention for namespaced models in i18n *thoefer*
-
- Now the key can be either "namespace.model" or "namespace/model" until further deprecation.
-
-* It is prohibited to perform a in-place SafeBuffer mutation *tenderlove*
-
- The old behavior of SafeBuffer allowed you to mutate string in place via
- method like `sub!`. These methods can add unsafe strings to a safe buffer,
- and the safe buffer will continue to be marked as safe.
-
- An example problem would be something like this:
-
- <%= link_to('hello world', @user).sub!(/hello/, params[:xss]) %>
-
- In the above example, an untrusted string (`params[:xss]`) is added to the
- safe buffer returned by `link_to`, and the untrusted content is successfully
- sent to the client without being escaped. To prevent this from happening
- `sub!` and other similar methods will now raise an exception when they are called on a safe buffer.
-
- In addition to the in-place versions, some of the versions of these methods which return a copy of the string will incorrectly mark strings as safe. For example:
-
- <%= link_to('hello world', @user).sub(/hello/, params[:xss]) %>
-
- The new versions will now ensure that *all* strings returned by these methods on safe buffers are marked unsafe.
-
- You can read more about this change in http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2e516e7acc96c4fb
-
-* Warn if we cannot verify CSRF token authenticity *José Valim*
-
-* Allow AM/PM format in datetime selectors *Aditya Sanghi*
-
-* Only show dump of regular env methods on exception screen (not all the rack crap) *DHH*
-
-* auto_link has been removed with no replacement. If you still use auto_link
- please install the rails_autolink gem:
- http://github.com/tenderlove/rails_autolink
-
- *tenderlove*
-
-* Added streaming support, you can enable it with: *José Valim*
-
- class PostsController < ActionController::Base
- stream :only => :index
- end
-
- Please read the docs at `ActionController::Streaming` for more information.
-
-* Added `ActionDispatch::Request.ignore_accept_header` to ignore accept headers and only consider the format given as parameter *José Valim*
-
-* Created `ActionView::Renderer` and specified an API for `ActionView::Context`, check those objects for more information *José Valim*
-
-* Added `ActionController::ParamsWrapper` to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default *Prem Sichanugrist*
-
- This can be customized by setting `ActionController::Base.wrap_parameters` in `config/initializer/wrap_parameters.rb`
-
-* RJS has been extracted out to a gem. *fxn*
-
-* Implicit actions named not_implemented can be rendered. *Santiago Pastorino*
-
-* Wildcard route will always match the optional format segment by default. *Prem Sichanugrist*
-
- For example if you have this route:
-
- match '*pages' => 'pages#show'
-
- by requesting '/foo/bar.json', your `params[:pages]` will be equals to "foo/bar" with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `:format => false` like this:
-
- match '*pages' => 'pages#show', :format => false
-
-* Added Base.http_basic_authenticate_with to do simple http basic authentication with a single class method call *DHH*
-
- class PostsController < ApplicationController
- USER_NAME, PASSWORD = "dhh", "secret"
-
- before_filter :authenticate, :except => [ :index ]
-
- def index
- render :text => "Everyone can see me!"
- end
-
- def edit
- render :text => "I'm only accessible if you know the password"
- end
-
- private
- def authenticate
- authenticate_or_request_with_http_basic do |user_name, password|
- user_name == USER_NAME && password == PASSWORD
- end
- end
- end
-
- ..can now be written as
-
- class PostsController < ApplicationController
- http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
-
- def index
- render :text => "Everyone can see me!"
- end
-
- def edit
- render :text => "I'm only accessible if you know the password"
- end
- end
-
-* Allow you to add `force_ssl` into controller to force browser to transfer data via HTTPS protocol on that particular controller. You can also specify `:only` or `:except` to specific it to particular action. *DHH and Prem Sichanugrist*
-
-* Allow FormHelper#form_for to specify the :method as a direct option instead of through the :html hash *DHH*
-
- form_for(@post, remote: true, method: :delete) instead of form_for(@post, remote: true, html: { method: :delete })
-
-* Make JavaScriptHelper#j() an alias for JavaScriptHelper#escape_javascript() -- note this then supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper *DHH*
-
-* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. *Prem Sichanugrist, fxn*
-
-* URL parameters which return false for to_param now appear in the query string (previously they were removed) *Andrew White*
-
-* URL parameters which return nil for to_param are now removed from the query string *Andrew White*
-
-* ActionDispatch::MiddlewareStack now uses composition over inheritance. It is
- no longer an array which means there may be methods missing that were not tested.
-
-* Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). *Jakub Kuźma, Igor Wiedler*
-
-* HTML5 button_tag helper. *Rizwan Reza*
-
-* Template lookup now searches further up in the inheritance chain. *Artemave*
-
-* Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. *Piotr Sarnacki*
-
-* url_for and named url helpers now accept :subdomain and :domain as options, *Josh Kalderimis*
-
-* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). *Josh Kalderimis*
-
-* Added config.action_controller.include_all_helpers. By default 'helper :all' is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and helper corresponding to controller (like foo_helper for foo_controller). *Piotr Sarnacki*
-
-* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:
-
- tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
- # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
-
- Keys are dasherized. Values are JSON-encoded, except for strings and symbols. *Stephen Celis*
-
-* Deprecate old template handler API. The new API simply requires a template handler to respond to call. *José Valim*
-
-* :rhtml and :rxml were finally removed as template handlers. *José Valim*
-
-* Moved etag responsibility from ActionDispatch::Response to the middleware stack. *José Valim*
-
-* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept 4 arguments and requires #destroy_session instead of simply #destroy. *José Valim*
-
-* file_field automatically adds :multipart => true to the enclosing form. *Santiago Pastorino*
-
-* Renames csrf_meta_tag -> csrf_meta_tags, and aliases csrf_meta_tag for backwards compatibility. *fxn*
-
-* Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. *Yehuda Katz, Carl Lerche*
-
-
-## Rails 3.0.12 (March 1, 2012) ##
-
-* Fix using `tranlate` helper with a html translation which uses the `:count` option for
- pluralization.
-
- *Jon Leighton*
-
-
-## Rails 3.0.11 (November 18, 2011) ##
-
-* Fix XSS security vulnerability in the `translate` helper method. When using interpolation
- in combination with HTML-safe translations, the interpolated input would not get HTML
- escaped. *GH 3664*
-
- Before:
-
- translate('foo_html', :something => '<script>') # => "...<script>..."
-
- After:
-
- translate('foo_html', :something => '<script>') # => "...&lt;script&gt;..."
-
- *Sergey Nartimov*
-
-* Implement a workaround for a bug in ruby-1.9.3p0 where an error would be
- raised while attempting to convert a template from one encoding to another.
-
- Please see http://redmine.ruby-lang.org/issues/5564 for details of the bug.
-
- The workaround is to load all conversions into memory ahead of time, and will
- only happen if the ruby version is exactly 1.9.3p0. The hope is obviously
- that the underlying problem will be resolved in the next patchlevel release
- of 1.9.3.
-
-* Fix assert_select_email to work on multipart and non-multipart emails as the method stopped working correctly in Rails 3.x due to changes in the new mail gem.
-
-* Fix url_for when passed a hash to prevent additional options (eg. :host, :protocol) from being added to the hash after calling it.
-
-
-## Rails 3.0.10 (August 16, 2011) ##
-
-* Fixes an issue where cache sweepers with only after filters would have no
- controller object, it would raise undefined method controller_name for nil [jeroenj]
-
-* Ensure status codes are logged when exceptions are raised.
-
-* Subclasses of OutputBuffer are respected.
-
-* Fixed ActionView::FormOptionsHelper#select with :multiple => false
-
-* Avoid extra call to Cache#read in case of a fragment cache hit
-
-
-## Rails 3.0.9 (June 16, 2011) ##
-
-* json_escape will now return a SafeBuffer string if it receives SafeBuffer string [tenderlove]
-
-* Make sure escape_js returns SafeBuffer string if it receives SafeBuffer string [Prem Sichanugrist]
-
-* Fix text helpers to work correctly with the new SafeBuffer restriction [Paul Gallagher, Arun Agrawal, Prem Sichanugrist]
-
-
-## Rails 3.0.8 (June 7, 2011) ##
-
-* It is prohibited to perform a in-place SafeBuffer mutation [tenderlove]
-
- The old behavior of SafeBuffer allowed you to mutate string in place via
- method like `sub!`. These methods can add unsafe strings to a safe buffer,
- and the safe buffer will continue to be marked as safe.
-
- An example problem would be something like this:
-
- <%= link_to('hello world', @user).sub!(/hello/, params[:xss]) %>
-
- In the above example, an untrusted string (`params[:xss]`) is added to the
- safe buffer returned by `link_to`, and the untrusted content is successfully
- sent to the client without being escaped. To prevent this from happening
- `sub!` and other similar methods will now raise an exception when they are called on a safe buffer.
-
- In addition to the in-place versions, some of the versions of these methods which return a copy of the string will incorrectly mark strings as safe. For example:
-
- <%= link_to('hello world', @user).sub(/hello/, params[:xss]) %>
-
- The new versions will now ensure that *all* strings returned by these methods on safe buffers are marked unsafe.
-
- You can read more about this change in http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2e516e7acc96c4fb
-
-* Fixed github issue #342 with asset paths and relative roots.
-
-
-## Rails 3.0.7 (April 18, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.6 (April 5, 2011) ##
-
-* Fixed XSS vulnerability in `auto_link`. `auto_link` no longer marks input as
- html safe. Please make sure that calls to auto_link() are wrapped in a
- sanitize(), or a raw() depending on the type of input passed to auto_link().
- For example:
-
- <%= sanitize(auto_link(some_user_input)) %>
-
- Thanks to Torben Schulz for reporting this. The fix can be found here:
- 61ee3449674c591747db95f9b3472c5c3bd9e84d
-
-* Fixes the output of `rake routes` to be correctly match to the behavior of the application, as the regular expression used to match the path is greedy and won't capture the format part by default *Prem Sichanugrist*
-
-* Fixes an issue with number_to_human when converting values which are less than 1 but greater than -1 *Josh Kalderimis*
-
-* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. *Prem Sichanugrist, fxn*
-
-* URL parameters which return nil for to_param are now removed from the query string *Andrew White*
-
-* Don't allow i18n to change the minor version, version now set to ~> 0.5.0 *Santiago Pastorino*
-
-* Make TranslationHelper#translate use the :rescue_format option in I18n 0.5.0 *Sven Fuchs*
-
-* Fix regression: javascript_include_tag shouldn't raise if you register an expansion key with nil or [] value *Santiago Pastorino*
-
-* Fix Action caching bug where an action that has a non-cacheable response always renders a nil response body. It now correctly renders the response body. *Cheah Chu Yeow*
-
-
-## Rails 3.0.5 (February 26, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.4 (February 8, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.3 (November 16, 2010) ##
-
-* When ActiveRecord::Base objects are sent to predicate methods, the id of the object should be sent to ARel, not the ActiveRecord::Base object.
-
-* :constraints routing should only do sanity checks against regular expressions. String arguments are OK.
-
-
-## Rails 3.0.2 (November 15, 2010) ##
-
-* The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. *Don Wilson*
-
-
-## Rails 3.0.1 (October 15, 2010) ##
-
-* No Changes, just a version bump.
-
-
-## Rails 3.0.0 (August 29, 2010) ##
-
-* password_field renders with nil value by default making the use of passwords secure by default, if you want to render you should do for instance f.password_field(:password, :value => @user.password) *Santiago Pastorino*
-
-* Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. *José Valim*
-
-* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. *José Valim*
-
-* Support routing constraints in functional tests. *Andrew White*
-
-* Add a header that tells Internet Explorer (all versions) to use the best available standards support. *Yehuda Katz*
-
-* Allow stylesheet/javascript extensions to be changed through railties. *Josh Kalderimis*
-
-* link_to, button_to, and tag/tag_options now rely on html_escape instead of escape_once. *fxn*
-
-* url_for returns always unescaped strings, and the :escape option is gone. *fxn*
-
-* Added accept-charset parameter and _snowman hidden field to force the contents
- of Rails POSTed forms to be in UTF-8 *Yehuda Katz*
-
-* Upgrade to Rack 1.2.1 *Jeremy Kemper*
-
-* Allow :path to be given to match/get/post/put/delete instead of :path_names in the new router *Carlos Antônio da Silva*
-
-* Added resources_path_names to the new router DSL *José Valim*
-
-* Allow options to be given to the namespace method in the new router *Carlos Antônio da Silva*
-
-* Deprecate :name_prefix in the new router DSL *José Valim*
-
-* Add shallow routes back to the new router *Diego Carrion, Andrew White*
-
- resources :posts do
- shallow do
- resources :comments
- end
- end
-
- You can now use comment_path for /comments/1 instead of post_comment_path for /posts/1/comments/1.
-
-* Add support for multi-subdomain session by setting cookie host in session cookie so you can share session between www.example.com, example.com and user.example.com. #4818 *Guillermo Álvarez*
-
-* Removed textilize, textilize_without_paragraph and markdown helpers. *Santiago Pastorino*
-
-* Remove middleware laziness *José Valim*
-
-* Make session stores rely on request.cookie_jar and change set_session semantics to return the cookie value instead of a boolean. *José Valim*
-
-* OAuth 2: HTTP Token Authorization support to complement Basic and Digest Authorization. *Rick Olson*
-
-* Fixed inconsistencies in form builder and view helpers #4432 *Neeraj Singh*
-
-* Both :xml and :json renderers now forwards the given options to the model, allowing you to invoke them as render :xml => @projects, :include => :tasks *José Valim, Yehuda Katz*
-
-* Renamed the field error CSS class from fieldWithErrors to field_with_errors for consistency. *Jeremy Kemper*
-
-* Add support for shorthand routes like /projects/status(.:format) #4423 *Diego Carrion*
-
-* Changed translate helper so that it doesn’t mark every translation as safe HTML. Only keys with a "_html" suffix and keys named "html" are considered to be safe HTML. All other translations are left untouched. *Craig Davey*
-
-* New option :as added to form_for allows to change the object name. The old <% form_for :client, @post %> becomes <% form_for @post, :as => :client %> *spastorino*
-
-* Removed verify method in controllers. *JV*
- It's now available as a plugin at http://github.com/rails/verification
-
-* Removed input, form, error_messages_for and error_message_on from views. *JV*
- It's now available as a plugin at http://github.com/rails/dynamic_form
-
-* Routes can be scoped by controller module. *Jeremy Kemper*
-
- # /session => Auth::SessionsController
- scope :module => 'auth' do
- resource :session
- end
-
-* Added #favicon_link_tag, it uses #image_path so in particular the favicon gets an asset ID *fxn*
-
-* Fixed that default locale templates should be used if the current locale template is missing *DHH*
-
-* Added all the new HTML5 form types as individual form tag methods (search, url, number, etc) #3646 *Stephen Celis*
-
-* Changed the object used in routing constraints to be an instance of
- ActionDispatch::Request rather than Rack::Request *YK*
-
-* Changed ActionDispatch::Request#method to return a String, to be compatible
- with Rack::Request. Added ActionDispatch::Request#method_symbol to
- return a symbol form of the request method. *YK*
-
-* Changed ActionDispatch::Request#method to return the original
- method and #request_method to return the overridden method in the
- case of methodoverride being used (this means that #method returns
- "HEAD" and #request_method returns "GET" in HEAD requests). This
- is for compatibility with Rack::Request *YK*
-
-* #concat is now deprecated in favor of using <%= %> helpers *YK*
-
-* Block helpers now return Strings, so you can use <%= form_for @foo do |f| %>.
- <% form_for do |f| %> still works with deprecation notices *YK*
-
-* Add a new #mount method on the router that does not anchor the PATH_INFO
- at the end *YK & CL*
-
-* Create a new LookupContext object that is responsible for performantly
- finding a template for a given pattern *JV*
-
-* Removed relative_url_for in favor of respecting SCRIPT_NAME *YK & CL*
-
-* Changed file streaming to use Rack::Sendfile middleware *YK*
-
-* ActionDispatch::Request#content_type returns a String to be compatible with
- Rack::Request. Use #content_mime_type for the Mime::Type instance *YK*
-
-* Updated Prototype to 1.6.1 and Scriptaculous to 1.8.3 *ML*
-
-* Change the preferred way that URL helpers are included into a class*YK & CL*
-
- # for all helpers including named routes
- include Rails.application.router.url_helpers
-
- # for just url_for
- include Rails.application.router.url_for
-
-* Fixed that PrototypeHelper#update_page should return html_safe *DHH*
-
-* Fixed that much of DateHelper wouldn't return html_safe? strings *DHH*
-
-* Fixed that fragment caching should return a cache hit as html_safe (or it would all just get escaped) *DHH*
-
-* Added that ActionController::Base now does helper :all instead of relying on the default ApplicationController in Rails to do it *DHH*
-
-* Added ActionDispatch::Request#authorization to access the http authentication header regardless of its proxy hiding *DHH*
-
-* Added :alert, :notice, and :flash as options to ActionController::Base#redirect_to that'll automatically set the proper flash before the redirection *DHH*. Examples:
-
- flash[:notice] = 'Post was created'
- redirect_to(@post)
-
- ...becomes:
-
- redirect_to(@post, :notice => 'Post was created')
-
-* Added ActionController::Base#notice/= and ActionController::Base#alert/= as a convenience accessors in both the controller and the view for flash[:notice]/= and flash[:alert]/= *DHH*
-
-* Introduce grouped_collection_select helper. #1249 *Dan Codeape, Erik Ostrom*
-
-* Make sure javascript_include_tag/stylesheet_link_tag does not append ".js" or ".css" onto external urls. #1664 *Matthew Rudy Jacobs*
-
-* Ruby 1.9: fix Content-Length for multibyte send_data streaming. #2661 *Sava Chankov*
-
-* Ruby 1.9: ERB template encoding using a magic comment at the top of the file. *Jeremy Kemper*
- <%# encoding: utf-8 %>
-
-* Change integration test helpers to accept Rack environment instead of just HTTP Headers *Pratik Naik*
-
- Before : get '/path', {}, 'Accept' => 'text/javascript'
- After : get '/path', {}, 'HTTP_ACCEPT' => 'text/javascript'
-
-* Instead of checking Rails.env.test? in Failsafe middleware, check env["rails.raise_exceptions"] *Bryan Helmkamp*
-
-* Fixed that TestResponse.cookies was returning cookies unescaped #1867 *Doug McInnes*
-
-
-## 2.3.2 Final (March 15, 2009) ##
-
-* Fixed that redirection would just log the options, not the final url (which lead to "Redirected to #<Post:0x23150b8>") *DHH*
-
-* Don't check authenticity tokens for any AJAX requests *Ross Kaffenberger/Bryan Helmkamp*
-
-* Added ability to pass in :public => true to fresh_when, stale?, and expires_in to make the request proxy cachable #2095 *Gregg Pollack*
-
-* Fixed that passing a custom form builder would be forwarded to nested fields_for calls #2023 *Eloy Duran/Nate Wiger*
-
-* Form option helpers now support disabled option tags and the use of lambdas for selecting/disabling option tags from collections #837 *Tekin*
-
-* Added partial scoping to TranslationHelper#translate, so if you call translate(".foo") from the people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo") *DHH*
-
-* Fix a syntax error in current_page?() that was prevent matches against URL's with multiple query parameters #1385, #1868 *chris finne/Andrew White*
-
-* Added localized rescue template when I18n.locale is set (ex: public/404.da.html) #1835 *José Valim*
-
-* Make the form_for and fields_for helpers support the new Active Record nested update options. #1202 *Eloy Duran*
-
- <% form_for @person do |person_form| %>
- ...
- <% person_form.fields_for :projects do |project_fields| %>
- <% if project_fields.object.active? %>
- Name: <%= project_fields.text_field :name %>
- <% end %>
- <% end %>
- <% end %>
-
-
-* Added grouped_options_for_select helper method for wrapping option tags in optgroups. #977 *Jon Crawford*
-
-* Implement HTTP Digest authentication. #1230 *Gregg Kellogg, Pratik Naik* Example :
-
- class DummyDigestController < ActionController::Base
- USERS = { "lifo" => 'world' }
-
- before_filter :authenticate
-
- def index
- render :text => "Hello Secret"
- end
-
- private
-
- def authenticate
- authenticate_or_request_with_http_digest("Super Secret") do |username|
- # Return the user's password
- USERS[username]
- end
- end
- end
-
-* Improved i18n support for the number_to_human_size helper. Changes the storage_units translation data; update your translations accordingly. #1634 *Yaroslav Markin*
- storage_units:
- # %u is the storage unit, %n is the number (default: 2 MB)
- format: "%n %u"
- units:
- byte:
- one: "Byte"
- other: "Bytes"
- kb: "KB"
- mb: "MB"
- gb: "GB"
- tb: "TB"
-
-* Added :silence option to BenchmarkHelper#benchmark and turned log_level into a hash parameter and deprecated the old use *DHH*
-
-* Fixed the AssetTagHelper cache to use the computed asset host as part of the cache key instead of just assuming the its a string #1299 *DHH*
-
-* Make ActionController#render(string) work as a shortcut for render :file/:template/:action => string. #1435 *Pratik Naik* Examples:
-
- \# Instead of render(:action => 'other_action')
- render('other_action') # argument has no '/'
- render(:other_action)
-
- \# Instead of render(:template => 'controller/action')
- render('controller/action') # argument must not begin with a '/', but contain a '/'
-
- \# Instead of render(:file => '/Users/lifo/home.html.erb')
- render('/Users/lifo/home.html.erb') # argument must begin with a '/'
-
-* Add :prompt option to date/time select helpers. #561 *Sam Oliver*
-
-* Fixed that send_file shouldn't set an etag #1578 *Hongli Lai*
-
-* Allow users to opt out of the spoofing checks in Request#remote_ip. Useful for sites whose traffic regularly triggers false positives. *Darren Boyd*
-
-* Deprecated formatted_polymorphic_url. *Jeremy Kemper*
-
-* Added the option to declare an asset_host as an object that responds to call (see http://github.com/dhh/asset-hosting-with-minimum-ssl for an example) *David Heinemeier Hansson*
-
-* Added support for multiple routes.rb files (useful for plugin engines). This also means that draw will no longer clear the route set, you have to do that by hand (shouldn't make a difference to you unless you're doing some funky stuff) *David Heinemeier Hansson*
-
-* Dropped formatted_* routes in favor of just passing in :format as an option. This cuts resource routes generation in half #1359 *aaronbatalion*
-
-* Remove support for old double-encoded cookies from the cookie store. These values haven't been generated since before 2.1.0, and any users who have visited the app in the intervening 6 months will have had their cookie upgraded. *Michael Koziarski*
-
-* Allow helpers directory to be overridden via ActionController::Base.helpers_dir #1424 *Sam Pohlenz*
-
-* Remove deprecated ActionController::Base#assign_default_content_type_and_charset
-
-* Changed the default of ActionView#render to assume partials instead of files when not given an options hash *DHH*. Examples:
-
- # Instead of <%= render :partial => "account" %>
- <%= render "account" %>
-
- # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
- <%= render "account", :account => @buyer %>
-
- # @account is an Account instance, so it uses the RecordIdentifier to replace
- # <%= render :partial => "accounts/account", :locals => { :account => @account } %>
- <%= render(@account) %>
-
- # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
- # <%= render :partial => "posts/post", :collection => @posts %>
- <%= render(@posts) %>
-
-* Remove deprecated render_component. Please use the plugin from http://github.com/rails/render_component/tree/master *Pratik Naik*
-
-* Fixed RedCloth and BlueCloth shouldn't preload. Instead just assume that they're available if you want to use textilize and markdown and let autoload require them *David Heinemeier Hansson*
-
-
-## 2.2.2 (November 21st, 2008) ##
-
-* I18n: translate number_to_human_size. Add storage_units: [Bytes, KB, MB, GB, TB] to your translations. #1448 *Yaroslav Markin*
-
-* Restore backwards compatible functionality for setting relative_url_root. Include deprecation
-
-* Switched the CSRF module to use the request content type to decide if the request is forgeable. #1145 *Jeff Cohen*
-
-* Added :only and :except to map.resources to let people cut down on the number of redundant routes in an application. Typically only useful for huge routesets. #1215 *Tom Stuart*
-
- map.resources :products, :only => :show do |product|
- product.resources :images, :except => :destroy
- end
-
-* Added render :js for people who want to render inline JavaScript replies without using RJS *David Heinemeier Hansson*
-
-* Fixed that polymorphic_url should compact given array #1317 *hiroshi*
-
-* Fixed the sanitize helper to avoid double escaping already properly escaped entities #683 *antonmos/Ryan McGeary*
-
-* Fixed that FormTagHelper generated illegal html if name contained square brackets #1238 *Vladimir Dobriakov*
-
-* Fix regression bug that made date_select and datetime_select raise a Null Pointer Exception when a nil date/datetime was passed and only month and year were displayed #1289 *Bernardo Padua/Tor Erik*
-
-* Simplified the logging format for parameters (don't include controller, action, and format as duplicates) *David Heinemeier Hansson*
-
-* Remove the logging of the Session ID when the session store is CookieStore *David Heinemeier Hansson*
-
-* Fixed regex in redirect_to to fully support URI schemes #1247 *Seth Fitzsimmons*
-
-* Fixed bug with asset timestamping when using relative_url_root #1265 *Joe Goldwasser*
-
-
-## 2.2.0 RC1 (October 24th, 2008) ##
-
-* Fix incorrect closing CDATA delimiter and that HTML::Node.parse would blow up on unclosed CDATA sections *packagethief*
-
-* Added stale? and fresh_when methods to provide a layer of abstraction above request.fresh? and friends *DHH*. Example:
-
- class ArticlesController < ApplicationController
- def show_with_respond_to_block
- @article = Article.find(params[:id])
-
-
- # If the request sends headers that differs from the options provided to stale?, then
- # the request is indeed stale and the respond_to block is triggered (and the options
- # to the stale? call is set on the response).
- #
- # If the request headers match, then the request is fresh and the respond_to block is
- # not triggered. Instead the default render will occur, which will check the last-modified
- # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
- # of rendering the template.
- if stale?(:last_modified => @article.published_at.utc, :etag => @article)
- respond_to do |wants|
- # normal response processing
- end
- end
- end
-
- def show_with_implied_render
- @article = Article.find(params[:id])
-
- # Sets the response headers and checks them against the request, if the request is stale
- # (i.e. no match of either etag or last-modified), then the default render of the template happens.
- # If the request is fresh, then the default render will return a "304 Not Modified"
- # instead of rendering the template.
- fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
- end
- end
-
-
-* Added inline builder yield to atom_feed_helper tags where appropriate *Sam Ruby*. Example:
-
- entry.summary :type => 'xhtml' do |xhtml|
- xhtml.p pluralize(order.line_items.count, "line item")
- xhtml.p "Shipped to #{order.address}"
- xhtml.p "Paid by #{order.pay_type}"
- end
-
-* Make PrototypeHelper#submit_to_remote a wrapper around PrototypeHelper#button_to_remote. *Tarmo Tänav*
-
-* Set HttpOnly for the cookie session store's cookie. #1046
-
-* Added FormTagHelper#image_submit_tag confirm option #784 *Alastair Brunton*
-
-* Fixed FormTagHelper#submit_tag with :disable_with option wouldn't submit the button's value when was clicked #633 *Jose Fernandez*
-
-* Stopped logging template compiles as it only clogs up the log *David Heinemeier Hansson*
-
-* Changed the X-Runtime header to report in milliseconds *David Heinemeier Hansson*
-
-* Changed BenchmarkHelper#benchmark to report in milliseconds *David Heinemeier Hansson*
-
-* Changed logging format to be millisecond based and skip misleading stats *DHH*. Went from:
-
- Completed in 0.10000 (4 reqs/sec) | Rendering: 0.04000 (40%) | DB: 0.00400 (4%) | 200 OK [http://example.com]
-
- ...to:
-
- Completed in 100ms (View: 40, DB: 4) | 200 OK [http://example.com]
-
-* Add support for shallow nesting of routes. #838 *S. Brent Faulkner*
-
- Example :
-
- map.resources :users, :shallow => true do |user|
- user.resources :posts
- end
-
- - GET /users/1/posts (maps to PostsController#index action as usual)
- named route "user_posts" is added as usual.
-
- - GET /posts/2 (maps to PostsController#show action as if it were not nested)
- Additionally, named route "post" is added too.
-
-* Added button_to_remote helper. #3641 *Donald Piret, Tarmo Tänav*
-
-* Deprecate render_component. Please use render_component plugin from http://github.com/rails/render_component/tree/master *Pratik Naik*
-
-* Routes may be restricted to lists of HTTP methods instead of a single method or :any. #407 *Brennan Dunn, Gaius Centus Novus*
- map.resource :posts, :collection => { :search => [:get, :post] }
- map.session 'session', :requirements => { :method => [:get, :post, :delete] }
-
-* Deprecated implicit local assignments when rendering partials *Josh Peek*
-
-* Introduce current_cycle helper method to return the current value without bumping the cycle. #417 *Ken Collins*
-
-* Allow polymorphic_url helper to take url options. #880 *Tarmo Tänav*
-
-* Switched integration test runner to use Rack processor instead of CGI *Josh Peek*
-
-* Made AbstractRequest.if_modified_sense return nil if the header could not be parsed *Jamis Buck*
-
-* Added back ActionController::Base.allow_concurrency flag *Josh Peek*
-
-* AbstractRequest.relative_url_root is no longer automatically configured by a HTTP header. It can now be set in your configuration environment with config.action_controller.relative_url_root *Josh Peek*
-
-* Update Prototype to 1.6.0.2 #599 *Patrick Joyce*
-
-* Conditional GET utility methods. *Jeremy Kemper*
- response.last_modified = @post.updated_at
- response.etag = [:admin, @post, current_user]
-
- if request.fresh?(response)
- head :not_modified
- else
- # render ...
- end
-
-* All 2xx requests are considered successful *Josh Peek*
-
-* Fixed that AssetTagHelper#compute_public_path shouldn't cache the asset_host along with the source or per-request proc's won't run *David Heinemeier Hansson*
-
-* Removed config.action_view.cache_template_loading, use config.cache_classes instead *Josh Peek*
-
-* Get buffer for fragment cache from template's @output_buffer *Josh Peek*
-
-* Set config.action_view.warn_cache_misses = true to receive a warning if you perform an action that results in an expensive disk operation that could be cached *Josh Peek*
-
-* Refactor template preloading. New abstractions include Renderable mixins and a refactored Template class *Josh Peek*
-
-* Changed ActionView::TemplateHandler#render API method signature to render(template, local_assigns = {}) *Josh Peek*
-
-* Changed PrototypeHelper#submit_to_remote to PrototypeHelper#button_to_remote to stay consistent with link_to_remote (submit_to_remote still works as an alias) #8994 *clemens*
-
-* Add :recursive option to javascript_include_tag and stylesheet_link_tag to be used along with :all. #480 *Damian Janowski*
-
-* Allow users to disable the use of the Accept header *Michael Koziarski*
-
- The accept header is poorly implemented by browsers and causes strange
- errors when used on public sites where crawlers make requests too. You can use formatted urls (e.g. /people/1.xml) to support API clients in a much simpler way.
- To disable the header you need to set:
- config.action_controller.use_accept_header = false
-* Do not stat template files in production mode before rendering. You will no longer be able to modify templates in production mode without restarting the server *Josh Peek*
-
-* Deprecated TemplateHandler line offset *Josh Peek*
-
-* Allow caches_action to accept cache store options. #416. *José Valim*. Example:
-
- caches_action :index, :redirected, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour
-
-* Remove define_javascript_functions, javascript_include_tag and friends are far superior. *Michael Koziarski*
-
-* Deprecate :use_full_path render option. The supplying the option no longer has an effect *Josh Peek*
-
-* Add :as option to render a collection of partials with a custom local variable name. #509 *Simon Jefford, Pratik Naik*
-
- render :partial => 'other_people', :collection => @people, :as => :person
-
- This will let you access objects of @people as 'person' local variable inside 'other_people' partial template.
-
-* time_zone_select: support for regexp matching of priority zones. Resolves #195 *Ernie Miller*
-
-* Made ActionView::Base#render_file private *Josh Peek*
-
-* Refactor and simplify the implementation of assert_redirected_to. Arguments are now normalised relative to the controller being tested, not the root of the application. *Michael Koziarski*
-
- This could cause some erroneous test failures if you were redirecting between controllers
- in different namespaces and wrote your assertions relative to the root of the application.
-
-* Remove follow_redirect from controller functional tests.
-
- If you want to follow redirects you can use integration tests. The functional test version was only useful if you were using redirect_to :id=>...
-* Fix polymorphic_url with singleton resources. #461 *Tammer Saleh*
-
-* Replaced TemplateFinder abstraction with ViewLoadPaths *Josh Peek*
-
-* Added block-call style to link_to *Sam Stephenson/David Heinemeier Hansson*. Example:
-
- <% link_to(@profile) do %>
- <strong><%= @profile.name %></strong> -- <span>Check it out!!</span>
- <% end %>
-
-* Performance: integration test benchmarking and profiling. *Jeremy Kemper*
-
-* Make caching more aware of mime types. Ensure request format is not considered while expiring cache. *Jonathan del Strother*
-
-* Drop ActionController::Base.allow_concurrency flag *Josh Peek*
-
-* More efficient concat and capture helpers. Remove ActionView::Base.erb_variable. *Jeremy Kemper*
-
-* Added page.reload functionality. Resolves #277. *Sean Huber*
-
-* Fixed Request#remote_ip to only raise hell if the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR doesn't match (not just if they're both present) *Mark Imbriaco, Bradford Folkens*
-
-* Allow caches_action to accept a layout option *José Valim*
-
-* Added Rack processor *Ezra Zygmuntowicz, Josh Peek*
-
-
-## 2.1.0 (May 31st, 2008) ##
-
-* InstanceTag#default_time_from_options overflows to DateTime *Geoff Buesing*
-
-* Fixed that forgery protection can be used without session tracking (Peter Jones) *#139*
-
-* Added session(:on) to turn session management back on in a controller subclass if the superclass turned it off (Peter Jones) *#136*
-
-* Change the request forgery protection to go by Content-Type instead of request.format so that you can't bypass it by POSTing to "#{request.uri}.xml" *Rick Olson*
-* InstanceTag#default_time_from_options with hash args uses Time.current as default; respects hash settings when time falls in system local spring DST gap *Geoff Buesing*
-
-* select_date defaults to Time.zone.today when config.time_zone is set *Geoff Buesing*
-
-* Fixed that TextHelper#text_field would corrypt when raw HTML was used as the value (mchenryc, Kevin Glowacz) *#80*
-
-* Added ActionController::TestCase#rescue_action_in_public! to control whether the action under test should use the regular rescue_action path instead of simply raising the exception inline (great for error testing) *David Heinemeier Hansson*
-
-* Reduce number of instance variables being copied from controller to view. *Pratik Naik*
-
-* select_datetime and select_time default to Time.zone.now when config.time_zone is set *Geoff Buesing*
-
-* datetime_select defaults to Time.zone.now when config.time_zone is set *Geoff Buesing*
-
-* Remove ActionController::Base#view_controller_internals flag. *Pratik Naik*
-
-* Add conditional options to caches_page method. *Paul Horsfall*
-
-* Move missing template logic to ActionView. *Pratik Naik*
-
-* Introduce ActionView::InlineTemplate class. *Pratik Naik*
-
-* Automatically parse posted JSON content for Mime::JSON requests. *Rick Olson*
-
- POST /posts
- {"post": {"title": "Breaking News"}}
-
- def create
- @post = Post.create params[:post]
- # ...
- end
-
-* add json_escape ERB util to escape html entities in json strings that are output in HTML pages. *Rick Olson*
-
-* Provide a helper proxy to access helper methods from outside views. Closes #10839 *Josh Peek*
- e.g. ApplicationController.helpers.simple_format(text)
-
-* Improve documentation. *Xavier Noria, leethal, jerome*
-
-* Ensure RJS redirect_to doesn't html-escapes string argument. Closes #8546 *Josh Peek, eventualbuddha, Pratik Naik*
-
-* Support render :partial => collection of heterogeneous elements. #11491 *Zach Dennis*
-
-* Avoid remote_ip spoofing. *Brian Candler*
-
-* Added support for regexp flags like ignoring case in the :requirements part of routes declarations #11421 *NeilW*
-
-* Fixed that ActionController::Base#read_multipart would fail if boundary was exactly 10240 bytes #10886 *ariejan*
-
-* Fixed HTML::Tokenizer (used in sanitize helper) didn't handle unclosed CDATA tags #10071 *esad, packagethief*
-
-* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
-
-* Fixed that FormHelper#radio_button would produce invalid ids #11298 *harlancrystal*
-
-* Added :confirm option to submit_tag #11415 *Emilio Tagua*
-
-* Fixed NumberHelper#number_with_precision to properly round in a way that works equally on Mac, Windows, Linux (closes #11409, #8275, #10090, #8027) *zhangyuanyi*
-
-* Allow the #simple_format text_helper to take an html_options hash for each paragraph. #2448 *François Beausoleil, Chris O'Sullivan*
-
-* Fix regression from filter refactoring where re-adding a skipped filter resulted in it being called twice. *Rick Olson*
-
-* Refactor filters to use Active Support callbacks. #11235 *Josh Peek*
-
-* Fixed that polymorphic routes would modify the input array #11363 *thomas.lee*
-
-* Added :format option to NumberHelper#number_to_currency to enable better localization support #11149 *lylo*
-
-* Fixed that TextHelper#excerpt would include one character too many #11268 *Irfy*
-
-* Fix more obscure nested parameter hash parsing bug. #10797 *thomas.lee*
-
-* Added ActionView::Helpers::register_javascript/stylesheet_expansion to make it easier for plugin developers to inject multiple assets. #10350 *lotswholetime*
-
-* Fix nested parameter hash parsing bug. #10797 *thomas.lee*
-
-* Allow using named routes in ActionController::TestCase before any request has been made. Closes #11273 *Eloy Duran*
-
-* Fixed that sweepers defined by cache_sweeper will be added regardless of the perform_caching setting. Instead, control whether the sweeper should be run with the perform_caching setting. This makes testing easier when you want to turn perform_caching on/off *David Heinemeier Hansson*
-
-* Make MimeResponds::Responder#any work without explicit types. Closes #11140 *jaw6*
-
-* Better error message for type conflicts when parsing params. Closes #7962 *spicycode, matt*
-
-* Remove unused ActionController::Base.template_class. Closes #10787 *Pratik Naik*
-
-* Moved template handlers related code from ActionView::Base to ActionView::Template. *Pratik Naik*
-
-* Tests for div_for and content_tag_for helpers. Closes #11223 *Chris O'Sullivan*
-
-* Allow file uploads in Integration Tests. Closes #11091 *RubyRedRick*
-
-* Refactor partial rendering into a PartialTemplate class. *Pratik Naik*
-
-* Added that requests with JavaScript as the priority mime type in the accept header and no format extension in the parameters will be treated as though their format was :js when it comes to determining which template to render. This makes it possible for JS requests to automatically render action.js.rjs files without an explicit respond_to block *David Heinemeier Hansson*
-
-* Tests for distance_of_time_in_words with TimeWithZone instances. Closes #10914 *Ernesto Jimenez*
-
-* Remove support for multivalued (e.g., '&'-delimited) cookies. *Jamis Buck*
-
-* Fix problem with render :partial collections, records, and locals. #11057 *lotswholetime*
-
-* Added support for naming concrete classes in sweeper declarations *David Heinemeier Hansson*
-
-* Remove ERB trim variables from trace template in case ActionView::Base.erb_trim_mode is changed in the application. #10098 *Tim Pope, Chris Kampmeier*
-
-* Fix typo in form_helper documentation. #10650 *Xavier Shay, Chris Kampmeier*
-
-* Fix bug with setting Request#format= after the getter has cached the value. #10889 *cch1*
-
-* Correct inconsistencies in RequestForgeryProtection docs. #11032 *Mislav Marohnić*
-
-* Introduce a Template class to ActionView. #11024 *Pratik Naik*
-
-* Introduce the :index option for form_for and fields_for to simplify multi-model forms (see http://railscasts.com/episodes/75). #9883 *rmm5t*
-
-* Introduce map.resources :cards, :as => 'tarjetas' to use a custom resource name in the URL: cards_path == '/tarjetas'. #10578 *blj*
-
-* TestSession supports indifferent access. #7372 *tamc, Arsen7, mhackett, julik, jean.helou*
-
-* Make assert_routing aware of the HTTP method used. #8039 *mpalmer*
- e.g. assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
-
-* Make map.root accept a single symbol as an argument to declare an alias. #10818 *bscofield*
-
- e.g. map.dashboard '/dashboard', :controller=>'dashboard'
- map.root :dashboard
-
-* Handle corner case with image_tag when passed 'messed up' image names. #9018 *Duncan Beevers, mpalmer*
-
-* Add label_tag helper for generating elements. #10802 *DefV*
-
-* Introduce TemplateFinder to handle view paths and lookups. #10800 *Pratik Naik*
-
-* Performance: optimize route recognition. Large speedup for apps with many resource routes. #10835 *oleganza*
-
-* Make render :partial recognise form builders and use the _form partial. #10814 *Damian Janowski*
-
-* Allow users to declare other namespaces when using the atom feed helpers. #10304 *david.calavera*
-
-* Introduce send_file :x_sendfile => true to send an X-Sendfile response header. *Jeremy Kemper*
-
-* Fixed ActionView::Helpers::ActiveRecordHelper::form for when protect_from_forgery is used #10739 *Jeremy Evans*
-
-* Provide nicer access to HTTP Headers. Instead of request.env["HTTP_REFERRER"] you can now use request.headers["Referrer"]. *Michael Koziarski*
-
-* UrlWriter respects relative_url_root. #10748 *Cheah Chu Yeow*
-
-* The asset_host block takes the controller request as an optional second argument. Example: use a single asset host for SSL requests. #10549 *Cheah Chu Yeow, Peter B, Tom Taylor*
-
-* Support render :text => nil. #6684 *tjennings, PotatoSalad, Cheah Chu Yeow*
-
-* assert_response failures include the exception message. #10688 *Seth Rasmussen*
-
-* All fragment cache keys are now by default prefixed with the "views/" namespace *David Heinemeier Hansson*
-
-* Moved the caching stores from ActionController::Caching::Fragments::* to ActiveSupport::Cache::*. If you're explicitly referring to a store, like ActionController::Caching::Fragments::MemoryStore, you need to update that reference with ActiveSupport::Cache::MemoryStore *David Heinemeier Hansson*
-
-* Deprecated ActionController::Base.fragment_cache_store for ActionController::Base.cache_store *David Heinemeier Hansson*
-
-* Made fragment caching in views work for rjs and builder as well #6642 *Dee Zsombor*
-
-* Fixed rendering of partials with layout when done from site layout #9209 *antramm*
-
-* Fix atom_feed_helper to comply with the atom spec. Closes #10672 *Xavier Shay*
-
- * The tags created do not contain a date (http://feedvalidator.org/docs/error/InvalidTAG.html)
- * IDs are not guaranteed unique
- * A default self link was not provided, contrary to the documentation
- * NOTE: This changes tags for existing atom entries, but at least they validate now.
-
-* Correct indentation in tests. Closes #10671 *Luca Guidi*
-
-* Fix that auto_link looks for ='s in url paths (Amazon urls have them). Closes #10640 *Brad Greenlee*
-
-* Ensure that test case setup is run even if overridden. #10382 *Josh Peek*
-
-* Fix HTML Sanitizer to allow trailing spaces in CSS style attributes. Closes #10566 *wesley.moxam*
-
-* Add :default option to time_zone_select. #10590 *Matt Aimonetti*
-
-
-## 2.0.2 (December 16th, 2007) ##
-
-* Added delete_via_redirect and put_via_redirect to integration testing #10497 *philodespotos*
-
-* Allow headers['Accept'] to be set by hand when calling xml_http_request #10461 *BMorearty*
-
-* Added OPTIONS to list of default accepted HTTP methods #10449 *holoway*
-
-* Added option to pass proc to ActionController::Base.asset_host for maximum configurability #10521 *Cheah Chu Yeow*. Example:
-
- ActionController::Base.asset_host = Proc.new { |source|
- if source.starts_with?('/images')
- "http://images.example.com"
- else
- "http://assets.example.com"
- end
- }
-
-* Fixed that ActionView#file_exists? would be incorrect if @first_render is set #10569 *dbussink*
-
-* Added that Array#to_param calls to_param on all it's elements #10473 *brandon*
-
-* Ensure asset cache directories are automatically created. #10337 *Josh Peek, Cheah Chu Yeow*
-
-* render :xml and :json preserve custom content types. #10388 *jmettraux, Cheah Chu Yeow*
-
-* Refactor Action View template handlers. #10437, #10455 *Josh Peek*
-
-* Fix DoubleRenderError message and leave out mention of returning false from filters. Closes #10380 *Frederick Cheung*
-
-* Clean up some cruft around ActionController::Base#head. Closes #10417 *ssoroka*
-
-
-## 2.0.1 (December 7th, 2007) ##
-
-* Fixed send_file/binary_content for testing #8044 *tolsen*
-
-* When a NonInferrableControllerError is raised, make the proposed fix clearer in the error message. Closes #10199 *Jack Danger Canty*
-
-* Update Prototype to 1.6.0.1. *sam*
-
-* Update script.aculo.us to 1.8.0.1. *madrobby*
-
-* Add 'disabled' attribute to <OPTION> separators used in time zone and country selects. Closes #10354 *Josh Susser*
-
-* Added the same record identification guessing rules to fields_for as form_for has *David Heinemeier Hansson*
-
-* Fixed that verification violations with no specified action didn't halt the chain (now they do with a 400 Bad Request) *David Heinemeier Hansson*
-
-* Raise UnknownHttpMethod exception for unknown HTTP methods. Closes #10303 *Tarmo Tänav*
-
-* Update to Prototype -r8232. *sam*
-
-* Make sure the optimisation code for routes doesn't get used if :host, :anchor or :port are provided in the hash arguments. *pager, Michael Koziarski* #10292
-
-* Added protection from trailing slashes on page caching #10229 *devrieda*
-
-* Asset timestamps are appended, not prepended. Closes #10276 *Mike Naberezny*
-
-* Minor inconsistency in description of render example. Closes #10029 *ScottSchram*
-
-* Add #prepend_view_path and #append_view_path instance methods on ActionController::Base for consistency with the class methods. *Rick Olson*
-
-* Refactor sanitizer helpers into HTML classes and make it easy to swap them out with custom implementations. Closes #10129. *Rick Olson*
-
-* Add deprecation for old subtemplate syntax for ActionMailer templates, use render :partial *Rick Olson*
-
-* Fix TemplateError so it doesn't bomb on exceptions while running tests *Rick Olson*
-
-* Fixed that named routes living under resources shouldn't have double slashes #10198 *Isaac Feliu*
-
-* Make sure that cookie sessions use a secret that is at least 30 chars in length. *Michael Koziarski*
-
-* Fixed that partial rendering should look at the type of the first render to determine its own type if no other clues are available (like when using text.plain.erb as the extension in AM) #10130 *java*
-
-* Fixed that has_many :through associations should render as collections too #9051 *mathie/Jack Danger Canty*
-
-* Added :mouseover short-cut to AssetTagHelper#image_tag for doing easy image swaps #6893 *joost*
-
-* Fixed handling of non-domain hosts #9479 *purp*
-
-* Fix syntax error in documentation example for cycle method. Closes #8735 *foca*
-
-* Document :with option for link_to_remote. Closes #8765 *Ryan Bates*
-
-* Document :minute_step option for time_select. Closes #8814 *brupm*
-
-* Explain how to use the :href option for link_to_remote to degrade gracefully in the absence of JavaScript. Closes #8911 *vlad*
-
-* Disambiguate :size option for text area tag. Closes #8955 *redbeard*
-
-* Fix broken tag in assert_tag documentation. Closes #9037 *mfazekas*
-
-* Add documentation for route conditions. Closes #9041 *innu, Manfred Stienstra*
-
-* Fix typo left over from previous typo fix in url helper. Closes #9414 *Henrik N*
-
-* Fixed that ActionController::CgiRequest#host_with_port() should handle standard port #10082 *moro*
-
-* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. *sam, madrobby*
-
-* Expose the cookie jar as a helper method (before the view would just get the raw cookie hash) *David Heinemeier Hansson*
-
-* Integration tests: get_ and post_via_redirect take a headers hash. #9130 *simonjefford*
-
-* Simplfy #view_paths implementation. ActionView templates get the exact object, not a dup. *Rick Olson*
-
-* Update tests for ActiveSupport's JSON escaping change. *Rick Olson*
-
-* FormHelper's auto_index should use #to_param instead of #id_before_type_cast. Closes #9994 *mattly*
-
-* Doc typo fixes for ActiveRecordHelper. Closes #9973 *mikong*
-
-* Make example parameters in restful routing docs idiomatic. Closes #9993 *Jack Danger Canty*
-
-* Make documentation comment for mime responders match documentation example. Closes #9357 *yon*
-
-* Introduce a new test case class for functional tests. ActionController::TestCase. *Michael Koziarski*
-
-* Fix incorrect path in helper rdoc. Closes #9926 *viktor tron*
-
-* Partials also set 'object' to the default partial variable. #8823 *Nick Retallack, Jeremy Kemper*
-
-* Request profiler. *Jeremy Kemper*
- $ cat login_session.rb
- get_with_redirect '/'
- say "GET / => #{path}"
- post_with_redirect '/sessions', :username => 'john', :password => 'doe'
- say "POST /sessions => #{path}"
- $ ./script/performance/request -n 10 login_session.rb
-
-* Disabled checkboxes don't submit a form value. #9301 *vladr, robinjfisher*
-
-* Added tests for options to ActiveRecordHelper#form. Closes #7213 *richcollins, mikong, Mislav Marohnić*
-
-* Changed before_filter halting to happen automatically on render or redirect but no longer on simply returning false *David Heinemeier Hansson*
-
-* Ensure that cookies handle array values correctly. Closes #9937 *queso*
-
-* Make sure resource routes don't clash with internal helpers like javascript_path, image_path etc. #9928 *Geoff Buesing*
-
-* caches_page uses a single after_filter instead of one per action. #9891 *Pratik Naik*
-
-* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. *sam, madrobby*
-
-* Dispatcher: fix that to_prepare should only run once in production. #9889 *Nathaniel Talbott*
-
-* Memcached sessions: add session data on initialization; don't silently discard exceptions; add unit tests. #9823 *kamk*
-
-* error_messages_for also takes :message and :header_message options which defaults to the old "There were problems with the following fields:" and "<count> errors prohibited this <object_name> from being saved". #8270 *rmm5t, zach-inglis-lt3*
-
-* Make sure that custom inflections are picked up by map.resources. #9815 *Mislav Marohnić*
-
-* Changed SanitizeHelper#sanitize to only allow the custom attributes and tags when specified in the call *David Heinemeier Hansson*
-
-* Extracted sanitization methods from TextHelper to SanitizeHelper *David Heinemeier Hansson*
-
-* rescue_from accepts :with => lambda { |exception| ... } or a normal block. #9827 *Pratik Naik*
-
-* Add :status to redirect_to allowing users to choose their own response code without manually setting headers. #8297 *Coda Hale, chasgrundy*
-
-* Add link_to :back which uses your referrer with a fallback to a javascript link. #7366 *eventualbuddha, Tarmo Tänav*
-
-* error_messages_for and friends also work with local variables. #9699 *Frederick Cheung*
-
-* Fix url_for, redirect_to, etc. with :controller => :symbol instead of 'string'. #8562, #9525 *Justin Lynn, Tarmo Tänav, shoe*
-
-* Use #require_library_or_gem to load the memcache library for the MemCache session and fragment cache stores. Closes #8662. *Rick Olson*
-
-* Move ActionController::Routing.optimise_named_routes to ActionController::Base.optimise_named_routes. Now you can set it in the config. *Rick Olson*
-
- config.action_controller.optimise_named_routes = false
-
-* ActionController::Routing::DynamicSegment#interpolation_chunk should call #to_s on all values before calling URI.escape. *Rick Olson*
-
-* Only accept session ids from cookies, prevents session fixation attacks. *bradediger*
-
-
-## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.12.2 - 1.13.3 ##
-
-* Fixed that render template did not honor exempt_from_layout #9698 *pezra*
-
-* Better error messages if you leave out the :secret option for request forgery protection. Closes #9670 *Rick Olson*
-
-* Allow ability to disable request forgery protection, disable it in test mode by default. Closes #9693 *Pratik Naik*
-
-* Avoid calling is_missing on LoadErrors. Closes #7460. *ntalbott*
-
-* Move Railties' Dispatcher to ActionController::Dispatcher, introduce before_ and after_dispatch callbacks, and warm up to non-CGI requests. *Jeremy Kemper*
-
-* The tag helper may bypass escaping. *Jeremy Kemper*
-
-* Cache asset ids. *Jeremy Kemper*
-
-* Optimized named routes respect AbstractRequest.relative_url_root. #9612 *Daniel Morrison, Jeremy Kemper*
-
-* Introduce ActionController::Base.rescue_from to declare exception-handling methods. Cleaner style than the case-heavy rescue_action_in_public. #9449 *Norbert Crombach*
-
-* Rename some RequestForgeryProtection methods. The class method is now #protect_from_forgery, and the default parameter is now 'authenticity_token'. *Rick Olson*
-
-* Merge csrf_killer plugin into rails. Adds RequestForgeryProtection model that verifies session-specific _tokens for non-GET requests. *Rick Olson*
-
-* Secure #sanitize, #strip_tags, and #strip_links helpers against xss attacks. Closes #8877. *Rick Olson, Pratik Naik, Jacques Distler*
-
- This merges and renames the popular white_list helper (along with some css sanitizing from Jacques Distler version of the same plugin).
- Also applied updated versions of #strip_tags and #strip_links from #8877.
-
-* Remove use of & logic operator. Closes #8114. *watson*
-
-* Fixed JavaScriptHelper#escape_javascript to also escape closing tags #8023 *Ruy Asan*
-
-* Fixed TextHelper#word_wrap for multiline strings with extra carrier returns #8663 *seth*
-
-* Fixed that setting the :host option in url_for would automatically turn off :only_path (since :host would otherwise not be shown) #9586 *Bounga*
-
-* Added FormHelper#label. #8641, #9850 *jcoglan, Jarkko Laine*
-
-* Added AtomFeedHelper (slightly improved from the atom_feed_helper plugin) *David Heinemeier Hansson*
-
-* Prevent errors when generating routes for uncountable resources, (i.e. sheep where plural == singluar). map.resources :sheep now creates sheep_index_url for the collection and sheep_url for the specific item. *Michael Koziarski*
-
-* Added support for HTTP Only cookies (works in IE6+ and FF 2.0.5+) as an improvement for XSS attacks #8895 *Pratik Naik, Mark Somerville*
-
-* Don't warn when a path segment precedes a required segment. Closes #9615. *Nicholas Seckar*
-
-* Fixed CaptureHelper#content_for to work with the optional content parameter instead of just the block #9434 *sandofsky/wildchild*.
-
-* Added Mime::Type.register_alias for dealing with different formats using the same mime type *DHH*. Example:
-
- class PostsController < ApplicationController
- before_filter :adjust_format_for_iphone
-
- def index
- @posts = Post.find(:all)
-
- respond_to do |format|
- format.html # => renders index.html.erb and uses "text/html" as the content type
- format.iphone # => renders index.iphone.erb and uses "text/html" as the content type
- end
- end
-
-
- private
- def adjust_format_for_iphone
- if request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/iPhone/]
- request.format = :iphone
- end
- end
- end
-
-* Added that render :json will automatically call .to_json unless it's being passed a string *DHH*.
-
-* Autolink behaves well with emails embedded in URLs. #7313 *Jeremy McAnally, Tarmo Tänav*
-
-* Fixed that default layouts did not take the format into account #9564 *Pratik Naik*
-
-* Fixed optimized route segment escaping. #9562 *wildchild, Jeremy Kemper*
-
-* Added block acceptance to JavaScriptHelper#javascript_tag. #7527 *Bob Silva, Tarmo Tänav, rmm5t*
-
-* root_path returns '/' not ''. #9563 *Pratik Naik*
-
-* Fixed that setting request.format should also affect respond_to blocks *David Heinemeier Hansson*
-
-* Add option to force binary mode on tempfile used for fixture_file_upload. #6380 *Jonathan Viney*
-
-* Fixed that resource namespaces wouldn't stick to all nested resources #9399 *pixeltrix*
-
-* Moved ActionController::Macros::AutoComplete into the auto_complete plugin on the official Rails svn. #9512 *Pratik Naik*
-
-* Moved ActionController::Macros::InPlaceEditing into the in_place_editor plugin on the official Rails svn. #9513 *Pratik Naik*
-
-* Removed deprecated form of calling xml_http_request/xhr without the first argument being the http verb *David Heinemeier Hansson*
-
-* Removed deprecated methods *DHH*:
-
- - ActionController::Base#keep_flash (use flash.keep instead)
- - ActionController::Base#expire_matched_fragments (just call expire_fragment with a regular expression)
- - ActionController::Base.template_root/= methods (use ActionController#Base.view_paths/= instead)
- - ActionController::Base.cookie (use ActionController#Base.cookies[]= instead)
-
-* Removed the deprecated behavior of appending ".png" to image_tag/image_path calls without an existing extension *David Heinemeier Hansson*
-
-* Removed ActionController::Base.scaffold -- it went through the whole idea of scaffolding (card board walls you remove and tweak one by one). Use the scaffold generator instead (it does resources too now!) *David Heinemeier Hansson*
-
-* Optimise named route generation when using positional arguments. *Michael Koziarski*
-
- This change delivers significant performance benefits for the most
- common usage scenarios for modern rails applications by avoiding the
- costly trip through url_for. Initial benchmarks indicate this is
- between 6 and 20 times as fast.
-
-* Explicitly require active_record/query_cache before using it. *Jeremy Kemper*
-
-* Fix layout overriding response status. #9476 *lotswholetime*
-
-* Add field_set_tag for generating field_sets, closes #9477. *Damian Janowski*
-
-* Allow additional parameters to be passed to named route helpers when using positional arguments. Closes #8930 *Ian White*
-
-* Make render :partial work with a :collection of Hashes, previously this wasn't possible due to backwards compatibility restrictions. *Pratik Naik*
-
-* request.host works with IPv6 addresses. #9458 *yuya*
-
-* Fix bug where action caching sets the content type to the ActionCachePath object. Closes #9282 *mindforge*
-
-* Find layouts even if they're not in the first view_paths directory. Closes #9258 *caio*
-
-* Major improvement to the documentation for the options / select form helpers. Closes #9038 *Chris Kampmeier, jardeon, wesg*
-
-* Fix number_to_human_size when using different precisions. Closes #7536. *RichardStrand, mpalmer*
-
-* Added partial layouts (see example in action_view/lib/partials.rb) *David Heinemeier Hansson*
-
-* Allow you to set custom :conditions on resource routes. *Rick Olson*
-
-* Fixed that file.content_type for uploaded files would include a trailing \r #9053 *Brad Greenlee*
-
-* url_for now accepts a series of symbols representing the namespace of the record *Josh Knowles*
-
-* Make :trailing_slash work with query parameters for url_for. Closes #4004 *nov*
-
-* Make sure missing template exceptions actually say which template they were looking for. Closes #8683 *dasil003*
-
-* Fix errors with around_filters which do not yield, restore 1.1 behaviour with after filters. Closes #8891 *Stefan Kaes*
-
- After filters will *no longer* be run if an around_filter fails to yield, users relying on
- this behaviour are advised to put the code in question after a yield statement in an around filter.
-
-
-* Allow you to delete cookies with options. Closes #3685 *Josh Peek, Chris Wanstrath*
-
-* Allow you to render views with periods in the name. Closes #8076 *Norbert Crombach*
-
- render :partial => 'show.html.erb'
-
-* Improve capture helper documentation. #8796 *Chris Kampmeier*
-
-* Prefix nested resource named routes with their action name, e.g. new_group_user_path(@group) instead of group_new_user_path(@group). The old nested action named route is deprecated in Rails 1.2.4. #8558 *David Chelimsky*
-
-* Allow sweepers to be created solely for expiring after controller actions, not model changes *David Heinemeier Hansson*
-
-* Added assigns method to ActionController::Caching::Sweeper to easily access instance variables on the controller *David Heinemeier Hansson*
-
-* Give the legacy X-POST_DATA_FORMAT header greater precedence during params parsing for backward compatibility. *Jeremy Kemper*
-
-* Fixed that link_to with an href of # when using :method will not allow for click-through without JavaScript #7037 *Steven Bristol, Josh Peek*
-
-* Fixed that radio_button_tag should generate unique ids #3353 *Bob Silva, Rebecca, Josh Peek*
-
-* Fixed that HTTP authentication should work if the header is called REDIRECT_X_HTTP_AUTHORIZATION as well #6754 *Mislav Marohnić*
-
-* Don't mistakenly interpret the request uri as the query string. #8731 *Pratik Naik, Jeremy Kemper*
-
-* Make ActionView#view_paths an attr_accessor for real this time. Also, don't perform an unnecessary #compact on the @view_paths array in #initialize. Closes #8582 *dasil003, julik, Rick Olson*
-
-* Tolerate missing content type on multipart file uploads. Fix for Safari 3. *Jeremy Kemper*
-
-* Deprecation: remove pagination. Install the classic_pagination plugin for forward compatibility, or move to the superior will_paginate plugin. #8157 *Josh Peek*
-
-* Action caching is limited to GET requests returning 200 OK status. #3335 *tom@craz8.com, halfbyte, Dan Kubb, Josh Peek*
-
-* Improve Text Helper test coverage. #7274 *Rob Sanheim, Josh Peek*
-
-* Improve helper test coverage. #7208, #7212, #7215, #7233, #7234, #7235, #7236, #7237, #7238, #7241, #7243, #7244 *Rich Collins, Josh Peek*
-
-* Improve UrlRewriter tests. #7207 *Rich Collins*
-
-* Resources: url_for([parent, child]) generates /parents/1/children/2 for the nested resource. Likewise with the other simply helpful methods like form_for and link_to. #6432 *mhw, Jonathan Vaught, lotswholetime*
-
-* Assume html format when rendering partials in RJS. #8076 *Rick Olson*
-
-* Don't double-escape url_for in views. #8144 *Rich Collins, Josh Peek*
-
-* Allow JSON-style values for the :with option of observe_field. Closes #8557 *kommen*
-
-* Remove RAILS_ROOT from backtrace paths. #8540 *Tim Pope*
-
-* Routing: map.resource :logo routes to LogosController so the controller may be reused for multiple nestings or namespaces. *Jeremy Kemper*
-
-* render :partial recognizes Active Record associations as Arrays. #8538 *Kamal Fariz Mahyuddin*
-
-* Routing: drop semicolon and comma as route separators. *Jeremy Kemper*
-
-* request.remote_ip understands X-Forwarded-For addresses with nonstandard whitespace. #7386 *moses*
-
-* Don't prepare response when rendering a component. #8493 *jsierles*
-
-* Reduce file stat calls when checking for template changes. #7736 *alex*
-
-* Added custom path cache_page/expire_page parameters in addition to the options hashes *DHH*. Example:
-
- def index
- caches_page(response.body, "/index.html")
- end
-
-* Action Caching speedup. #8231 *Stefan Kaes*
-
-* Wordsmith resources documentation. #8484 *marclove*
-
-* Fix syntax error in code example for routing documentation. #8377. *Norbert Crombach*
-
-* Routing: respond with 405 Method Not Allowed status when the route path matches but the HTTP method does not. #6953 *Josh Peek, defeated, Dan Kubb, Coda Hale*
-
-* Add support for assert_select_rjs with :show and :hide. #7780 *dchelimsky*
-
-* Make assert_select's failure messages clearer about what failed. #7779 *dchelimsky*
-
-* Introduce a default respond_to block for custom types. #8174 *Josh Peek*
-
-* auto_complete_field takes a :method option so you can GET or POST. #8120 *zapnap*
-
-* Added option to suppress :size when using :maxlength for FormTagHelper#text_field #3112 *Tim Pope*
-
-* catch possible WSOD when trying to render a missing partial. Closes #8454 *Jonathan del Strother*
-
-* Rewind request body after reading it, if possible. #8438 *s450r1*
-
-* Resource namespaces are inherited by their has_many subresources. #8280 *marclove, Geoff Garside*
-
-* Fix filtered parameter logging with nil parameter values. #8422 *choonkeat*
-
-* Integration tests: alias xhr to xml_http_request and add a request_method argument instead of always using POST. #7124 *Nik Wakelin, François Beausoleil, Wizard*
-
-* Document caches_action. #5419 *Jarkko Laine*
-
-* Update to Prototype 1.5.1. *Sam Stephenson*
-
-* Allow routes to be decalred under namespaces *Tobias Lütke*:
-
- map.namespace :admin do |admin|
- admin.root :controller => "products"
- admin.feed 'feed.xml', :controller => 'products', :action => 'feed', :format => 'xml'
- end
-
-* Update to script.aculo.us 1.7.1_beta3. *Thomas Fuchs*
-
-* observe_form always sends the serialized form. #5271 *Manfred Stienstra, normelton@gmail.com*
-
-* Parse url-encoded and multipart requests ourselves instead of delegating to CGI. *Jeremy Kemper*
-
-* select :include_blank option can be set to a string instead of true, which just uses an empty string. #7664 *Wizard*
-
-* Added url_for usage on render :location, which allows for record identification *DHH*. Example:
-
- render :xml => person, :status => :created, :location => person
-
- ...expands the location to person_url(person).
-
-* Introduce the request.body stream. Lazy-read to parse parameters rather than always setting RAW_POST_DATA. Reduces the memory footprint of large binary PUT requests. *Jeremy Kemper*
-
-* Add some performance enhancements to ActionView.
-
- * Cache base_paths in @@cached_base_paths
- * Cache template extensions in @@cached_template_extension
- * Remove unnecessary rescues
-
-* Assume that rendered partials go by the HTML format by default
-
- def my_partial
- render :update do |page|
- # in this order
- # _foo.html.erb
- # _foo.erb
- # _foo.rhtml
- page.replace :foo, :partial => 'foo'
- end
- end
-
-* Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for *DHH*. Examples:
-
- <% form_for(@post) do |f| %>
- ...
- <% end %>
-
- This will expand to be the same as:
-
- <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
- ...
- <% end %>
-
- And for new records:
-
- <% form_for(Post.new) do |f| %>
- ...
- <% end %>
-
- This will expand to be the same as:
-
- <% form_for :post, @post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
- ...
- <% end %>
-
-* Rationalize route path escaping according to RFC 2396 section 3.3. #7544, #8307. *Jeremy Kemper, Chris Roos, begemot, jugend*
-
-* Added record identification with polymorphic routes for ActionController::Base#url_for and ActionView::Base#url_for *DHH*. Examples:
-
- redirect_to(post) # => redirect_to(posts_url(post)) => Location: http://example.com/posts/1
- link_to(post.title, post) # => link_to(post.title, posts_url(post)) => <a href="/posts/1">Hello world</a>
-
- Any method that calls url_for on its parameters will automatically benefit from this.
-
-* Removed deprecated parameters_for_method_reference concept (legacy from before named routes) *David Heinemeier Hansson*
-
-* Add ActionController::Routing::Helpers, a module to contain common URL helpers such as polymorphic_url. *Nicholas Seckar*
-
-* Included the HttpAuthentication plugin as part of core (ActionController::HttpAuthentication::Basic) *David Heinemeier Hansson*
-
-* Modernize documentation for form helpers. *Jeremy McAnally*
-
-* Add brief introduction to REST to the resources documentation. *fearoffish*
-
-* Fix various documentation typos throughout ActionPack. *Henrik N*
-
-* Enhance documentation and add examples for url_for. *Jeremy McAnally*
-
-* Fix documentation typo in routes. *Norbert Crombach, pam*
-
-* Sweep flash when filter chain is halted. *Caio Chassot <lists@v2studio.com>*
-
-* Fixed that content_tag with a block will just return the result instead of concate it if not used in a ERb view #7857, #7432 *michael.niessner*
-
-* Replace the current block/continuation filter chain handling by an implementation based on a simple loop. #8226 *Stefan Kaes*
-
-* Update UrlWriter to accept :anchor parameter. Closes #6771. *Chris McGrath*
-
-* Added RecordTagHelper for using RecordIdentifier conventions on divs and other container elements *DHH*. Example:
-
- <% div_for(post) do %> <div id="post_45" class="post">
- <%= post.body %> What a wonderful world!
- <% end %> </div>
-
-* Added page[record] accessor to JavaScriptGenerator that relies on RecordIdentifier to find the right dom id *DHH*. Example:
-
- format.js do
- # Calls: new Effect.fade('post_45');
- render(:update) { |page| page[post].visual_effect(:fade) }
- end
-
-* Added RecordIdentifier to enforce view conventions on records for dom ids, classes, and partial paths *David Heinemeier Hansson*
-
-* Added map.namespace to deal with the common situation of admin sections and the like *David Heinemeier Hansson*
-
- Before:
-
- map.resources :products, :path_prefix => "admin", :controller => "admin/products", :collection => { :inventory => :get }, :member => { :duplicate => :post }
- map.resources :tags, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_tags"
- map.resources :images, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_images"
- map.resources :variants, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_variants"
-
- After:
-
- map.namespace(:admin) do |admin|
- admin.resources :products,
- :collection => { :inventory => :get },
- :member => { :duplicate => :post },
- :has_many => [ :tags, :images, :variants ]
- end
-
-* Added :name_prefix as standard for nested resources *DHH*. WARNING: May be backwards incompatible with your app
-
- Before:
-
- map.resources :emails do |emails|
- emails.resources :comments, :name_prefix => "email_"
- emails.resources :attachments, :name_prefix => "email_"
- end
-
- After:
-
- map.resources :emails do |emails|
- emails.resources :comments
- emails.resources :attachments
- end
-
- This does mean that if you intended to have comments_url go to /emails/5/comments, then you'll have to set :name_prefix to nil explicitly.
-
-* Added :has_many and :has_one for declaring plural and singular resources beneath the current *David Heinemeier Hansson*
-
- Before:
-
- map.resources :notes do |notes|
- notes.resources :comments
- notes.resources :attachments
- notes.resource :author
- end
-
- After:
-
- map.resources :notes, :has_many => [ :comments, :attachments ], :has_one => :author
-
-* Added that render :xml will try to call to_xml if it can *DHH*. Makes these work:
-
- render :xml => post
- render :xml => comments
-
-* Added :location option to render so that the common pattern of rendering a response after creating a new resource is now a 1-liner *David Heinemeier Hansson*
-
- render :xml => post.to_xml, :status => :created, :location => post_url(post)
-
-* Ensure that render_text only adds string content to the body of the response *David Heinemeier Hansson*
-
-* Return the string representation from an Xml Builder when rendering a partial. Closes #5044 *Tim Pope*
-
-* Fixed that parameters from XML should also be presented in a hash with indifferent access *David Heinemeier Hansson*
-
-* Tweak template format rules so that the ACCEPT header is only used if it's text/javascript. This is so ajax actions without a :format param get recognized as Mime::JS. *Rick Olson*
-
-* The default respond_to blocks don't set a specific extension anymore, so that both 'show.rjs' and 'show.js.rjs' will work. *Rick Olson*
-
-* Allow layouts with extension of .html.erb. Closes #8032 *Josh Knowles*
-
-* Change default respond_to templates for xml and rjs formats. *Rick Olson*
-
- * Default xml template goes from #{action_name}.rxml => #{action_name}.xml.builder.
- * Default rjs template goes from #{action_name}.rjs => #{action_name}.js.rjs.
-
- You can still specify your old templates:
-
- respond_to do |format|
- format.xml do
- render :action => "#{action_name}.rxml"
- end
- end
-
-* Fix WSOD due to modification of a formatted template extension so that requests to templates like 'foo.html.erb' fail on the second hit. *Rick Olson*
-
-* Fix WSOD when template compilation fails *Rick Olson*
-
-* Change ActionView template defaults. Look for templates using the request format first, such as "show.html.erb" or "show.xml.builder", before looking for the old defaults like "show.erb" or "show.builder" *Rick Olson*
-
-* Highlight helper highlights one or many terms in a single pass. *Jeremy Kemper*
-
-* Dropped the use of ; as a separator of non-crud actions on resources and went back to the vanilla slash. It was a neat idea, but lots of the non-crud actions turned out not to be RPC (as the ; was primarily intended to discourage), but legitimate sub-resources, like /parties/recent, which didn't deserve the uglification of /parties;recent. Further more, the semicolon caused issues with caching and HTTP authentication in Safari. Just Not Worth It *David Heinemeier Hansson*
-
-* Added that FormTagHelper#submit_tag will return to its original state if the submit fails and you're using :disable_with *David Heinemeier Hansson*
-
-* Cleaned up, corrected, and mildly expanded ActionPack documentation. Closes #7190 *Jeremy McAnally*
-
-* Small collection of ActionController documentation cleanups. Closes #7319 *Jeremy McAnally*
-
-* Make sure the route expiry hash is constructed by comparing the to_param-ized values of each hash. *Jamis Buck*
-
-* Allow configuration of the default action cache path for #caches_action calls. *Rick Olson*
-
- class ListsController < ApplicationController
- caches_action :index, :cache_path => Proc.new { |controller|
- controller.params[:user_id] ?
- controller.send(:user_lists_url, c.params[:user_id]) :
- controller.send(:lists_url) }
- end
-
-* Performance: patch cgi/session/pstore to require digest/md5 once rather than per #initialize. #7583 *Stefan Kaes*
-
-* Cookie session store: ensure that new sessions doesn't reuse data from a deleted session in the same request. *Jeremy Kemper*
-
-* Deprecation: verification with :redirect_to => :named_route shouldn't be deprecated. #7525 *Justin French*
-
-* Cookie session store: raise ArgumentError when :session_key is blank. *Jeremy Kemper*
-
-* Deprecation: remove deprecated request, redirect, and dependency methods. Remove deprecated instance variables. Remove deprecated url_for(:symbol, *args) and redirect_to(:symbol, *args) in favor of named routes. Remove uses_component_template_root for toplevel components directory. Privatize deprecated render_partial and render_partial_collection view methods. Remove deprecated link_to_image, link_image_to, update_element_function, start_form_tag, and end_form_tag helper methods. Remove deprecated human_size helper alias. *Jeremy Kemper*
-
-* Consistent public/protected/private visibility for chained methods. #7813 *Dan Manges*
-
-* Prefer MIME constants to strings. #7707 *Dan Kubb*
-
-* Allow array and hash query parameters. Array route parameters are converted/to/a/path as before. #6765, #7047, #7462 *bgipsy, Jeremy McAnally, Dan Kubb, brendan*
-
- \# Add a #dbman attr_reader for CGI::Session and make CGI::Session::CookieStore#generate_digest public so it's easy to generate digests using the cookie store's secret. *Rick Olson*
-* Added Request#url that returns the complete URL used for the request *David Heinemeier Hansson*
-
-* Extract dynamic scaffolding into a plugin. #7700 *Josh Peek*
-
-* Added user/password options for url_for to add http authentication in a URL *David Heinemeier Hansson*
-
-* Fixed that FormTagHelper#text_area_tag should disregard :size option if it's not a string *Brendon Davidson*
-
-* Set the original button value in an attribute of the button when using the :disable_with key with submit_tag, so that the original can be restored later. *Jamis Buck*
-
-* session_enabled? works with session :off. #6680 *Jonathan del Strother*
-
-* Added :port and :host handling to UrlRewriter (which unified url_for usage, regardless of whether it's called in view or controller) #7616 *alancfrancis*
-
-* Allow send_file/send_data to use a registered mime type as the :type parameter #7620 *jonathan*
-
-* Allow routing requirements on map.resource(s) #7633 *quixoten*. Example:
-
- map.resources :network_interfaces, :requirements => { :id => /^\d+\.\d+\.\d+\.\d+$/ }
-
-* Cookie session store: empty and unchanged sessions don't write a cookie. *Jeremy Kemper*
-
-* Added helper(:all) as a way to include all helpers from app/helpers/**/*.rb in ApplicationController *David Heinemeier Hansson*
-
-* Integration tests: introduce methods for other HTTP methods. #6353 *caboose*
-
-* Routing: better support for escaped values in route segments. #7544 [Chris
- Roos]
-* Introduce a cookie-based session store as the Rails default. Sessions typically contain at most a user_id and flash message; both fit within the 4K cookie size limit. A secure message digest is included with the cookie to ensure data integrity (a user cannot alter his user_id without knowing the secret key included in the digest). If you have more than 4K of session data or don't want your data to be visible to the user, pick another session store. Cookie-based sessions are dramatically faster than the alternatives. *Jeremy Kemper*
-
- Example config/environment.rb:
- # Use an application-wide secret key and the default SHA1 message digest.
- config.action_controller.session = { :secret => "can't touch this" }
-
- # Store a secret key per user and employ a stronger message digest.
- config.action_controller.session = {
- :digest => 'SHA512',
- :secret => Proc.new { User.current.secret_key }
- }
-
-* Added .erb and .builder as preferred aliases to the now deprecated .rhtml and .rxml extensions *Chad Fowler*. This is done to separate the renderer from the mime type. .erb templates are often used to render emails, atom, csv, whatever. So labeling them .rhtml doesn't make too much sense. The same goes for .rxml, which can be used to build everything from HTML to Atom to whatever. .rhtml and .rxml will continue to work until Rails 3.0, though. So this is a slow phasing out. All generators and examples will start using the new aliases, though.
-
-* Added caching option to AssetTagHelper#stylesheet_link_tag and AssetTagHelper#javascript_include_tag *DHH*. Examples:
-
- stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
- <link href="/stylesheets/style1.css" media="screen" rel="Stylesheet" type="text/css" />
- <link href="/stylesheets/styleB.css" media="screen" rel="Stylesheet" type="text/css" />
- <link href="/stylesheets/styleX2.css" media="screen" rel="Stylesheet" type="text/css" />
-
- stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is true =>
- <link href="/stylesheets/all.css" media="screen" rel="Stylesheet" type="text/css" />
-
- ...when caching is on, all.css is the concatenation of style1.css, styleB.css, and styleX2.css.
- Same deal for JavaScripts.
-
-* Work around the two connection per host browser limit: use asset%d.myapp.com to distribute asset requests among asset[0123].myapp.com. Use a DNS wildcard or CNAMEs to map these hosts to your asset server. See http://www.die.net/musings/page_load_time/ for background. *Jeremy Kemper*
-
-* Added default mime type for CSS (Mime::CSS) *David Heinemeier Hansson*
-
-* Added that rendering will automatically insert the etag header on 200 OK responses. The etag is calculated using MD5 of the response body. If a request comes in that has a matching etag, the response will be changed to a 304 Not Modified and the response body will be set to an empty string. *David Heinemeier Hansson*
-
-* Added X-Runtime to all responses with the request run time *David Heinemeier Hansson*
-
-* Add Mime::Type convenience methods to check the current mime type. *Rick Olson*
-
- request.format.html? # => true if Mime::HTML
- request.format.jpg? # => true if Mime::JPG
-
- \# ActionController sample usage:
- \# the session will be disabled for non html/ajax requests
- session :off, :if => Proc.new { |req| !(req.format.html? || req.format.js?) }
-
-* Performance: patch cgi/session to require digest/md5 once rather than per #create_new_id. *Stefan Kaes*
-
-* Add a :url_based_filename => true option to ActionController::Streaming::send_file, which allows URL-based filenames. *Thomas Fuchs*
-
-* Fix that FormTagHelper#submit_tag using :disable_with should trigger the onsubmit handler of its form if available *David Heinemeier Hansson*
-
-* Fix #render_file so that TemplateError is called with the correct params and you don't get the WSOD. *Rick Olson*
-
-* Fix issue with deprecation messing up #template_root= usage. Add #prepend_view_path and #append_view_path to allow modification of a copy of the
- superclass' view_paths. *Rick Olson*
-* Allow Controllers to have multiple view_paths instead of a single template_root. Closes #2754 *John Long*
-
-* Add much-needed html-scanner tests. Fixed CDATA parsing bug. *Rick Olson*
-
-* improve error message for Routing for named routes. Closes #7346 *Rob Sanheim*
-
-* Added enhanced docs to routing assertions. Closes #7359 *Rob Sanheim*
-
-* fix form_for example in ActionController::Resources documentation. Closes #7362 *gnarg*
-
-* Make sure that the string returned by TextHelper#truncate is actually a string, not a char proxy -- that should only be used internally while working on a multibyte-safe way of truncating *David Heinemeier Hansson*
-
-* Added FormBuilder#submit as a delegate for FormTagHelper#submit_tag *David Heinemeier Hansson*
-
-* Allow Routes to generate all urls for a set of options by specifying :generate_all => true. Allows caching to properly set or expire all paths for a resource. References #1739. *Nicholas Seckar*
-
-* Change the query parser to map empty GET params to "" rather than nil. Closes #5694. *Nicholas Seckar*
-
-* date_select and datetime_select take a :default option. #7052 *Nik Wakelin*
- date_select "post", "written_on", :default => 3.days.from_now
- date_select "credit_card", "bill_due", :default => { :day => 20 }
-
-* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 *nik.kakelin, ben, julik*
-
-* Improve routes documentation. #7095 *zackchandler*
-
-* mail_to :encode => 'hex' also encodes the mailto: part of the href attribute as well as the linked email when no name is given. #2061 *Jarkko Laine, pfc.pille@gmx.net*
-
-* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 *dkubb*
-
-* Remove deprecated assertions. *Jeremy Kemper*
-
-* Change session restoration to allow namespaced models to be autoloaded. Closes #6348. *Nicholas Seckar*
-
-* Fix doubly appearing parameters due to string and symbol mixups. Closes #2551. *Anthony Eden*
-
-* Fix overly greedy rescues when loading helpers. Fixes #6268. *Nicholas Seckar*
-
-* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 *ceefour*
-
-* Autolinking recognizes trailing and embedded . , : ; #7354 *Jarkko Laine*
-
-* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. *imajes*
-
-* Update to script.aculo.us 1.7.0. *Thomas Fuchs*
-
-* Modernize cookie testing code, and increase coverage (Heckle++) #7101 *Kevin Clark*
-
-* Improve Test Coverage for ActionController::Routing::Route#matches_controller_and_action? (Heckle++) #7115 *Kevin Clark*
-
-* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 *Kevin Clark*
-
-* Fix #distance_of_time_in_words to report accurately against the Duration class. #7114 *eventualbuddha*
-
-* Refactor #form_tag to allow easy extending. *Rick Olson*
-
-* Update to Prototype 1.5.0. *Sam Stephenson*
-
-* RecordInvalid, RecordNotSaved => 422 Unprocessable Entity, StaleObjectError => 409 Conflict. #7097 *dkubb*
-
-* Allow fields_for to be nested inside form_for, so that the name and id get properly constructed *Jamis Buck*
-
-* Allow inGroupsOf and eachSlice to be called through rjs. #7046 *Cody Fauser*
-
-* Allow exempt_from_layout :rhtml. #6742, #7026 *Dan Manges, Squeegy*
-
-* Recognize the .txt extension as Mime::TEXT *Rick Olson*
-
-* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 *Nicholas Seckar, aiwilliams, brentrowland*
-
-* link_to_unless_current works with full URLs as well as paths. #6891 *Jarkko Laine, Manfred Stienstra, idrifter*
-
-* Lookup the mime type for #auto_discovery_link_tag in the Mime::Type class. Closes #6941 *Josh Peek*
-
-* Fix bug where nested resources ignore a parent singleton parent's path prefix. Closes #6940 *Dan Kubb*
-
-* Fix no method error with error_messages_on. Closes #6935 *nik.wakelin Koz*
-
-* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 *Steven Bristol*
-
-* Slight doc tweak to #prepend_filter. Closes #6493 *Jeremy Voorhis*
-
-* Add more extensive documentation to the AssetTagHelper. Closes #6452 *Bob Silva*
-
-* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 *Bob Silva*
-
-* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 *Jan Prill*
-
-* Make sure html_document is reset between integration test requests. *ctm*
-
-* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. *Josh Susser*
-
-* Routing uses URI escaping for path components and CGI escaping for query parameters. *darix, Jeremy Kemper*
-
-* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. *Rick Olson*
-
-* Singleton resources: POST /singleton => create, GET /singleton/new => new. *Jeremy Kemper*
-
-* Use 400 Bad Request status for unrescued ActiveRecord::RecordInvalid exceptions. *Jeremy Kemper*
-
-* Silence log_error deprecation warnings from inspecting deprecated instance variables. *Nate Wiger*
-
-* Only cache GET requests with a 200 OK response. #6514, #6743 *RSL, anamba*
-
-* Add a 'referer' attribute to TestRequest. *Jamis Buck*
-
-* Ensure render :json => ... skips the layout. Closes #6808 *Josh Peek*
-
-* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 *mitreandy*
-
-* Correctly report which filter halted the chain. #6699 *Martin Emde*
-
-* Fix a bug in Routing where a parameter taken from the path of the current request could not be used as a query parameter for the next. Closes #6752. *Nicholas Seckar*
-
-* Unrescued ActiveRecord::RecordNotFound responds with 404 instead of 500. *Jeremy Kemper*
-
-* Improved auto_link to match more valid urls correctly *Tobias Lütke*
-
-* Add singleton resources. *Rick Olson*
-
- map.resource :account
-
- GET /account
- GET /account;edit
- UPDATE /account
- DELETE /account
-
-* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 *Scott Raymond, eventualbuddha*
- # application/json response with body 'Element.show({:name: "David"})'
- respond_to do |format|
- format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
- end
-
-* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 *sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva*
-
-* Adds html id attribute to date helper elements. #1050, #1382 *mortonda@dgrmm.net, David North, Bob Silva*
-
-* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 *moriq, Doug Fales, Bob Silva*
-
-* Add :order to datetime_select, select_datetime, and select_date. #1427 *Timothee Peignier, Patrick Lenz, Bob Silva*
-
-* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 *Justin Palmer, Andre Caum, Bob Silva*
-
-* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 *csn, Bob Silva*
-
-* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 *tomasj, Bob Silva*
-
-* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 *Bob Silva*
-
-* Added map.root as an alias for map.connect '' *David Heinemeier Hansson*
-
-* Added Request#format to return the format used for the request as a mime type. If no format is specified, the first Request#accepts type is used. This means you can stop using respond_to for anything else than responses *DHH*. Examples:
-
- GET /posts/5.xml | request.format => Mime::XML
- GET /posts/5.xhtml | request.format => Mime::HTML
- GET /posts/5 | request.format => request.accepts.first (usually Mime::HTML for browsers)
-
-* Added the option for extension aliases to mime type registration *DHH*. Example (already in the default routes):
-
- Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
-
- ...will respond on both .html and .xhtml.
-
-* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. *Jeremy Kemper*
-
-* Added CSV to Mime::SET so that respond_to csv will work *Cody Fauser*
-
-* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) *David Heinemeier Hansson*
-
-* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 *David Heinemeier Hansson*
-
-* Update Routing to complain when :controller is not specified by a route. Closes #6669. *Nicholas Seckar*
-
-* Ensure render_to_string cleans up after itself when an exception is raised. #6658 *Rob Sanheim*
-
-* Extract template_changed_since? from compile_template? so plugins may override its behavior for non-file-based templates. #6651 *Jeff Barczewski*
-
-* Update to Prototype and script.aculo.us [5579]. *Thomas Fuchs*
-
-* simple_format helper doesn't choke on nil. #6644 *jerry426*
-
-* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again *Thomas Fuchs*
-
-* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. *Nicholas Seckar*
-
-* ActionView::Base.erb_variable accessor names the buffer variable used to render templates. Defaults to _erbout; use _buf for erubis. *Rick Olson*
-
-* assert_select_rjs :remove. *Dylan Egan*
-
-* Always clear model associations from session. #4795 *sd@notso.net, andylien@gmail.com*
-
-* Update to Prototype 1.5.0_rc2. *Sam Stephenson*
-
-* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. *Sam Stephenson*
-
-* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 *dkubb*
-
-* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 *Andreas Schwarz, Jeremy Kemper*
-
-* assert_response supports symbolic status codes. #6569 *Kevin Clark*
- assert_response :ok
- assert_response :not_found
- assert_response :forbidden
-
-* Cache parsed query parameters. #6559 *Stefan Kaes*
-
-* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS *Thomas Fuchs*
-
-* pluralize helper interprets nil as zero. #6474 *Tim Pope*
-
-* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 *Bob Silva*
-
-* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. *Jeremy Kemper*
-
-* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 *Bob Silva*
-
-* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions *Thomas Fuchs*
-
-* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. *Rick Olson*
-
-* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag *Rick Olson*
-
-* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. *Rick Olson*
-
-* Added block-usage to TagHelper#content_tag *DHH*. Example:
-
- <% content_tag :div, :class => "strong" %>
- Hello world!
- <% end %>
-
- Will output:
- <div class="strong">Hello world!</div>
-
-* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 *Bob Silva*
-
-* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 *Bob Silva*
-
-* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 *Bob Silva/chrismear*
-
-* Force *_url named routes to show the host in ActionView *Rick Olson*
-
- <%= url_for ... %> # no host
- <%= foo_path %> # no host
- <%= foo_url %> # host!
-
-* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. *Sam Stephenson*
-
-* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. *Sam Stephenson*
-
-* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. *Rick Olson*
-
-* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc. *Rick Olson*
-
-* Fix deprecation warnings when rendering the template error template. *Nicholas Seckar*
-
-* Fix routing to correctly determine when generation fails. Closes #6300. *psross*.
-
-* Fix broken assert_generates when extra keys are being checked. *Jamis Buck*
-
-* Replace KCODE checks with String#chars for truncate. Closes #6385 *Manfred Stienstra*
-
-* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. *Marcel Molina Jr.*
-
-* Use String#chars in TextHelper::excerpt. Closes #6386 *Manfred Stienstra*
-
-* Install named routes into ActionView::Base instead of proxying them to the view via helper_method. Closes #5932. *Nicholas Seckar*
-
-* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
-
-* Fix relative URL root matching problems. *Mark Imbriaco*
-
-* Fix filter skipping in controller subclasses. #5949, #6297, #6299 *Martin Emde*
-
-* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). *Jeremy Kemper*
-
-* Rename test assertion to prevent shadowing. Closes #6306. *psross*
-
-* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 *Philip Hallstrom*
-
-* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 *evansj*
-
-* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 *tzaharia*. Example:
-
- update_page_tag :defer => 'true' { |page| ... }
-
- Gives:
-
- <script defer="true" type="text/javascript">...</script>
-
- Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
-
-* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 *Mike Naberezny*
-
-* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 *sven@c3d2.de*
-
-* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 *cmselmer*
-
-* respond_to :html doesn't assume .rhtml. #6281 *Hampton Catlin*
-
-* Fixed some deprecation warnings in ActionPack *Rick Olson*
-
-* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 *japgolly*
-
-* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. *Jeremy Kemper*
-
-* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. *Jamis Buck*. Examples:
-
- head :status => 404 # expands to "404 Not Found"
- head :status => :not_found # expands to "404 Not Found"
- head :status => :created # expands to "201 Created"
-
-* Add head(options = {}) for responses that have no body. *Jamis Buck*. Examples:
-
- head :status => 404 # return an empty response with a 404 status
- head :location => person_path(@person), :status => 201
-
-* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. *Rick Olson*
-
-* strip_links is case-insensitive. #6285 *tagoh, Bob Silva*
-
-* Clear the cache of possible controllers whenever Routes are reloaded. *Nicholas Seckar*
-
-* Filters overhaul including meantime filter support using around filters + blocks. #5949 *Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper*
-
-* Update RJS render tests. *sam*
-
-* Update CGI process to allow sessions to contain namespaced models. Closes #4638. *dfelstead@site5.com*
-
-* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. *Nicholas Seckar*
-
-* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 *sdsykes, fhanshaw@vesaria.com*
-
-* Added that respond_to blocks will automatically set the content type to be the same as is requested *DHH*. Examples:
-
- respond_to do |format|
- format.html { render :text => "I'm being sent as text/html" }
- format.rss { render :text => "I'm being sent as application/rss+xml" }
- format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
- end
-
-* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) *David Heinemeier Hansson*
-
-* Added proper getters and setters for content type and charset *DHH*. Example of what we used to do:
-
- response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
-
- ...now:
-
- response.content_type = Mime::ATOM
- response.charset = "utf-8"
-
-* Updated prototype.js to 1.5.0_rc1 with latest fixes. *Rick Olson*
-
- - XPATH support
- - Make Form.getElements() return elements in the correct order
- - fix broken Form.serialize return
-
-* Declare file extensions exempt from layouts. #6219 *brandon*
- Example: ActionController::Base.exempt_from_layout 'rpdf'
-
-* Add chained replace/update support for assert_select_rjs *Rick Olson*
-
- Given RJS like...
-
- page['test1'].replace "<div id=\"1\">foo</div>"
- page['test2'].replace_html "<div id=\"2\">foo</div>"
-
- Test it with...
-
- assert_select_rjs :chained_replace
- assert_select_rjs :chained_replace, "test1"
-
- assert_select_rjs :chained_replace_html
- assert_select_rjs :chained_replace_html, "test2"
-
-* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 *choonkeat@gmail.com*
-
-* Skip params with empty names, such as the &=Save query string from <input type="submit"/>. #2569 *Manfred Stienstra, raphinou@yahoo.com*
-
-* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 *Eric Hodel*
-
-* Add descriptive messages to the exceptions thrown by cgi_methods. #6091, #6103 *Nicholas Seckar, Bob Silva*
-
-* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 *petermichaux@gmail.com*
-
-* Update UrlWriter to support :only_path. *Nicholas Seckar, Dave Thomas*
-
-* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional *DHH*. So what used to require a nil, like this:
-
- link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
-
- ...can be written like this:
-
- link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
-
-* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
-
-* Update to Prototype 1.5.0_rc1 *sam*
-
-* Added access to nested attributes in RJS #4548 *richcollins@gmail.com*. Examples:
-
- page['foo']['style'] # => $('foo').style;
- page['foo']['style']['color'] # => $('blank_slate').style.color;
- page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
- page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
-
-* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) *eule@space.ch*
-
-* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension *David Heinemeier Hansson*
-
-* Fixed FormOptionsHelper#select to respect :selected value #5813
-
-* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 *moriq@moriq.com*
-
-* Fixed TextHelper#pluralize to handle 1 as a string #5909 *rails@bencurtis.com*
-
-* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 *Bob Silva*
-
-* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" *David Heinemeier Hansson*
-
-* Integration tests: thoroughly test ActionController::Integration::Session. #6022 *Kevin Clark*
- (tests skipped unless you `gem install mocha`)
-
-* Added deprecation language for pagination which will become a plugin by Rails 2.0 *David Heinemeier Hansson*
-
-* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 *David Heinemeier Hansson*
-
-* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support *David Heinemeier Hansson*
-
-* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 *assaf.arkin@gmail.com*
-
-* radio_button_tag generates unique id attributes. #3353 *Bob Silva, somekool@gmail.com*
-
-* strip_tags passes through blank args such as nil or "". #2229, #6702 *duncan@whomwah.com, dharana*
-
-* Cleanup assert_tag :children counting. #2181 *jamie@bravenet.com*
-
-* button_to accepts :method so you can PUT and DELETE with it. #6005 *Dan Webb*
-
-* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. *Rick Olson*
-
-* Update routing documentation. Closes #6017 *Nathan Witmer*
-
-* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 *Nathan Witmer*
-
-* Deprecation: update docs. #5998 *Jakob Skjerning, Kevin Clark*
-
-* Make auto_link parse a greater subset of valid url formats. *Jamis Buck*
-
-* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. *Mike Clark*
-
-* Tighten rescue clauses. #5985 *james@grayproductions.net*
-
-* Fix send_data documentation typo. #5982 *brad@madriska.com*
-
-* Switch to using FormEncodedPairParser for parsing request parameters. *Nicholas Seckar, David Heinemeier Hansson*
-
-* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. *Tobias Lütke*
-
-* Deprecation: test deprecated instance vars in partials. *Jeremy Kemper*
-
-* Add UrlWriter to allow writing urls from Mailers and scripts. *Nicholas Seckar*
-
-* Clean up and run the Active Record integration tests by default. #5854 *Kevin Clark, Jeremy Kemper*
-
-* Correct example in cookies docs. #5832 *jessemerriman@warpmail.net*
-
-* Updated to script.aculo.us 1.6.2 *Thomas Fuchs*
-
-* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. *Nicholas Seckar*
-
-* Add controller_paths variable to Routing. *Nicholas Seckar*
-
-* Fix assert_redirected_to issue with named routes for module controllers. *Rick Olson*
-
-* Tweak RoutingError message to show option diffs, not just missing named route significant keys. *Rick Olson*
-
-* Invoke method_missing directly on hidden actions. Closes #3030. *Nicholas Seckar*
-
-* Require Tempfile explicitly for TestUploadedFile due to changes in class auto loading. *Rick Olson*
-
-* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. *Rick Olson*
-
-* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
-
-* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. *Jeremy Kemper*
-
-* Add support for the param_name parameter to the auto_complete_field helper. #5026 *david.a.williams@gmail.com*
-
-* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. *Jeremy Kemper*
-
-* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 *François Beausoleil*
-
-* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 *pjhyett@gmail.com*
-
-* Short documentation to mention use of Mime::Type.register. #5710 *choonkeat@gmail.com*
-
-* Make controller_path available as an instance method. #5724 *jmckible@gmail.com*
-
-* Update query parser to support adjacent hashes. *Nicholas Seckar*
-
-* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. *Marcel Molina Jr.*
-
-* Restrict Request Method hacking with ?_method to POST requests. *Rick Olson*
-
-* Fix bug when passing multiple options to SimplyRestful, like :new => { :preview => :get, :draft => :get }. *Rick Olson, Josh Susser, Lars Pind*
-
-* Dup the options passed to map.resources so that multiple resources get the same options. *Rick Olson*
-
-* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. *Rick Olson*
-
-* Added map.resources from the Simply Restful plugin *DHH*. Examples (the API has changed to use plurals!):
-
- map.resources :messages
- map.resources :messages, :comments
- map.resources :messages, :new => { :preview => :post }
-
-* Fixed that integration simulation of XHRs should set Accept header as well *Edward Frederick*
-
-* TestRequest#reset_session should restore a TestSession, not a hash *Michael Koziarski*
-
-* Don't search a load-path of '.' for controller files *Jamis Buck*
-
-* Update integration.rb to require test_process explicitly instead of via Dependencies. *Nicholas Seckar*
-
-* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 *lmarlow*
-
-* Allow form_for and fields_for to work with indexed form inputs. *Jeremy Kemper, Matt Lyon*
-
- <% form_for 'post[]', @post do |f| -%>
- <% end -%>
-
-* Remove leak in development mode by replacing define_method with module_eval. *Nicholas Seckar*
-
-* Provide support for decimal columns to form helpers. Closes #5672. *Dave Thomas*
-
-* Update documentation for erb trim syntax. #5651 *matt@mattmargolis.net*
-
-* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 *olivier_ansaldi@yahoo.com*
-
-* Reset @html_document between requests so assert_tag works. #4810 *Jarkko Laine, easleydp@gmail.com*
-
-* Update render :partial documentation. #5646 *matt@mattmargolis.net*
-
-* Integration tests behave well with render_component. #4632 *edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com*
-
-* Added exception handling of missing layouts #5373 *chris@ozmm.org*
-
-* Fixed that real files and symlinks should be treated the same when compiling templates #5438 *zachary@panandscan.com*
-
-* Fixed that the flash should be reset when reset_session is called #5584 *Shugo Maeda*
-
-* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 *murpyh@rubychan.de*
-
-* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) *David Heinemeier Hansson*
-
-* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. *Nicholas Seckar*
-
-* Avoid naming collision among compiled view methods. *Jeremy Kemper*
-
-* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 *Mislav Marohnić*
-
-* Determine the correct template_root for deeply nested components. #2841 *s.brink@web.de*
-
-* Fix that routes with *path segments in the recall can generate URLs. *Rick Olson*
-
-* Fix strip_links so that it doesn't hang on multiline <acronym> tags *Jamis Buck*
-
-* Remove problematic control chars in rescue template. #5316 *Stefan Kaes*
-
-* Make sure passed routing options are not mutated by routing code. #5314 *Blair Zajac*
-
-* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. *Jamis Buck*
-
-* Escape the path before routing recognition. #3671
-
-* Make sure :id and friends are unescaped properly. #5275 *me@julik.nl*
-
-* Fix documentation for with_routing to reflect new reality. #5281 *rramdas@gmail.com*
-
-* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 *mklame@atxeu.com, matthew@walker.wattle.id.au*
-
-* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types *David Heinemeier Hansson*
-
-* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types *DHH*. Example: Mime::Type.register("image/gif", :gif)
-
-* Added support for Mime objects in render :content_type option *DHH*. Example: render :text => some_atom, :content_type => Mime::ATOM
-
-* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <m.stienstra@fngtps.com>*
-
-* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. *Nicholas Seckar, Jamis Buck*
-
- map.connect '/foo/:id', :controller => '...', :action => '...'
- map.connect '/foo/:id.:format', :controller => '...', :action => '...'
- map.connect '/foo/:id', ..., :conditions => { :method => :get }
-
-* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. *Jeremy Kemper*
-
-* Accept multipart PUT parameters. #5235 *guy.naor@famundo.com*
-
-* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output *DHH*. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find :all
-
- respond_to do |format|
- format.html
- format.xml { render :xml => @posts.to_xml }
- format.rss { render :action => "feed.rxml" }
- end
- end
- end
-
- \# returns HTML when requested by a browser, since the browser
- \# has the HTML mimetype at the top of its priority list
- Accept: text/html
- GET /weblog
-
- \# returns the XML
- Accept: application/xml
- GET /weblog
-
- \# returns the HTML
- Accept: application/xml
- GET /weblog.html
-
- \# returns the XML
- Accept: text/html
- GET /weblog.xml
-
- All this relies on the fact that you have a route that includes .:format.
-
-* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post *David Heinemeier Hansson*
-
-* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete *David Heinemeier Hansson*
-
-* follow_redirect doesn't complain about being redirected to the same controller. #5153 *dymo@mk.ukrtelecom.ua*
-
-* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. *Kevin Clark*
-
-* Fix NoMethodError when parsing params like &&. *Adam Greenfield*
-
-* Fix flip flopped logic in docs for url_for's :only_path option. Closes #4998. *esad@esse.at*
-
-* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). *Jeremy Kemper*
-
-* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 *anonymous*
-
-* Small fix in routing to allow dynamic routes (broken after [4242]) *Rick Olson*
-
- map.connect '*path', :controller => 'files', :action => 'show'
-
-* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
-
-* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
-
-* Use #flush between switching from #write to #syswrite. Closes #4907. *Blair Zajac <blair@orcaware.com>*
-
-* Documentation fix: integration test scripts don't require integration_test. Closes #4914. *Frederick Ros <sl33p3r@free.fr>*
-
-* ActionController::Base Summary documentation rewrite. Closes #4900. *Kevin Clark*
-
-* Fix text_helper.rb documentation rendering. Closes #4725. *Frederick Ros*
-
-* Fixes bad rendering of JavaScriptMacrosHelper rdoc (closes #4910) *Frederick Ros*
-
-* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. *andrew@redlinesoftware.com, Marcel Molina Jr.*
-
- error_messages_for :account, :user, :subscription, :object_name => :account
-
-* Enhance documentation for setting headers in integration tests. Skip auto HTTP prepending when its already there. Closes #4079. *Rick Olson*
-
-* Documentation for AbstractRequest. Closes #4895. *Kevin Clark*
-
-* Refactor various InstanceTag instance method to class methods. Closes #4800. *Stefan Kaes*
-
-* Remove all remaining references to @params in the documentation. *Marcel Molina Jr.*
-
-* Add documentation for redirect_to :back's RedirectBackError exception. *Marcel Molina Jr.*
-
-* Update layout and content_for documentation to use yield rather than magic @content_for instance variables. *Marcel Molina Jr.*
-
-* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: *Rick Olson*
-
- redirect_to :action => 'new'
- assert_redirected_to :controller => 'monkeys', :action => 'new'
-
-* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. *Rick Olson*
-
-* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method *Rick Olson*
-
- assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
- assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
-
-* Diff compared options with #assert_redirected_to *Rick Olson*
-
-* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action *Jamis Buck*
-
-* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. *zraii@comcast.net, Sam Stephenson*
-
-* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for *David Heinemeier Hansson*
-
-* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. *Jamis Buck*
-
-* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. *Sam Stephenson*
- ex. verify :only => :speak, :method => :post,
- :render => { :status => 405, :text => "Must be post" },
- :add_headers => { "Allow" => "POST" }
-
-* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled #1897 *jeremye@bsa.ca.gov*
-
-
-## 1.13.3 (March 12th, 2007) ##
-
-* Apply [5709] to stable.
-
-* session_enabled? works with session :off. #6680 *Jonathan del Strother*
-
-* Performance: patch cgi/session to require digest/md5 once rather than per #create_new_id. *Stefan Kaes*
-
-
-## 1.13.2 (February 5th, 2007) ##
-
-* Add much-needed html-scanner tests. Fixed CDATA parsing bug. *Rick Olson*
-
-* improve error message for Routing for named routes. *Rob Sanheim*
-
-* Added enhanced docs to routing assertions. *Rob Sanheim*
-
-* fix form_for example in ActionController::Resources documentation. *gnarg*
-
-* Add singleton resources from trunk *Rick Olson*
-
-* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 *nik.kakelin, ben, julik*
-
-* Improve routes documentation. #7095 *zackchandler*
-
-* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 *dkubb*
-
-* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 *ceefour*
-
-* Autolinking recognizes trailing and embedded . , : ; #7354 *Jarkko Laine*
-
-* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. *imajes*
-
-* Improved auto_link to match more valid urls correctly *Tobias Lütke*
-
-
-## 1.13.1 (January 18th, 2007) ##
-
-* Fixed content-type bug in Prototype *sam*
-
-
-## 1.13.0 (January 16th, 2007) ##
-
-* Modernize cookie testing code, and increase coverage (Heckle++) #7101 *Kevin Clark*
-
-* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 *Kevin Clark*
-
-* Update to Prototype 1.5.0. *Sam Stephenson*
-
-* Allow exempt_from_layout :rhtml. #6742, #7026 *Dan Manges, Squeegy*
-
-* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 *Nicholas Seckar, aiwilliams, brentrowland*
-
-* link_to_unless_current works with full URLs as well as paths. #6891 *Jarkko Laine, Manfred Stienstra, idrifter*
-
-* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 *mitreandy*
-
-* Fix no method error with error_messages_on. Closes #6935 *nik.wakelin Koz*
-
-* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 *Steven Bristol*
-
-* Slight doc tweak to #prepend_filter. Closes #6493 *Jeremy Voorhis*
-
-* Add more extensive documentation to the AssetTagHelper. Closes #6452 *Bob Silva*
-
-* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 *Bob Silva*
-
-* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 *Jan Prill*
-
-* Make sure html_document is reset between integration test requests. *ctm*
-
-* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. *Josh Susser*
-
-* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. *Rick Olson*
-
-* Ensure render :json => ... skips the layout. #6808 *Josh Peek*
-
-* Silence log_error deprecation warnings from inspecting deprecated instance variables. *Nate Wiger*
-
-* Only cache GET requests with a 200 OK response. #6514, #6743 *RSL, anamba*
-
-* Correctly report which filter halted the chain. #6699 *Martin Emde*
-
-* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 *Scott Raymond, eventualbuddha*
- # application/json response with body 'Element.show({:name: "David"})'
- respond_to do |format|
- format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
- end
-
-* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 *sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva*
-
-* Adds html id attribute to date helper elements. #1050, #1382 *mortonda@dgrmm.net, David North, Bob Silva*
-
-* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 *moriq, Doug Fales, Bob Silva*
-
-* Add :order to datetime_select, select_datetime, and select_date. #1427 *Timothee Peignier, Patrick Lenz, Bob Silva*
-
-* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 *Justin Palmer, Andre Caum, Bob Silva*
-
-* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 *csn, Bob Silva*
-
-* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 *tomasj, Bob Silva*
-
-* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 *Bob Silva*
-
-* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. *Jeremy Kemper*
-
-* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) *David Heinemeier Hansson*
-
-* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 *David Heinemeier Hansson*
-
-
-## 1.13.0 RC1 (r5619, November 22nd, 2006) ##
-
-* Update Routing to complain when :controller is not specified by a route. Closes #6669. *Nicholas Seckar*
-
-* Ensure render_to_string cleans up after itself when an exception is raised. #6658 *rsanheim*
-
-* Update to Prototype and script.aculo.us [5579]. *Sam Stephenson, Thomas Fuchs*
-
-* simple_format helper doesn't choke on nil. #6644 *jerry426*
-
-* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. *Nicholas Seckar*
-
-* Deprecate standalone components. *Jeremy Kemper*
-
-* Always clear model associations from session. #4795 *sd@notso.net, andylien@gmail.com*
-
-* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. *Sam Stephenson*
-
-* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 *dkubb*
-
-* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 *Andreas Schwarz, Jeremy Kemper*
-
-* assert_response supports symbolic status codes. #6569 *Kevin Clark*
- assert_response :ok
- assert_response :not_found
- assert_response :forbidden
-
-* Cache parsed query parameters. #6559 *Stefan Kaes*
-
-* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS *Thomas Fuchs*
-
-* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 *Bob Silva*
-
-* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. *Jeremy Kemper*
-
-* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 *Bob Silva*
-
-* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. *Rick Olson*
-
-* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag *Rick Olson*
-
-* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. *Rick Olson*
-
-* Added block-usage to TagHelper#content_tag *DHH*. Example:
-
- <% content_tag :div, :class => "strong" %>
- Hello world!
- <% end %>
-
- Will output:
- <div class="strong">Hello world!</div>
-
-* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 *Bob Silva*
-
-* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 *Bob Silva*
-
-* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 *Bob Silva/chrismear*
-
-* Force *_url named routes to show the host in ActionView *Rick Olson*
-
- <%= url_for ... %> # no host
- <%= foo_path %> # no host
- <%= foo_url %> # host!
-
-* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. *Sam Stephenson*
-
-* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. *Sam Stephenson*
-
-* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. *Rick Olson*
-
-* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc. *Rick Olson*
-
-* Fix routing to correctly determine when generation fails. Closes #6300. *psross*.
-
-* Fix broken assert_generates when extra keys are being checked. *Jamis Buck*
-
-* Replace KCODE checks with String#chars for truncate. Closes #6385 *Manfred Stienstra*
-
-* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. *Marcel Molina Jr.*
-
-* Use String#chars in TextHelper::excerpt. Closes #6386 *Manfred Stienstra*
-
-* Fix relative URL root matching problems. *Mark Imbriaco*
-
-* Fix filter skipping in controller subclasses. #5949, #6297, #6299 *Martin Emde*
-
-* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). *Jeremy Kemper*
-
-* Rename test assertion to prevent shadowing. Closes #6306. *psross*
-
-* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 *Philip Hallstrom*
-
-* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 *evansj*
-
-* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 *tzaharia*. Example:
-
- update_page_tag :defer => 'true' { |page| ... }
-
- Gives:
-
- <script defer="true" type="text/javascript">...</script>
-
- Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
-
-* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 *Mike Naberezny*
-
-* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 *sven@c3d2.de*
-
-* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 *cmselmer*
-
-* respond_to :html doesn't assume .rhtml. #6281 *Hampton Catlin*
-
-* Fixed some deprecation warnings in ActionPack *Rick Olson*
-
-* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 *japgolly*
-
-* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. *Jeremy Kemper*
-
-* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. *Jamis Buck*. Examples:
-
- head :status => 404 # expands to "404 Not Found"
- head :status => :not_found # expands to "404 Not Found"
- head :status => :created # expands to "201 Created"
-
-* Add head(options = {}) for responses that have no body. *Jamis Buck*. Examples:
-
- head :status => 404 # return an empty response with a 404 status
- head :location => person_path(@person), :status => 201
-
-* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. *Rick Olson*
-
-* strip_links is case-insensitive. #6285 *tagoh, Bob Silva*
-
-* Clear the cache of possible controllers whenever Routes are reloaded. *Nicholas Seckar*
-
-* Filters overhaul including meantime filter support using around filters + blocks. #5949 *Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper*
-
-* Update CGI process to allow sessions to contain namespaced models. Closes #4638. *dfelstead@site5.com*
-
-* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. *Nicholas Seckar*
-
-* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 *sdsykes, fhanshaw@vesaria.com*
-
-* Added that respond_to blocks will automatically set the content type to be the same as is requested *DHH*. Examples:
-
- respond_to do |format|
- format.html { render :text => "I'm being sent as text/html" }
- format.rss { render :text => "I'm being sent as application/rss+xml" }
- format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
- end
-
-* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) *David Heinemeier Hansson*
-
-* Added proper getters and setters for content type and charset *DHH*. Example of what we used to do:
-
- response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
-
- ...now:
-
- response.content_type = Mime::ATOM
- response.charset = "utf-8"
-
-* Declare file extensions exempt from layouts. #6219 *brandon*
- Example: ActionController::Base.exempt_from_layout 'rpdf'
-
-* Add chained replace/update support for assert_select_rjs *Rick Olson*
-
- Given RJS like...
-
- page['test1'].replace "<div id=\"1\">foo</div>"
- page['test2'].replace_html "<div id=\"2\">foo</div>"
-
- Test it with...
-
- assert_select_rjs :chained_replace
- assert_select_rjs :chained_replace, "test1"
-
- assert_select_rjs :chained_replace_html
- assert_select_rjs :chained_replace_html, "test2"
-
-* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 *choonkeat@gmail.com*
-
-* Skip params with empty names, such as the &=Save query string from <input type="submit"/>. #2569 *Manfred Stienstra, raphinou@yahoo.com*
-
-* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 *Eric Hodel*
-
-* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 *petermichaux@gmail.com*
-
-* Update UrlWriter to support :only_path. *Nicholas Seckar, Dave Thomas*
-
-* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional *DHH*. So what used to require a nil, like this:
-
- link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
-
- ...can be written like this:
-
- link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
-
-* Added access to nested attributes in RJS #4548 *richcollins@gmail.com*. Examples:
-
- page['foo']['style'] # => $('foo').style;
- page['foo']['style']['color'] # => $('blank_slate').style.color;
- page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
- page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
-
-* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) *eule@space.ch*
-
-* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension *David Heinemeier Hansson*
-
-* Fixed FormOptionsHelper#select to respect :selected value #5813
-
-* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 *moriq@moriq.com*
-
-* Fixed TextHelper#pluralize to handle 1 as a string #5909 *rails@bencurtis.com*
-
-* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 *Bob Silva*
-
-* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" *David Heinemeier Hansson*
-
-* Added deprecation language for pagination which will become a plugin by Rails 2.0 *David Heinemeier Hansson*
-
-* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 *David Heinemeier Hansson*
-
-* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support *David Heinemeier Hansson*
-
-* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 *assaf.arkin@gmail.com*
-
-* radio_button_tag generates unique id attributes. #3353 *Bob Silva, somekool@gmail.com*
-
-* strip_tags passes through blank args such as nil or "". #2229, #6702 *duncan@whomwah.com, dharana*
-
-* Cleanup assert_tag :children counting. #2181 *jamie@bravenet.com*
-
-* button_to accepts :method so you can PUT and DELETE with it. #6005 *Dan Webb*
-
-* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. *Rick Olson*
-
-* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 *Nathan Witmer*
-
-* Make auto_link parse a greater subset of valid url formats. *Jamis Buck*
-
-* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. *Mike Clark*
-
-* Switch to using FormEncodedPairParser for parsing request parameters. *Nicholas Seckar, David Heinemeier Hansson*
-
-* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. *Tobias Lütke*
-
-* Deprecation: test deprecated instance vars in partials. *Jeremy Kemper*
-
-* Add UrlWriter to allow writing urls from Mailers and scripts. *Nicholas Seckar*
-
-* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. *Nicholas Seckar*
-
-* Add controller_paths variable to Routing. *Nicholas Seckar*
-
-* Fix assert_redirected_to issue with named routes for module controllers. *Rick Olson*
-
-* Tweak RoutingError message to show option diffs, not just missing named route significant keys. *Rick Olson*
-
-* Invoke method_missing directly on hidden actions. Closes #3030. *Nicholas Seckar*
-
-* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. *Rick Olson*
-
-* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
-
-* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. *Jeremy Kemper*
-
-* Add support for the param_name parameter to the auto_complete_field helper. #5026 *david.a.williams@gmail.com*
-
-* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. *Jeremy Kemper*
-
-* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 *François Beausoleil*
-
-* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 *pjhyett@gmail.com*
-
-* Make controller_path available as an instance method. #5724 *jmckible@gmail.com*
-
-* Update query parser to support adjacent hashes. *Nicholas Seckar*
-
-* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. *Marcel Molina Jr.*
-
-* Restrict Request Method hacking with ?_method to POST requests. *Rick Olson*
-
-* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. *Rick Olson*
-
-* Added map.resources from the Simply Restful plugin *DHH*. Examples (the API has changed to use plurals!):
-
- map.resources :messages
- map.resources :messages, :comments
- map.resources :messages, :new => { :preview => :post }
-
-* Fixed that integration simulation of XHRs should set Accept header as well *Edward Frederick*
-
-* TestRequest#reset_session should restore a TestSession, not a hash *Michael Koziarski*
-
-* Don't search a load-path of '.' for controller files *Jamis Buck*
-
-* Update integration.rb to require test_process explicitly instead of via Dependencies. *Nicholas Seckar*
-
-* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 *lmarlow*
-
-* Allow form_for and fields_for to work with indexed form inputs. *Jeremy Kemper, Matt Lyon*
-
- <% form_for 'post[]', @post do |f| -%>
- <% end -%>
-
-* Remove leak in development mode by replacing define_method with module_eval. *Nicholas Seckar*
-
-* Provide support for decimal columns to form helpers. Closes #5672. *Dave Thomas*
-
-* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 *olivier_ansaldi@yahoo.com*
-
-* Reset @html_document between requests so assert_tag works. #4810 *Jarkko Laine, easleydp@gmail.com*
-
-* Integration tests behave well with render_component. #4632 *edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com*
-
-* Added exception handling of missing layouts #5373 *chris@ozmm.org*
-
-* Fixed that real files and symlinks should be treated the same when compiling templates #5438 *zachary@panandscan.com*
-
-* Fixed that the flash should be reset when reset_session is called #5584 *Shugo Maeda*
-
-* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 *murpyh@rubychan.de*
-
-* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) *David Heinemeier Hansson*
-
-* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. *Nicholas Seckar*
-
-* Avoid naming collision among compiled view methods. *Jeremy Kemper*
-
-* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 *Mislav Marohnić*
-
-* Determine the correct template_root for deeply nested components. #2841 *s.brink@web.de*
-
-* Fix that routes with *path segments in the recall can generate URLs. *Rick Olson*
-
-* Fix strip_links so that it doesn't hang on multiline <acronym> tags *Jamis Buck*
-
-* Remove problematic control chars in rescue template. #5316 *Stefan Kaes*
-
-* Make sure passed routing options are not mutated by routing code. #5314 *Blair Zajac*
-
-* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. *Jamis Buck*
-
-* Escape the path before routing recognition. #3671
-
-* Make sure :id and friends are unescaped properly. #5275 *me@julik.nl*
-
-* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 *mklame@atxeu.com, matthew@walker.wattle.id.au*
-
-* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types *David Heinemeier Hansson*
-
-* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types *DHH*. Example: Mime::Type.register("image/gif", :gif)
-
-* Added support for Mime objects in render :content_type option *DHH*. Example: render :text => some_atom, :content_type => Mime::ATOM
-
-* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <m.stienstra@fngtps.com>*
-
-* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. *Nicholas Seckar, Jamis Buck*
-
- map.connect '/foo/:id', :controller => '...', :action => '...'
- map.connect '/foo/:id.:format', :controller => '...', :action => '...'
- map.connect '/foo/:id', ..., :conditions => { :method => :get }
-
-* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. *Jeremy Kemper*
-
-* Accept multipart PUT parameters. #5235 *guy.naor@famundo.com*
-
-* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output *DHH*. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find :all
-
- respond_to do |format|
- format.html
- format.xml { render :xml => @posts.to_xml }
- format.rss { render :action => "feed.rxml" }
- end
- end
- end
-
- \# returns HTML when requested by a browser, since the browser
- \# has the HTML mimetype at the top of its priority list
- Accept: text/html
- GET /weblog
-
- \# returns the XML
- Accept: application/xml
- GET /weblog
-
- \# returns the HTML
- Accept: application/xml
- GET /weblog.html
-
- \# returns the XML
- Accept: text/html
- GET /weblog.xml
-
- All this relies on the fact that you have a route that includes .:format.
-
-* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post *David Heinemeier Hansson*
-
-* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete *David Heinemeier Hansson*
-
-* follow_redirect doesn't complain about being redirected to the same controller. #5153 *dymo@mk.ukrtelecom.ua*
-
-* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. *Kevin Clark*
-
-* Fix NoMethodError when parsing params like &&. *Adam Greenfield*
-
-* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). *Jeremy Kemper*
-
-* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 *anonymous*
-
-* Small fix in routing to allow dynamic routes (broken after [4242]) *Rick Olson*
-
- map.connect '*path', :controller => 'files', :action => 'show'
-
-* Use #flush between switching from #write to #syswrite. Closes #4907. *Blair Zajac <blair@orcaware.com>*
-
-* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. *andrew@redlinesoftware.com, Marcel Molina Jr.*
-
- error_messages_for :account, :user, :subscription, :object_name => :account
-
-* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: *Rick Olson*
-
- redirect_to :action => 'new'
- assert_redirected_to :controller => 'monkeys', :action => 'new'
-
-* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method *Rick Olson*
-
- assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
- assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
-
-* Diff compared options with #assert_redirected_to *Rick Olson*
-
-* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action *Jamis Buck*
-
-* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. *zraii@comcast.net, Sam Stephenson*
-
-* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. *Jamis Buck*
-
-* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. *Sam Stephenson*
- ex. verify :only => :speak, :method => :post,
- :render => { :status => 405, :text => "Must be post" },
- :add_headers => { "Allow" => "POST" }
-
-
-## 1.12.5 (August 10th, 2006) ##
-
-* Updated security fix
-
-
-## 1.12.4 (August 8th, 2006) ##
-
-* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. *Rick Olson*
-
-* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for *David Heinemeier Hansson*
-
-* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled. #1897 *jeremye@bsa.ca.gov*
-
-* Fixed that real files and symlinks should be treated the same when compiling templates. #5438 *zachary@panandscan.com*
-
-* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <m.stienstra@fngtps.com>*
-
-* Update documentation for erb trim syntax. #5651 *matt@mattmargolis.net*
-
-* Short documentation to mention use of Mime::Type.register. #5710 *choonkeat@gmail.com*
-
-
-## 1.12.3 (June 28th, 2006) ##
-
-* Fix broken traverse_to_controller. We now:
- Look for a _controller.rb file under RAILS_ROOT to load.
- If we find it, we require_dependency it and return the controller it defined. (If none was defined we stop looking.)
- If we don't find it, we look for a .rb file under RAILS_ROOT to load. If we find it, and it loads a constant we keep looking.
- Otherwise we check to see if a directory of the same name exists, and if it does we create a module for it.
-
-
-## 1.12.2 (June 27th, 2006) ##
-
-* Refinement to avoid exceptions in traverse_to_controller.
-
-* (Hackish) Fix loading of arbitrary files in Ruby's load path by traverse_to_controller. *Nicholas Seckar*
-
-
-## 1.12.1 (April 6th, 2006) ##
-
-* Fixed that template extensions would be cached development mode #4624 *Stefan Kaes*
-
-* Update to Prototype 1.5.0_rc0 *Sam Stephenson*
-
-* Honor skipping filters conditionally for only certain actions even when the parent class sets that filter to conditionally be executed only for the same actions. #4522 *Marcel Molina Jr.*
-
-* Delegate xml_http_request in integration tests to the session instance. *Jamis Buck*
-
-* Update the diagnostics template skip the useless '<controller not set>' text. *Nicholas Seckar*
-
-* CHANGED DEFAULT: Don't parse YAML input by default, but keep it available as an easy option *David Heinemeier Hansson*
-
-* Add additional autocompleter options *aballai, Thomas Fuchs*
-
-* Fixed fragment caching of binary data on Windows #4493 *bellis@deepthought.org*
-
-* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us *Sam Stephenson, Thomas Fuchs*
-
-* Added automated timestamping to AssetTagHelper methods for stylesheets, javascripts, and images when Action Controller is run under Rails *DHH*. Example:
-
- image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?1143664135" />'
-
- ...to avoid frequent stats (not a problem for most people), you can set RAILS_ASSET_ID in the ENV to avoid stats:
-
- ENV["RAILS_ASSET_ID"] = "2345"
- image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?2345" />'
-
- This can be used by deployment managers to set the asset id by application revision
-
-
-## 1.12.0 (March 27th, 2006) ##
-
-* Add documentation for respond_to. *Jamis Buck*
-
-* Fixed require of bluecloth and redcloth when gems haven't been loaded #4446 *murphy@cYcnus.de*
-
-* Update to Prototype 1.5.0_pre1 *Sam Stephenson*
-
-* Change #form_for and #fields_for so that the second argument is not required *Dave Thomas*
-
- <% form_for :post, @post, :url => { :action => 'create' } do |f| -%>
-
- becomes...
-
- <% form_for :post, :url => { :action => 'create' } do |f| -%>
-
-* Update to script.aculo.us 1.6 *Thomas Fuchs*
-
-* Enable application/x-yaml processing by default *Jamis Buck*
-
-* Fix double url escaping of remote_function. Add :escape => false option to ActionView's url_for. *Nicholas Seckar*
-
-* Add :script option to in_place_editor to support evalScripts (closes #4194) *Cody Fauser*
-
-* Fix mixed case enumerable methods in the JavaScript Collection Proxy (closes #4314) *Cody Fauser*
-
-* Undo accidental escaping for mail_to; add regression test. *Nicholas Seckar*
-
-* Added nicer message for assert_redirected_to (closes #4294) *court3nay*
-
- assert_redirected_to :action => 'other_host', :only_path => false
-
- when it was expecting...
-
- redirected_to :action => 'other_host', :only_path => true, :host => 'other.test.host'
-
- gives the error message...
-
- response is not a redirection to all of the options supplied (redirection is <{:only_path=>false, :host=>"other.test.host", :action=>"other_host"}>), difference: <{:only_path=>"true", :host=>"other.test.host"}>
-
-* Change url_for to escape the resulting URLs when called from a view. *Nicholas Seckar, coffee2code*
-
-* Added easy support for testing file uploads with fixture_file_upload #4105 *turnip@turnipspatch.com*. Example:
-
- # Looks in Test::Unit::TestCase.fixture_path + '/files/spongebob.png'
- post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
-
-* Fixed UrlHelper#current_page? to behave even when url-escaped entities are present #3929 *jeremy@planetargon.com*
-
-* Add ability for relative_url_root to be specified via an environment variable RAILS_RELATIVE_URL_ROOT. *isaac@reuben.com, Nicholas Seckar*
-
-* Fixed link_to "somewhere", :post => true to produce valid XHTML by using the parentnode instead of document.body for the instant form #3007 *Bob Silva*
-
-* Added :function option to PrototypeHelper#observe_field/observe_form that allows you to call a function instead of submitting an ajax call as the trigger #4268 *jonathan@daikini.com*
-
-* Make Mime::Type.parse consider q values (if any) *Jamis Buck*
-
-* XML-formatted requests are typecast according to "type" attributes for :xml_simple *Jamis Buck*
-
-* Added protection against proxy setups treating requests as local even when they're not #3898 *Steve Purcell*
-
-* Added TestRequest#raw_post that simulate raw_post from CgiRequest #3042 *François Beausoleil*
-
-* Underscore dasherized keys in formatted requests *Jamis Buck*
-
-* Add MimeResponds::Responder#any for managing multiple types with identical responses *Jamis Buck*
-
-* Make the xml_http_request testing method set the HTTP_ACCEPT header *Jamis Buck*
-
-* Add Verification to scaffolds. Prevent destructive actions using GET *Michael Koziarski*
-
-* Avoid hitting the filesystem when using layouts by using a File.directory? cache. *Stefan Kaes, Nicholas Seckar*
-
-* Simplify ActionController::Base#controller_path *Nicholas Seckar*
-
-* Added simple alert() notifications for RJS exceptions when config.action_view.debug_rjs = true. *Sam Stephenson*
-
-* Added :content_type option to render, so you can change the content type on the fly *DHH*. Example: render :action => "atom.rxml", :content_type => "application/atom+xml"
-
-* CHANGED DEFAULT: The default content type for .rxml is now application/xml instead of type/xml, see http://www.xml.com/pub/a/2004/07/21/dive.html for reason *David Heinemeier Hansson*
-
-* Added option to render action/template/file of a specific extension (and here by template type). This means you can have multiple templates with the same name but a different extension *DHH*. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find :all
-
- respond_to do |type|
- type.html # using defaults, which will render weblog/index.rhtml
- type.xml { render :action => "index.rxml" }
- type.js { render :action => "index.rjs" }
- end
- end
- end
-
-* Added better support for using the same actions to output for different sources depending on the Accept header *DHH*. Example:
-
- class WeblogController < ActionController::Base
- def create
- @post = Post.create(params[:post])
-
- respond_to do |type|
- type.js { render } # renders create.rjs
- type.html { redirect_to :action => "index" }
- type.xml do
- headers["Location"] = url_for(:action => "show", :id => @post)
- render(:nothing, :status => "201 Created")
- end
- end
- end
- end
-
-* Added Base#render(:xml => xml) that works just like Base#render(:text => text), but sets the content-type to text/xml and the charset to UTF-8 *David Heinemeier Hansson*
-
-* Integration test's url_for now runs in the context of the last request (if any) so after post /products/show/1 url_for :action => 'new' will yield /product/new *Tobias Lütke*
-
-* Re-added mixed-in helper methods for the JavascriptGenerator. Moved JavascriptGenerators methods to a module that is mixed in after the helpers are added. Also fixed that variables set in the enumeration methods like #collect are set correctly. Documentation added for the enumeration methods *Rick Olson*. Examples:
-
- page.select('#items li').collect('items') do |element|
- element.hide
- end
- # => var items = $$('#items li').collect(function(value, index) { return value.hide(); });
-
-* Added plugin support for parameter parsers, which allows for better support for REST web services. By default, posts submitted with the application/xml content type is handled by creating a XmlSimple hash with the same name as the root element of the submitted xml. More handlers can easily be registered like this:
-
- # Assign a new param parser to a new content type
- ActionController::Base.param_parsers['application/atom+xml'] = Proc.new do |data|
- node = REXML::Document.new(post)
- { node.root.name => node.root }
- end
-
- # Assign the default XmlSimple to a new content type
- ActionController::Base.param_parsers['application/backpack+xml'] = :xml_simple
-
- Default YAML web services were retired, ActionController::Base.param_parsers carries an example which shows how to get this functionality back. As part of this new plugin support, request.[formatted_post?, xml_post?, yaml_post? and post_format] were all deprecated in favor of request.content_type *Tobias Lütke*
-* Fixed Effect.Appear in effects.js to work with floats in Safari #3524, #3813, #3044 *Thomas Fuchs*
-
-* Fixed that default image extension was not appended when using a full URL with AssetTagHelper#image_tag #4032, #3728 *rubyonrails@beautifulpixel.com*
-
-* Added that page caching will only happen if the response code is less than 400 #4033 *g.bucher@teti.ch*
-
-* Add ActionController::IntegrationTest to allow high-level testing of the way the controllers and routes all work together *Jamis Buck*
-
-* Added support to AssetTagHelper#javascript_include_tag for having :defaults appear anywhere in the list, so you can now make one call ala javascript_include_tag(:defaults, "my_scripts") or javascript_include_tag("my_scripts", :defaults) depending on how you want the load order #3506 *Bob Silva*
-
-* Added support for visual effects scoped queues to the visual_effect helper #3530 *Abdur-Rahman Advany*
-
-* Added .rxml (and any non-rhtml template, really) supportfor CaptureHelper#content_for and CaptureHelper#capture #3287 *Brian Takita*
-
-* Added script.aculo.us drag and drop helpers to RJS *Thomas Fuchs*. Examples:
-
- page.draggable 'product-1'
- page.drop_receiving 'wastebasket', :url => { :action => 'delete' }
- page.sortable 'todolist', :url => { action => 'change_order' }
-
-* Fixed that form elements would strip the trailing [] from the first parameter #3545 *ruby@bobsilva.com*
-
-* During controller resolution, update the NameError suppression to check for the expected constant. *Nicholas Seckar*
-
-* Update script.aculo.us to V1.5.3 *Thomas Fuchs*
-
-* Added various InPlaceEditor options, #3746, #3891, #3896, #3906 *Bill Burcham, ruairi, sl33p3r*
-
-* Added :count option to pagination that'll make it possible for the ActiveRecord::Base.count call to using something else than * for the count. Especially important for count queries using DISTINCT #3839 *Stefan Kaes*
-
-* Update script.aculo.us to V1.5.2 *Thomas Fuchs*
-
-* Added element and collection proxies to RJS *DHH*. Examples:
-
- page['blank_slate'] # => $('blank_slate');
- page['blank_slate'].show # => $('blank_slate').show();
- page['blank_slate'].show('first').up # => $('blank_slate').show('first').up();
-
- page.select('p') # => $$('p');
- page.select('p.welcome b').first # => $$('p.welcome b').first();
- page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
-
-* Add JavaScriptGenerator#replace for replacing an element's "outer HTML". #3246 *tom@craz8.com, Sam Stephenson*
-
-* Remove over-engineered form_for code for a leaner implementation. *Nicholas Seckar*
-
-* Document form_for's :html option. *Nicholas Seckar*
-
-* Major components cleanup and speedup. #3527 *Stefan Kaes*
-
-* Fix problems with pagination and :include. *Kevin Clark*
-
-* Add ActiveRecordTestCase for testing AR integration. *Kevin Clark*
-
-* Add Unit Tests for pagination *Kevin Clark*
-
-* Add :html option for specifying form tag options in form_for. *Sam Stephenson*
-
-* Replace dubious controller parent class in filter docs. #3655, #3722 *info@rhalff.com, eigentone@gmail.com*
-
-* Don't interpret the :value option on text_area as an html attribute. Set the text_area's value. #3752 *gabriel@gironda.org*
-
-* Fix remote_form_for creates a non-ajax form. *Rick Olson*
-
-* Don't let arbitrary classes match as controllers -- a potentially dangerous bug. *Nicholas Seckar*
-
-* Fix Routing tests. Fix routing where failing to match a controller would prevent the rest of routes from being attempted. *Nicholas Seckar*
-
-* Add :builder => option to form_for and friends. *Nicholas Seckar, Rick Olson*
-
-* Fix controller resolution to avoid accidentally inheriting a controller from a parent module. *Nicholas Seckar*
-
-* Set sweeper's @controller to nil after a request so that the controller may be collected between requests. *Nicholas Seckar*
-
-* Subclasses of ActionController::Caching::Sweeper should be Reloadable. *Rick Olson*
-
-* Document the :xhr option for verifications. #3666 *leeo*
-
-* Added :only and :except controls to skip_before/after_filter just like for when you add filters *David Heinemeier Hansson*
-
-* Ensure that the instance variables are copied to the template when performing render :update. *Nicholas Seckar*
-
-* Add the ability to call JavaScriptGenerator methods from helpers called in update blocks. *Sam Stephenson* Example:
- module ApplicationHelper
- def update_time
- page.replace_html 'time', Time.now.to_s(:db)
- page.visual_effect :highlight, 'time'
- end
- end
-
- class UserController < ApplicationController
- def poll
- render :update { |page| page.update_time }
- end
- end
-
-* Add render(:update) to ActionView::Base. *Sam Stephenson*
-
-* Fix render(:update) to not render layouts. *Sam Stephenson*
-
-* Fixed that SSL would not correctly be detected when running lighttpd/fcgi behind lighttpd w/mod_proxy #3548 *Steve Purcell*
-
-* Added the possibility to specify atomatic expiration for the memcachd session container #3571 *Stefan Kaes*
-
-* Change layout discovery to take into account the change in semantics with File.join and nil arguments. *Marcel Molina Jr.*
-
-* Raise a RedirectBackError if redirect_to :back is called when there's no HTTP_REFERER defined #3049 *Kevin Clark*
-
-* Treat timestamps like datetimes for scaffolding purposes #3388 *Maik Schmidt*
-
-* Fix IE bug with link_to "something", :post => true #3443 *Justin Palmer*
-
-* Extract Test::Unit::TestCase test process behavior into an ActionController::TestProcess module. *Sam Stephenson*
-
-* Pass along blocks from render_to_string to render. *Sam Stephenson*
-
-* Add render :update for inline RJS. *Sam Stephenson* Example:
- class UserController < ApplicationController
- def refresh
- render :update do |page|
- page.replace_html 'user_list', :partial => 'user', :collection => @users
- page.visual_effect :highlight, 'user_list'
- end
- end
- end
-
-* allow nil objects for error_messages_for *Michael Koziarski*
-
-* Refactor human_size to exclude decimal place if it is zero. *Marcel Molina Jr.*
-
-* Update to Prototype 1.5.0_pre0 *Sam Stephenson*
-
-* Automatically discover layouts when a controller is namespaced. #2199, #3424 *me@jonnii.com rails@jeffcole.net Marcel Molina Jr.*
-
-* Add support for multiple proxy servers to CgiRequest#host *gaetanot@comcast.net*
-
-* Documentation typo fix. #2367 *Blair Zajac*
-
-* Remove Upload Progress. #2871 *Sean Treadway*
-
-* Fix typo in function name mapping in auto_complete_field. #2929 #3446 *doppler@gmail.com phil.ross@gmail.com*
-
-* Allow auto-discovery of third party template library layouts. *Marcel Molina Jr.*
-
-* Have the form builder output radio button, not check box, when calling the radio button helper. #3331 *LouisStAmour@gmail.com*
-
-* Added assignment of the Autocompleter object created by JavaScriptMacroHelper#auto_complete_field to a local javascript variables *David Heinemeier Hansson*
-
-* Added :on option for PrototypeHelper#observe_field that allows you to specify a different callback hook to have the observer trigger on *David Heinemeier Hansson*
-
-* Added JavaScriptHelper#button_to_function that works just like JavaScriptHelper#link_to_function but uses a button instead of a href *David Heinemeier Hansson*
-
-* Added that JavaScriptHelper#link_to_function will honor existing :onclick definitions when adding the function call *David Heinemeier Hansson*
-
-* Added :disable_with option to FormTagHelper#submit_tag to allow for easily disabled submit buttons with different text *David Heinemeier Hansson*
-
-* Make auto_link handle nil by returning quickly if blank? *Scott Barron*
-
-* Make auto_link match urls with a port number specified. *Marcel Molina Jr.*
-
-* Added support for toggling visual effects to ScriptaculousHelper::visual_effect, #3323. *Thomas Fuchs*
-
-* Update to script.aculo.us to 1.5.0 rev. 3343 *Thomas Fuchs*
-
-* Added :select option for JavaScriptMacroHelper#auto_complete_field that makes it easier to only use part of the auto-complete suggestion as the value for insertion *Thomas Fuchs*
-
-* Added delayed execution of Javascript from within RJS #3264 *devslashnull@gmail.com*. Example:
-
- page.delay(20) do
- page.visual_effect :fade, 'notice'
- end
-
-* Add session ID to default logging, but remove the verbose description of every step *David Heinemeier Hansson*
-
-* Add the following RJS methods: *Sam Stephenson*
-
- * alert - Displays an alert() dialog
- * redirect_to - Changes window.location.href to simulate a browser redirect
- * call - Calls a JavaScript function
- * assign - Assigns to a JavaScript variable
- * << - Inserts an arbitrary JavaScript string
-
-* Fix incorrect documentation for form_for *Nicholas Seckar*
-
-* Don't include a layout when rendering an rjs template using render's :template option. *Marcel Molina Jr.*
-
-## 1.1.2 (December 13th, 2005) ##
-
-* Become part of Rails 1.0
-
-* Update to script.aculo.us 1.5.0 final (equals 1.5.0_rc6) *Thomas Fuchs*
-
-* Update to Prototype 1.4.0 final *Sam Stephenson*
-
-* Added form_remote_for (form_for meets form_remote_tag) *David Heinemeier Hansson*
-
-* Update to script.aculo.us 1.5.0_rc6
-
-* More robust relative url root discovery for SCGI compatibility. This solves the 'SCGI routes problem' -- you no longer need to prefix all your routes with the name of the SCGI mountpoint. #3070 *Dave Ringoen*
-
-* Fix docs for text_area_tag. #3083. *Christopher Cotton*
-
-* Change form_for and fields_for method signatures to take object name and object as separate arguments rather than as a Hash. *David Heinemeier Hansson*
-
-* Introduce :selected option to the select helper. Allows you to specify a selection other than the current value of object.method. Specify :selected => nil to leave all options unselected. #2991 *Jonathan Viney <jonathan@bluewire.net.nz>*
-
-* Initialize @optional in routing code to avoid warnings about uninitialized access to an instance variable. *Nicholas Seckar*
-
-* Make ActionController's render honor the :locals option when rendering a :file. #1665. *Emanuel Borsboom, Marcel Molina Jr.*
-
-* Allow assert_tag(:conditions) to match the empty string when a tag has no children. Closes #2959. *Jamis Buck*
-
-* Update html-scanner to handle CDATA sections better. Closes #2970. *Jamis Buck*
-
-* Don't put flash in session if sessions are disabled. *Jeremy Kemper*
-
-* Strip out trailing &_= for raw post bodies. Closes #2868. *Sam Stephenson*
-
-* Pass multiple arguments to Element.show and Element.hide in JavaScriptGenerator instead of using iterators. *Sam Stephenson*
-
-* Improve expire_fragment documentation. #2966 *court3nay*
-
-* Correct docs for automatic layout assignment. #2610. *Charles M. Gerungan*
-
-* Always create new AR sessions rather than trying too hard to avoid database traffic. #2731 *Jeremy Kemper*
-
-* Update to Prototype 1.4.0_rc4. Closes #2943 (old Array.prototype.reverse behavior can be obtained by passing false as an argument). *Sam Stephenson*
-
-* Use Element.update('id', 'html') instead of $('id').innerHTML = 'html' in JavaScriptGenerator#replace_html so that script tags are evaluated. *Sam Stephenson*
-
-* Make rjs templates always implicitly skip out on layouts. *Marcel Molina Jr.*
-
-* Correct length for the truncate text helper. #2913 *Stefan Kaes*
-
-* Update to Prototype 1.4.0_rc3. Closes #1893, #2505, #2550, #2748, #2783. *Sam Stephenson*
-
-* Add support for new rjs templates which wrap an update_page block. *Marcel Molina Jr.*
-
-* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
-
-* Correct time_zone_options_for_select docs. #2892 *pudeyo@rpi.com*
-
-* Remove the unused, slow response_dump and session_dump variables from error pages. #1222 *lmarlow*
-
-* Performance tweaks: use Set instead of Array to speed up prototype helper include? calls. Avoid logging code if logger is nil. Inline commonly-called template presence checks. #2880, #2881, #2882, #2883 *Stefan Kaes*
-
-* MemCache store may be given multiple addresses. #2869 *Ryan Carver <ryan@fivesevensix.com>*
-
-* Handle cookie parsing irregularity for certain Nokia phones. #2530 *zaitzow@gmail.com*
-
-* Added PrototypeHelper::JavaScriptGenerator and PrototypeHelper#update_page for easily modifying multiple elements in an Ajax response. *Sam Stephenson* Example:
-
- update_page do |page|
- page.insert_html :bottom, 'list', '<li>Last item</li>'
- page.visual_effect :highlight, 'list'
- page.hide 'status-indicator', 'cancel-link'
- end
-
- generates the following JavaScript:
-
- new Insertion.Bottom("list", "<li>Last item</li>");
- new Effect.Highlight("list");
- ["status-indicator", "cancel-link"].each(Element.hide);
-
-* Refactored JavaScriptHelper into PrototypeHelper and ScriptaculousHelper *Sam Stephenson*
-
-* Update to latest script.aculo.us version (as of [3031])
-
-* Updated docs for in_place_editor, fixes a couple bugs and offers extended support for external controls *Justin Palmer*
-
-* Update documentation for render :file. #2858 *Tom Werner*
-
-* Only include builtin filters whose filenames match /^[a-z][a-z_]*_helper.rb$/ to avoid including operating system metadata such as ._foo_helper.rb. #2855 *court3nay*
-
-* Added FormHelper#form_for and FormHelper#fields_for that makes it easier to work with forms for single objects also if they don't reside in instance variables *DHH*. Examples:
-
- <% form_for :person, @person, :url => { :action => "update" } do |f| %>
- First name: <%= f.text_field :first_name %>
- Last name : <%= f.text_field :last_name %>
- Biography : <%= f.text_area :biography %>
- Admin? : <%= f.check_box :admin %>
- <% end %>
-
- <% form_for :person, person, :url => { :action => "update" } do |person_form| %>
- First name: <%= person_form.text_field :first_name %>
- Last name : <%= person_form.text_field :last_name %>
-
- <% fields_for :permission => person.permission do |permission_fields| %>
- Admin? : <%= permission_fields.check_box :admin %>
- <% end %>
- <% end %>
-
-* options_for_select allows any objects which respond_to? :first and :last rather than restricting to Array and Range. #2824 *Jacob Robbins <jrobbins@cmj.com>, Jeremy Kemper*
-
-* The auto_link text helper accepts an optional block to format the link text for each url and email address. Example: auto_link(post.body) { |text| truncate(text, 10) } *Jeremy Kemper*
-
-* assert_tag uses exact matches for string conditions, instead of partial matches. Use regex to do partial matches. #2799 *Jamis Buck*
-
-* CGI::Session::ActiveRecordStore.data_column_name = 'foobar' to use a different session data column than the 'data' default. *nbpwie102@sneakemail.com*
-
-* Do not raise an exception when default helper is missing; log a debug message instead. It's nice to delete empty helpers. *Jeremy Kemper*
-
-* Controllers with acronyms in their names (e.g. PDFController) require the correct default helper (PDFHelper in file pdf_helper.rb). #2262 *jeff@opendbms.com*
-
-
-## 1.11.0 (November 7th, 2005) ##
-
-* Added request as instance method to views, so you can do <%= request.env["HTTP_REFERER"] %>, just like you can already access response, session, and the likes *David Heinemeier Hansson*
-
-* Fix conflict with assert_tag and Glue gem #2255 *david.felstead@gmail.com*
-
-* Add documentation to assert_tag indicating that it only works with well-formed XHTML #1937, #2570 *Jamis Buck*
-
-* Added action_pack.rb stub so that ActionPack::Version loads properly *Sam Stephenson*
-
-* Added short-hand to assert_tag so assert_tag :tag => "span" can be written as assert_tag "span" *David Heinemeier Hansson*
-
-* Added skip_before_filter/skip_after_filter for easier control of the filter chain in inheritance hierachies *DHH*. Example:
-
- class ApplicationController < ActionController::Base
- before_filter :authenticate
- end
-
- class WeblogController < ApplicationController
- # will run the :authenticate filter
- end
-
- class SignupController < ActionController::Base
- # will not run the :authenticate filter
- skip_before_filter :authenticate
- end
-
-* Added redirect_to :back as a short-hand for redirect_to(request.env["HTTP_REFERER"]) *David Heinemeier Hansson*
-
-* Change javascript_include_tag :defaults to not use script.aculo.us loader, which facilitates the use of plugins for future script.aculo.us and third party javascript extensions, and provide register_javascript_include_default for plugins to specify additional JavaScript files to load. Removed slider.js and builder.js from actionpack. *Thomas Fuchs*
-
-* Fix problem where redirecting components can cause an infinite loop *Rick Olson*
-
-* Added support for the queue option on visual_effect *Thomas Fuchs*
-
-* Update script.aculo.us to V1.5_rc4 *Thomas Fuchs*
-
-* Fix that render :text didn't interpolate instance variables #2629, #2626 *Stefan Kaes*
-
-* Fix line number detection and escape RAILS_ROOT in backtrace Regexp *Nicholas Seckar*
-
-* Fixed document.getElementsByClassName from Prototype to be speedy again *Sam Stephenson*
-
-* Recognize ./#{RAILS_ROOT} as RAILS_ROOT in error traces *Nicholas Seckar*
-
-* Remove ARStore session fingerprinting *Nicholas Seckar*
-
-* Fix obscure bug in ARStore *Nicholas Seckar*
-
-* Added TextHelper#strip_tags for removing HTML tags from a string (using HTMLTokenizer) #2229 *marcin@junkheap.net*
-
-* Added a reader for flash.now, so it's possible to do stuff like flash.now[:alert] ||= 'New if not set' #2422 *Caio Chassot*
-
-
-## 1.10.2 (October 26th, 2005) ##
-
-* Reset template variables after using render_to_string *Stefan Kaes*
-
-* Expose the session model backing CGI::Session
-
-* Abbreviate RAILS_ROOT in traces
-
-
-## 1.10.1 (October 19th, 2005) ##
-
-* Update error trace templates *Nicholas Seckar*
-
-* Stop showing generated routing code in application traces *Nicholas Seckar*
-
-
-## 1.10.0 (October 16th, 2005) ##
-
-* Make string-keys locals assigns optional. Add documentation describing depreciated state *Stefan Kaes*
-
-* Improve line number detection for template errors *Nicholas Seckar*
-
-* Update/clean up documentation (rdoc)
-
-* Upgrade to Prototype 1.4.0_rc0 *Sam Stephenson*
-
-* Added assert_vaild. Reports the proper AR error messages as fail message when the passed record is invalid *Tobias Lütke*
-
-* Add temporary support for passing locals to render using string keys *Nicholas Seckar*
-
-* Clean up error pages by providing better backtraces *Nicholas Seckar*
-
-* Raise an exception if an attempt is made to insert more session data into the ActiveRecordStore data column than the column can hold. #2234. *justin@textdrive.com*
-
-* Removed references to assertions.rb from actionpack assert's backtraces. Makes error reports in functional unit tests much less noisy. *Tobias Lütke*
-
-* Updated and clarified documentation for JavaScriptHelper to be more concise about the various options for including the JavaScript libs. *Thomas Fuchs*
-
-* Hide "Retry with Breakpoint" button on error pages until feature is functional. *David Heinemeier Hansson*
-
-* Fix Request#host_with_port to use the standard port when Rails is behind a proxy. *Nicholas Seckar*
-
-* Escape query strings in the href attribute of URLs created by url_helper. #2333 *Michael Schuerig <michael@schuerig.de>*
-
-* Improved line number reporting for template errors *Nicholas Seckar*
-
-* Added :locals support for render :inline #2463 *mdabney@cavoksolutions.com*
-
-* Unset the X-Requested-With header when using the xhr wrapper in functional tests so that future requests aren't accidentally xhr'ed #2352 *me@julik.nl, Sam Stephenson*
-
-* Unescape paths before writing cache to file system. #1877. *Damien Pollet*
-
-* Wrap javascript_tag contents in a CDATA section and add a cdata_section method to TagHelper #1691 *Michael Schuerig, Sam Stephenson*
-
-* Misc doc fixes (typos/grammar/etc). #2445. *coffee2code*
-
-* Speed improvement for session_options. #2287. *Stefan Kaes*
-
-* Make cacheing binary files friendly with Windows. #1975. *Rich Olson*
-
-* Convert boolean form options form the tag_helper. #809. *Michael Schuerig <michael@schuerig.de>*
-
-* Fixed that an instance variable with the same name as a partial should be implicitly passed as the partial :object #2269 *court3nay*
-
-* Update Prototype to V1.4.0_pre11, script.aculo.us to [2502] *Thomas Fuchs*
-
-* Make assert_tag :children count appropriately. Closes #2181. *jamie@bravenet.com*
-
-* Forced newer versions of RedCloth to use hard breaks *David Heinemeier Hansson*
-
-* Added new scriptaculous options for auto_complete_field #2343 *Manfred Stienstra*
-
-* Don't prepend the asset host if the string is already a fully-qualified URL
-
-* Updated to script.aculo.us V1.5.0_rc2 and Prototype to V1.4.0_pre7 *Thomas Fuchs*
-
-* Undo condition change made in [2345] to prevent normal parameters arriving as StringIO.
-
-* Tolerate consecutive delimiters in query parameters. #2295 *darashi@gmail.com*
-
-* Streamline render process, code cleaning. Closes #2294. *skae*
-
-* Keep flash after components are rendered. #2291 *Rick Olson, Scott*
-
-* Shorten IE file upload path to filename only to match other browsers. #1507 *court3nay*
-
-* Fix open/save dialog in IE not opening files send with send_file/send_data, #2279 *Thomas Fuchs*
-
-* Fixed that auto_discovery_link_tag couldn't take a string as the URL *David Heinemeier Hansson*
-
-* Fixed problem with send_file and WEBrick using stdout #1812 *David Heinemeier Hansson*
-
-* Optimized tag_options to not sort keys, which is no longer necessary when assert_dom_equal and friend is available #1995 *skae*
-
-* Added assert_dom_equal and assert_dom_not_equal to compare tags generated by the helpers in an order-indifferent manner #1995 *skae*
-
-* Fixed that Request#domain caused an exception if the domain header wasn't set in the original http request #1795 *Michael Koziarski*
-
-* Make the truncate() helper multi-byte safe (assuming $KCODE has been set to something other than "NONE") #2103
-
-* Add routing tests from #1945 *ben@groovie.org*
-
-* Add a routing test case covering #2101 *Nicholas Seckar*
-
-* Cache relative_url_root for all webservers, not just Apache #2193 *skae*
-
-* Speed up cookie use by decreasing string copying #2194 *skae*
-
-* Fixed access to "Host" header with requests made by crappy old HTTP/1.0 clients #2124 *Marcel Molina Jr.*
-
-* Added easy assignment of fragment cache store through use of symbols for included stores (old way still works too)
-
- Before:
- ActionController::Base.fragment_cache_store =
- ActionController::Base::Caching::Fragments::FileStore.new("/path/to/cache/directory")
-
- After:
- ActionController::Base.fragment_cache_store = :file_store, "/path/to/cache/directory"
-
-* Added ActionController::Base.session_store=, session_store, and session_options to make it easier to tweak the session options (instead of going straight to ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS)
-
-* Added TextHelper#cycle to cycle over an array of values on each hit (useful for alternating row colors etc) #2154 *dave-ml@dribin.org*
-
-* Ensure that request.path never returns nil. Closes #1675 *Nicholas Seckar*
-
-* Add ability to specify Route Regexps for controllers. Closes #1917. *Sebastian Kanthak*
-
-* Provide Named Route's hash methods as helper methods. Closes #1744. *Nicholas Seckar, Steve Purcell*
-
-* Added :multipart option to ActiveRecordHelper#form to make it possible to add file input fields #2034 *jstirk@oobleyboo.com*
-
-* Moved auto-completion and in-place editing into the Macros module and their helper counterparts into JavaScriptMacrosHelper
-
-* Added in-place editing support in the spirit of auto complete with ActionController::Base.in_place_edit_for, JavascriptHelper#in_place_editor_field, and Javascript support from script.aculo.us #2038 *Jon Tirsen*
-
-* Added :disabled option to all data selects that'll make the elements inaccessible for change #2167, #253 *eigentone*
-
-* Fixed that TextHelper#auto_link_urls would include punctuation in the links #2166, #1671 *eigentone*
-
-* Fixed that number_to_currency(1000, {:precision => 0})) should return "$1,000", instead of "$1,000." #2122 *sd@notso.net*
-
-* Allow link_to_remote to use any DOM-element as the parent of the form elements to be submitted #2137 *erik@ruby-lang.nl*. Example:
-
- <tr id="row023">
- <td><input name="foo"/></td>
- <td><input name="bar"/></td>
- <td><%= link_to_remote 'Save', :update => "row023",
- :submit => "row023", :url => {:action => 'save_row'} %></td>
- </tr>
-
-* Fixed that render :partial would fail when :object was a Hash (due to backwards compatibility issues) #2148 *Sam Stephenson*
-
-* Fixed JavascriptHelper#auto_complete_for to only include unique items #2153 *Thomas Fuchs*
-
-* Fixed all AssetHelper methods to work with relative paths, such that javascript_include_tag('stdlib/standard') will look in /javascripts/stdlib/standard instead of '/stdlib/standard/' #1963
-
-* Avoid extending view instance with helper modules each request. Closes #1979
-
-* Performance improvements to CGI methods. Closes #1980 *Stefan Kaes*
-
-* Added :post option to UrlHelper#link_to that makes it possible to do POST requests through normal ahref links using Javascript
-
-* Fixed overwrite_params
-
-* Added ActionController::Base.benchmark and ActionController::Base.silence to allow for easy benchmarking and turning off the log
-
-* Updated vendor copy of html-scanner to support better xml parsing
-
-* Added :popup option to UrlHelper#link_to #1996 *gabriel.gironda@gmail.com*. Examples:
-
- link_to "Help", { :action => "help" }, :popup => true
- link_to "Busy loop", { :action => "busy" }, :popup => ['new_window', 'height=300,width=600']
-
-* Drop trailing \000 if present on RAW_POST_DATA (works around bug in Safari Ajax implementation) #918
-
-* Fix observe_field to fall back to event-based observation if frequency <= 0 #1916 *Michael Schubert*
-
-* Allow use of the :with option for submit_to_remote #1936 *jon@instance-design.co.uk*
-
-* AbstractRequest#domain returns nil when host is an ip address #2012 *Kevin Clark*
-
-* ActionController documentation update #2051 *François Beausoleil*
-
-* Yield @content_for_ variables to templates #2058 *Sam Stephenson*
-
-* Make rendering an empty partial collection behave like :nothing => true #2080 *Sam Stephenson*
-
-* Add option to specify the singular name used by pagination.
-
-* Use string key to obtain action value. Allows indifferent hashes to be disabled.
-
-* Added ActionView::Base.cache_template_loading back.
-
-* Rewrote compiled templates to decrease code complexity. Removed template load caching in favour of compiled caching. Fixed template error messages. *Nicholas Seckar*
-
-* Fix Routing to handle :some_param => nil better. *Nicholas Seckar, Luminas*
-
-* Add support for :include with pagination (subject to existing constraints for :include with :limit and :offset) #1478 *Michael Schubert*
-
-* Prevent the benchmark module from blowing up if a non-HTTP/1.1 request is processed
-
-* Added :use_short_month option to select_month helper to show month names as abbreviations
-
-* Make link_to escape the javascript in the confirm option #1964 *nicolas.pouillard@gmail.com*
-
-* Make assert_redirected_to properly check URL's passed as strings #1910 *Scott Barron*
-
-* Make sure :layout => false is always used when rendering inside a layout
-
-* Use raise instead of assert_not_nil in Test::Unit::TestCase#process to ensure that the test variables (controller, request, response) have been set
-
-* Make sure assigns are built for every request when testing #1866
-
-* Allow remote_addr to be queried on TestRequest #1668
-
-* Fixed bug when a partial render was passing a local with the same name as the partial
-
-* Improved performance of test app req/sec with ~10% refactoring the render method #1823 *Stefan Kaes*
-
-* Improved performance of test app req/sec with 5-30% through a series of Action Pack optimizations #1811 *Stefan Kaes*
-
-* Changed caching/expiration/hit to report using the DEBUG log level and errors to use the ERROR log level instead of both using INFO
-
-* Added support for per-action session management #1763
-
-* Improved rendering speed on complicated templates by up to 100% (the more complex the templates, the higher the speedup) #1234 *Stefan Kaes*. This did necessasitate a change to the internals of ActionView#render_template that now has four parameters. Developers of custom view handlers (like Amrita) need to update for that.
-
-* Added options hash as third argument to FormHelper#input, so you can do input('person', 'zip', :size=>10) #1719 *jeremye@bsa.ca.gov*
-
-* Added Base#expires_in(seconds)/Base#expires_now to control HTTP content cache headers #1755 *Thomas Fuchs*
-
-* Fixed line number reporting for Builder template errors #1753 *piotr*
-
-* Fixed assert_routing so that testing controllers in modules works as expected *Nicholas Seckar, Rick Olson*
-
-* Fixed bug with :success/:failure callbacks for the JavaScriptHelper methods #1730 *court3nay/Thomas Fuchs*
-
-* Added named_route method to RouteSet instances so that RouteSet instance methods do not prevent certain names from being used. *Nicholas Seckar*
-
-* Fixed routes so that routes which do not specify :action in the path or in the requirements have a default of :action => 'index', In addition, fixed url generation so that :action => 'index' does not need to be provided for such urls. *Nicholas Seckar, Markjuh*
-
-* Worked around a Safari bug where it wouldn't pass headers through if the response was zero length by having render :nothing return ' ' instead of ''
-
-* Fixed Request#subdomains to handle "foo.foo.com" correctly
-
-
-## 1.9.1 (11 July, 2005) ##
-
-* Fixed that auto_complete_for didn't force the input string to lower case even as the db comparison was
-
-* Fixed that Action View should always use the included Builder, never attempt to require the gem, to ensure compatibility
-
-* Added that nil options are not included in tags, so tag("p", :ignore => nil) now returns <p /> not <p ignore="" /> but that tag("p", :ignore => "") still includes it #1465 *Michael Schuerig*
-
-* Fixed that UrlHelper#link_to_unless/link_to_if used html_escape on the name if no link was to be applied. This is unnecessary and breaks its use with images #1649 *joergd@pobox.com*
-
-* Improved error message for DoubleRenderError
-
-* Fixed routing to allow for testing of *path components #1650 *Nicholas Seckar*
-
-* Added :handle as an option to sortable_element to restrict the drag handle to a given class #1642 *thejohnny*
-
-* Added a bunch of script.aculo.us features #1644, #1677, #1695 *Thomas Fuchs*
- * Effect.ScrollTo, to smoothly scroll the page to an element
- * Better Firefox flickering handling on SlideUp/SlideDown
- * Removed a possible memory leak in IE with draggables
- * Added support for cancelling dragging my hitting ESC
- * Added capability to remove draggables/droppables and redeclare sortables in dragdrop.js (this makes it possible to call sortable_element on the same element more than once, e.g. in AJAX returns that modify the sortable element. all current sortable 'stuff' on the element will be discarded and the sortable will be rebuilt)
- * Always reset background color on Effect.Highlight; this make change backwards-compatibility, to be sure include style="background-color:(target-color)" on your elements or else elements will fall back to their CSS rules (which is a good thing in most circumstances)
- * Removed circular references from element to prevent memory leaks (still not completely gone in IE)
- * Changes to class extension in effects.js
- * Make Effect.Highlight restore any previously set background color when finishing (makes effect work with CSS classes that set a background color)
- * Fixed myriads of memory leaks in IE and Gecko-based browsers *David Zülke*
- * Added incremental and local autocompleting and loads of documentation to controls.js *Ivan Krstic*
- * Extended the auto_complete_field helper to accept tokens option
- * Changed object extension mechanism to favor Object.extend to make script.aculo.us easily adaptable to support 3rd party libs like IE7.js *David Zülke*
-
-* Fixed that named routes didn't use the default values for action and possible other parameters #1534 *Nicholas Seckar*
-
-* Fixed JavascriptHelper#visual_effect to use camelize such that :blind_up will work #1639 *pelletierm@eastmedia.net*
-
-* Fixed that a SessionRestoreError was thrown if a model object was placed in the session that wasn't available to all controllers. This means that it's no longer necessary to use the 'model :post' work-around in ApplicationController to have a Post model in your session.
-
-
-## 1.9.0 (6 July, 2005) ##
-
-* Added logging of the request URI in the benchmark statement (makes it easy to grep for slow actions)
-
-* Added javascript_include_tag :defaults shortcut that'll include all the default javascripts included with Action Pack (prototype, effects, controls, dragdrop)
-
-* Cache several controller variables that are expensive to calculate #1229 *Stefan Kaes*
-
-* The session class backing CGI::Session::ActiveRecordStore may be replaced with any class that duck-types with a subset of Active Record. See docs for details #1238 *Stefan Kaes*
-
-* Fixed that hashes was not working properly when passed by GET to lighttpd #849 *Nicholas Seckar*
-
-* Fixed assert_template nil will be true when no template was rendered #1565 *maceywj@telus.net*
-
-* Added :prompt option to FormOptions#select (and the users of it, like FormOptions#select_country etc) to create "Please select" style descriptors #1181 *Michael Schuerig*
-
-* Added JavascriptHelper#update_element_function, which returns a Javascript function (or expression) that'll update a DOM element according to the options passed #933 *mortonda@dgrmm.net*. Examples:
-
- <%= update_element_function("products", :action => :insert, :position => :bottom, :content => "<p>New product!</p>") %>
-
- <% update_element_function("products", :action => :replace, :binding => binding) do %>
- <p>Product 1</p>
- <p>Product 2</p>
- <% end %>
-
-* Added :field_name option to DateHelper#select_(year|month|day) to deviate from the year/month/day defaults #1266 *Marcel Molina Jr.*
-
-* Added JavascriptHelper#draggable_element and JavascriptHelper#drop_receiving_element to facilitate easy dragging and dropping through the script.aculo.us libraries #1578 *Thomas Fuchs*
-
-* Added that UrlHelper#mail_to will now also encode the default link title #749 *f.svehla@gmail.com*
-
-* Removed the default option of wrap=virtual on FormHelper#text_area to ensure XHTML compatibility #1300 *thomas@columbus.rr.com*
-
-* Adds the ability to include XML CDATA tags using Builder #1563 *Josh Knowles*. Example:
-
- xml.cdata! "some text" # => <![CDATA[some text]]>
-
-* Added evaluation of SCRIPT blocks in content returned to Ajax calls #1577 *Thomas Fuchs/court3nay/Sean Treadway*
-
-* Directly generate paths with a leading slash instead of tacking it on later. #1543 *Nicholas Seckar*
-
-* Fixed errant parameter modification in functional tests. #1542 *Nicholas Seckar*
-
-* Routes fail with leading slash #1540 *Nicholas Seckar*
-
-* Added support for graceful error handling of Ajax calls #1217 *Jamis Buck/Thomas Fuchs*. Example:
-
- link_to_remote(
- "test",
- :url => { :action => "faulty" },
- :update => { :success => "good", :failure => "bad" },
- 403 => "alert('Forbidden- got ya!')",
- 404 => "alert('Nothing there...?')",
- :failure => "alert('Unkown error ' + request.status)")
-
-* Attempt to explicitly flush the output at the end of CgiProcess#out
-
-* Fixed assert_redirected_to to handle absolute controller paths properly #1472 *Rick Olson/Nicholas Seckar*
-
-* Added event-based observations when frequency is not set on observe_field/form #1474 *flash@vanklinkenbergsoftware.nl*
-
-* Added script.aculo.us Javascripts (controls.js, dragdrop.js, effects.js) (NEEDS MORE DESCRIPTION) #1509 *Thomas Fuchs*
-
-* Fixed prototype to consider all fields it doesn't know as text (such as Safari's search) just like the browser in its serialization #1497 *Sean Treadway*
-
-* Improved performance of Routes generation by a factor of 5 #1434 *Nicholas Seckar*
-
-* Added named routes (NEEDS BETTER DESCRIPTION) #1434 *Nicholas Seckar*
-
-* Improved AbstractRequest documentation #1483 *court3nay*
-
-* Added ActionController::Base.allow_concurrency to control whether the application is thread-safe, so multi-threaded servers like WEBrick knows whether to apply a mutex around the performance of each action. Turned off by default. EXPERIMENTAL FEATURE.
-
-* Added TextHelper#word_wrap(text, line_length = 80) #1449 *tuxie@dekadance.se*
-
-* Added a fall-through action for form_remote_tag that'll be used in case Javascript is unavailable #1459 *Scott Barron*. Example:
-
- form_remote_tag :html => { :action => url_for(:controller => "some", :action => "place") }
-
-* Added :xhr => true/false option to verify so you can ensure that a request is coming from an Ajax call or not #1464 *Thomas Fuchs*
-
-* Added tag_options as a third parameter to AssetHelper#auto_discovery_link_tag to control options like the title of the link #1430 *Kevin Clark*
-
-* Added option to pass in parameters to CaptureHelper#capture, so you can create more advanced view helper methods #1466 *duane.johnson@gmail.com*. Example:
-
- <% show_calendar(:year => 2005, :month => 6) do |day, options| %>
- <% options[:bgcolor] = '#dfd' if 10..15.include? day %>
- [<%= day %>]
- <% end %>
-
-* Changed the default name of the input tag generated by FormTagHelper#submit_tag from "submit" to "commit" so it doesn't clash with form.submit() calls in Javascript #1271
-
-* Fixed relative urls support for lighttpd #1048 *Nicholas Seckar/maznawak@nerim.net*
-
-* Correct distance_of_time_in_words for integer arguments and make the second arg optional, treating the first arg as a duration in seconds. #1458 *madrobby <thomas@fesch.at>*
-
-* Fixed query parser to deal gracefully with equal signs inside keys and values #1345 *gorou*.
- Example: /?sig=abcdef=:foobar=&x=y will pass now.
-
-* Added Cuba to country list #1351 *todd*
-
-* Fixed radio_button to work with numeric values #1352 *demetrius*
-
-* Added :extension option to NumberHelper#number_to_phone #1361 *delynnb*
-
-* Added button_to as a form-based solution to deal with harmful actions that should be hidden behind POSTs. This makes it just as easy as link_to to create a safe trigger for actions like destroy, although it's limited by being a block element, the fixed look, and a no-no inside other forms. #1371 *tom@moertel.com*
-
-* Fixed image_tag so an exception is not thrown just because the image is missing and alt value can't be generated #1395 *Marcel Molina Jr.*
-
-* Added a third parameter to TextHelper#auto_link called href_options for specifying additional tag options on the links generated #1401 *tyler.kovacs@gmail.com*. Example: auto_link(text, :all, { :target => "_blank" }) to have all the generated links open in a new window.
-
-* Fixed TextHelper#highlight to return the text, not nil, if the phrase is blank #1409 *Patrick Lenz*
-
-* Fixed TagHelper such that :name and 'name' keys in the options doesn't result in two attributes #1455 *take_tk*
-
-* Ensure that helpers are only available to the controllers where they are defined and their subclasses. #1394 *kdole@tamu.edu*
-
-* render("foo/bar") works with a layout again
-
-* Fixed double-singularization on scaffolded pagination call (Address would be turned into Addres) #1216, #1404 *nilsga*
-
-* Removed the require hack used by functional testing to work around an earlier bug in rake.
-
-* Allow distance_of_time_in_words to work with any value that responds to #to_time (like dates) #969
-
-* Support :render option for :verify #1440 *Tobias Lütke*
-
-* Updated vendor copy of html-scanner lib to 0.5.2, for bug fixes and optimizations. The :content option may be used as expected--to find a tag whose textual content is a particular value--in assert_tag, now.
-
-* Changed test requests to come from 0.0.0.0 instead of 127.0.0.1 such that they don't trigger debugging screens on exceptions, but instead call rescue_action_in_public
-
-* Modernize scaffolding to match the generator: use the new render method and change style from the warty @params["id"] to the sleek params[:id]. #1367
-
-* Include :id in the action generated by the form helper method. Then, for example, the controller can do Model.find(params[:id]) for both edit and update actions. Updated scaffolding to take advantage. #1367
-
-* Add assertions with friendly messages to TestCase#process to ensure that @controller, @request, and @response are set. #1367
-
-* Arrays, hashes sent via multipart posts are converted to strings #1032 *dj@omelia.org, me@julik.nl*
-
-* render(:layout => true) is a synonym for render(:layout => nil)
-
-* Make sure the benchmarking render method always returns the output of the render.
-
-* render(:action), render(:template) and render() are the only three calls that default to using a layout. All other render calls assume :layout => false. This also fixes send_file, which was applying a layout if one existed for the current action.
-
-* verify with :redirect_to won't redirect if a redirect or render has already been performed #1350
-
-* render(:partial => true) is identical to the behavior of the deprecated render_partial()
-
-* Fixed render(:partial => "...") to use an empty Hash for the local assigns #1365
-
-* Fixed Caching::Fragments::FileStore.delete to not raise an exception if the delete fails.
-
-* Deprecated all render_* methods in favor of consolidating all rendering behavior in Base#render(options). This enables more natural use of combining options, such as layouts. Examples:
-
- +---------------------------------------------------------------+-------------------------------------------------------+
- | BEFORE | AFTER |
- +---------------------------------------------------------------+-------------------------------------------------------+
- | render_with_layout "weblog/show", "200 OK", "layouts/dialog" | render :action => "show", :layout => "dialog" |
- | render_without_layout "weblog/show" | render :action => "show", :layout => false |
- | render_action "error", "404 Not Found" | render :action => "error", :status => "404 Not Found" |
- | render_template "xml.div('stuff')", "200 OK", :rxml | render :inline => "xml.div('stuff')", :type => :rxml |
- | render_text "hello world!" | render :text => "hello world!" |
- | render_partial_collection "person", @people, nil, :a => 1 | render :partial => "person", :collection => @people, |
- | | :locals => { :a => 1 } |
- +---------------------------------------------------------------+-------------------------------------------------------+
-
-* Deprecated redirect_to_path and redirect_to_url in favor of letting redirect_to do the right thing when passed either a path or url.
-
-* Fixed use of an integer as return code for renders, so render_text "hello world", 404 now works #1327
-
-* Fixed assert_redirect_to to work with redirect_to_path #869 *Nicholas Seckar*
-
-* Fixed escaping of :method option in remote_form_tag #1218 *Rick Olson*
-
-* Added Serbia and Montenegro to the country_select #1239 *todd@robotcoop.com*
-
-* Fixed Request#remote_ip in testing #1251 *Jeremy Kemper*
-
-* Fixed that compute_public_path should recognize external URLs, so image_tag("http://www.example.com/images/icon.gif") is not prefixed with the relative url path #1254 *victor-ronr-trac@carotena.net*
-
-* Added support for descending year values in DateHelper#select_year, like select_year(Date.today, :start_year => 2005, :end_year => 1900), which would count down from 2005 to 1900 instead of the other way #1274 *nwoods@mail.com*
-
-* Fixed that FormHelper#checkbox should return a checked checkbox if the value is the same as checked_value #1286 *Florian Weber*
-
-* Fixed Form.disable in Prototype #1317 *Wintermute*
-
-* Added accessors to logger, params, response, session, flash, and headers from the view, so you can write <% logger.info "stuff" %> instead of <% @logger.info "others" %> -- more consistent with the preferred way of accessing these attributes and collections from the controller
-
-* Added support for POST data in form of YAML or XML, which is controller through the Content-Type header. Example request:
-
- Content-Type: application/xml
- <request><item><content>HelloWorld</content></item></request>
-
- ...is the same as:
-
- Content-Type: application/x-yaml
- ---
- item:
- content: HelloWorld
-
- ...is the same as:
-
- item[content]=HelloWorld
-
- Which in the end turns into { "item" => { "content" => "HelloWorld" } }. This makes it a lot easier to publish REST web services on top of your regular actions (as they won't care).
-
- Example Curl call:
-
- curl -H 'Content-Type: application/xml' -d '<request><item><content>KillMeMore</content></item></request>' http://www.example.com/service
-
- You can query to find out whether a given request came through as one of these types with:
- - request.post_format? (:url_encoded, :xml or :yaml)
- - request.formatted_post? (for either xml or yaml)
- - request.xml_post?
- - request.yaml_post?
-
-* Added bundling of XmlSimple by Maik Schmidt
-
-* Fixed that render_partial_collection should always return a string (and not sometimes an array, despite <%= %> not caring)
-
-* Added TextHelper#sanitize that can will remove any Javascript handlers, blocks, and forms from an input of HTML. This allows for use of HTML on public sites, but still be free of XSS issues. #1277 *Jamis Buck*
-
-* Fixed the HTML scanner used by assert_tag where a infinite loop could be caused by a stray less-than sign in the input #1270 *Jamis Buck*
-
-* Added functionality to assert_tag, so you can now do tests on the siblings of a node, to assert that some element comes before or after the element in question, or just to assert that some element exists as a sibling #1226 *Jamis Buck*
-
-* Added better error handling for regexp caching expiration
-
-* Fixed handling of requests coming from unknown HTTP methods not to kill the server
-
-* Added that both AssetHelper#stylesheet_link_tag and AssetHelper#javascript_include_tag now accept an option hash as the last parameter, so you can do stuff like: stylesheet_link_tag "style", :media => "all"
-
-* Added FormTagHelper#image_submit_tag for making submit buttons that uses images
-
-* Added ActionController::Base.asset_host that will then be used by all the asset helpers. This enables you to easily offload static content like javascripts and images to a separate server tuned just for that.
-
-* Fixed action/fragment caching using the filestore when a directory and a file wanted to use the same name. Now there's a .cache prefix that sidesteps the conflict #1188 *imbcmdth@hotmail.com*
-
-* Fixed missing id uniqueness in FormTag#radio_button #1207 *Jarkko Laine*
-
-* Fixed assert_redirected_to to work with :only_path => false #1204 *Alisdair McDiarmid*
-
-* Fixed render_partial_collection to output an empty string instead of nil when handed an empty array #1202 *Ryan Carver*
-
-* Improved the speed of regular expression expirations for caching by a factor of 10 #1221 *Jamis Buck*
-
-* Removed dumping of template assigns on the rescue page as it would very easily include a ton of data making page loads take seconds (and the information was rarely helpful) #1222
-
-* Added BenchmarkHelper that can measure the execution time of a block in a template and reports the result to the log. Example:
-
- <% benchmark "Notes section" do %>
- <%= expensive_notes_operation %>
- <% end %>
-
- Will add something like "Notes section (0.345234)" to the log.
-
-* Added ActionController::Caching::Sweeper as an improved an easier to use sweeper. The new sweepers work on a single-step approach instead of two-steps like the old ones. Before
-
- def after_save(record)
- @list = record.is_a?(List) ? record : record.list
- end
-
- def filter(controller)
- controller.expire_page(:controller => "lists", :action => %w( show public feed ), :id => @list.id)
- controller.expire_action(:controller => "lists", :action => "all")
- @list.shares.each { |share| controller.expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
- end
-
- ..after:
-
- def after_save(record)
- list = record.is_a?(List) ? record : record.list
- expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
- expire_action(:controller => "lists", :action => "all")
- list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
- end
-
- The new sweepers can also observe on the actions themselves by implementing methods according to (before|after)_$controller_$action. Example of a callback that'll be called after PagesController#update_title has been performed:
-
- def after_pages_update_title
- expire_fragment(%r{pages/#{controller.assigns["page"].id}/.*})
- end
-
- Note that missing_method is delegated to the controller instance, which is assigned in a before filter. This means that you can call expire_fragment instead of @controller.expire_fragment.
-
-* Added that Fragments#expire_fragment now accepts as a regular expression as the name thereby deprecating expire_matched_fragments
-
-* Fixed that fragments shouldn't use the current host and the path as part of the key like pages does
-
-* Added conditions to around_filters just like before_filter and after_filter
-
-
-## 1.8.1 (20th April, 2005) ##
-
-* Added xml_http_request/xhr method for simulating XMLHttpRequest in functional tests #1151 *Sam Stephenson*. Example:
-
- xhr :post, :index
-
-* Fixed that Ajax.Base.options.asynchronous wasn't being respected in Ajax.Request (thanks Jon Casey)
-
-* Fixed that :get, :post, and the others should take a flash array as the third argument just like process #1144 *rails@cogentdude.com*
-
-* Fixed a problem with Flash.now
-
-* Fixed stringification on all assigned hashes. The sacrifice is that assigns[:person] won't work in testing. Instead assigns["person"] or assigns(:person) must be used. In other words, the keys of assigns stay strings but we've added a method-based accessor to appease the need for symbols.
-
-* Fixed that rendering a template would require a connection to the database #1146
-
-
-## 1.8.0 (19th April, 2005) ##
-
-* Added assert_tag and assert_no_tag as a much improved alternative to the deprecated assert_template_xpath_match #1126 *Jamis Buck*
-
-* Deprecated the majority of all the testing assertions and replaced them with a much smaller core and access to all the collections the old assertions relied on. That way the regular test/unit assertions can be used against these. Added documentation about how to use it all.
-
-* Added a wide range of new Javascript effects:
- * Effect.Puff zooms the element out and makes it smoothly transparent at the same time, giving a "puff" illusion #996 *thomas@fesch.at*
- After the animation is completed, the display property will be set to none.
- This effect will work on relative and absolute positioned elements.
-
- * Effect.Appear as the opposite of Effect.Fade #990 *thomas@fesch.at*
- You should return elements with style="display:none;" or a like class for this to work best and have no chance of flicker.
-
- * Effect.Squish for scaling down an element and making it disappear at the end #972 *thomas@fesch.at*
-
- * Effect.Scale for smoothly scaling images or text up and down #972 *thomas@fesch.at*
-
- * Effect.Fade which smoothly turns opacity from 100 to 0 and then hides the element #960 *thomas@fesch.at*
-
-* Added Request#xml_http_request? (and an alias xhr?) to that'll return true when the request came from one of the Javascript helper methods (Ajax). This can be used to give one behavior for modern browsers supporting Ajax, another to old browsers #1127 *Sam Stephenson*
-
-* Changed render_partial to take local assigns as the second parameter instead of an explicit object and then the assigns. So the API changes from:
-
- <%= render_partial "account", person, "rules" => regulations.rules %>
-
- ...to:
-
- <%= render_partial "account", :account => person, :rules => regulations.rules %>
-
- The old API will still work, though, and render_partial "account" will still assume :account => @account.
-
-* Added support for web servers that use PATH_INFO instead of REQUEST_URI like IIS #1014 *BradG/Nicholas Seckar*
-
-* Added graceful handling of PUT, DELETE, and OPTIONS requests for a complete coverage of REST functionality #1136 *Josh Knowles*
-
-* Fixed that you can now pass an alternative :href option to link_to_function/remote in order to point to somewhere other than # if the javascript fails or is turned off. You can do the same with form_remote_tag by passing in :action. #1113 *Sam Stephenson*
-
-* Fixed DateHelper to return values on the option tags such that they'll work properly in IE with form_remote_tag #1024 *Scott Raymond*
-
-* Fixed FormTagHelper#check_box to respect checked #1049 *DelynnB*
-
-* Added that render_partial called from a controller will use the action name as default #828 *Dan Peterson*
-
-* Added Element.toggle, Element.show, and Element.hide to the prototype javascript library. Toggle.display has been deprecated, but will still work #992 *Lucas Carlson*
-
-* Added that deleting a cookie should not just set it to an empty string but also instantly expire it #1118 *todd@robotcoop.com*
-
-* Added AssetTagHelper#image_path, AssetTagHelper#javascript_path, and AssetTagHelper#stylesheet_path #1110 *Larry Halff*
-
-* Fixed url_for(nil) in functional tests #1116 *Alisdair McDiarmid*
-
-* Fixed error handling of broken layouts #1115 *Michael Schubert*
-
-* Added submit_to_remote that allows you to trigger an Ajax form submition at the click of the submission button, which allows for multiple targets in a single form through the use of multiple submit buttons #930 *yrashk@gmail.com*
-
-* Fixed pagination to work with joins #1034 *scott@sigkill.org*
-
-* Fixed that *rest parameter in map.connect couldn't accept an empty list #1037 *Dee Zsombor*
-
-* Added :confirm option to link_to_remote just like link_to has #1082 *yrashk@fp.org.ua*
-
-* Added minute_step as an option to select_minute (and the helpers that use it) to jump in larger increments than just 1 minute. At 15, it would return 0, 15, 30, 45 options #1085 *ordwaye@evergreen.edu*
-
-* Fixed that an exception would be thrown when an empty form was submitted #1090 *jan@ulbrich-boerwang.de*
-
-* Moved TextHelper#human_size to NumberHelper#number_to_human_size, but kept an deprecated alias to the old method name
-
-* Fixed that the content-type for some browsers could include an additional \r which made wonky things happen #1067 *Thomas Fuchs*
-
-* Fixed that radio buttons shouldn't have a default size attribute #1074 *hendrik@mans.de*
-
-* Added ActionView::Helpers::InstanceTag::DEFAULT_RADIO_OPTIONS that contains a hash of default options for radio buttons #1074 *hendrik@mans.de*
-
-* Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 *Nicholas Seckar*
-
-* Added JavascriptHelper#periodically_call_remote in order to create areas of a page that update automatically at a set interval #945 *Jon Tirsen*
-
-* Fixed Cache#expire_matched_fragments that couldn't recognize the difference between string and url_for options #1030 *Stefan Kaes*
-
-* Added simulation of @request.request_uri in functional tests #1038 *Jamis Buck*
-
-* Fixed autolinking to work better in more cases #1013 *Jamis Buck*
-
-* Added the possible of using symbols in form helpers that relate to instance variables like text_field :account, :name in addition to text_field "account", "name"'
-
-* Fixed javascript_include_tag to output type instead of language and conform to XHTML #1018 *Rick Olson*
-
-* Added NumberHelper for common string representations like phone number, currency, and percentage #1015 *DeLynn*
-
-* Added pagination for scaffolding (10 items per page) #964 *mortonda@dgrmm.net*
-
-* Added assert_no_cookie and fixed assert_cookie_equal to deal with non-existing cookies #979 *Jeremy Kemper*
-
-* Fixed :overwrite_param so it doesn't delete but reject elements from @request.parameters #982 *raphinou@yahoo.com*
-
-* Added :method option to verify for ensuring that either GET, POST, etc is allowed #984 *Jamis Buck*
-
-* Added options to set cc, bcc, subject, and body for UrlHelper#mail_to #966 *DeLynn*
-
-* Fixed include_blank for select_hour/minute/second #527 *edward@debian.org*
-
-* Improved the message display on the exception handler pages #963 *Johan Sorensen*
-
-* Fixed that on very rare occasions, webrick would raise a NoMethodError: private method 'split' called for nil #1001 *Flurin Egger*
-
-* Fixed problem with page caching #958 *Rick Olson*
-
-
-## 1.7.0 (27th March, 2005) ##
-
-* Added ActionController::Base.page_cache_extension for setting the page cache file extension (the default is .html) #903 *Andreas*
-
-* Fixed "bad environment variable value" exception caused by Safari, Apache, and Ajax calls #918
-
-* Fixed that pagination_helper would ignore :params #947 *Sebastian Kanthak*
-
-* Added :owerwrite_params back to url_for and friends -- it was AWL since the introduction of Routes #921 *raphinou*
-
-* Added :position option to link_to_remote/form_remote_tag that can be either :before, :top, :bottom, or :after and specifies where the return from the method should be inserted #952 *Matthew McCray/Sam Stephenson*
-
-* Added Effect.Highlight to prototype.js to do Yellow Fade Technique (of 37signals' fame) on any container #952 *Sam Stephenson/court3nay*
-
-* Added include_seconds option as the third parameter to distance_of_time_in_words which will render "less than a minute" in higher resolution ("less than 10 seconds" etc) #944 *thomas@fesch.at*
-
-* Added fourth option to process in test cases to specify the content of the flash #949 *Jamis Buck*
-
-* Added Verifications that allows you to specify preconditions to actions in form of statements like <tt>verify :only => :update_post, :params => "admin_privileges", :redirect_to => { :action => "settings" }</tt>, which ensure that the update_post action is only called if admin_privileges is available as a parameter -- otherwise the user is redirected to settings. #897 *Jamis Buck*
-
-* Fixed Form.Serialize for the JavascriptHelper to also seriliaze password fields #934 *dweitzman@gmail.com*
-
-* Added JavascriptHelper#escape_javascript as a public method (was private) and made it escape both single and double quotes and new lines #940 *mortonda@dgrmm.net*
-
-* Added trailing_slash option to url_for, so you can generate urls ending in a slash. Note that is currently not recommended unless you need it for special reasons since it breaks caching #937 *stian@grytoyr.net*
-
-* Added expire_matched_fragments(regular_expression) to clear out a lot of fragment caches at once #927 *Rick Olson*
-
-* Fixed the problems with : and ? in file names for fragment caches on Windows #927 *Rick Olson*
-
-* Added TextHelper#human_size for formatting file sizes, like human_size(1234567) => 1.2 MB #943 *thomas@fesch.at*
-
-* Fixed link_to :confirm #936 *Nicholas Seckar*
-
-* Improved error reporting especially around never shallowing exceptions. Debugging helpers should be much easier now #980 *Nicholas Seckar*
-
-* Fixed Toggle.display in prototype.js #902 *Lucas Carlson*
-
-
-## 1.6.0 (22th March, 2005) ##
-
-* Added a JavascriptHelper and accompanying prototype.js library that opens the world of Ajax to Action Pack with a large array of options for dynamically interacting with an application without reloading the page #884 *Sam Stephenson/David*
-
-* Added pagination support through both a controller and helper add-on #817 *Sam Stephenson*
-
-* Fixed routing and helpers to make Rails work on non-vhost setups #826 *Nicholas Seckar/Tobias Lütke*
-
-* Added a much improved Flash module that allows for finer-grained control on expiration and allows you to flash the current action #839 *Caio Chassot*. Example of flash.now:
-
- class SomethingController < ApplicationController
- def save
- ...
- if @something.save
- # will redirect, use flash
- flash[:message] = 'Save successful'
- redirect_to :action => 'list'
- else
- # no redirect, message is for current action, use flash.now
- flash.now[:message] = 'Save failed, review'
- render_action 'edit'
- end
- end
- end
-
-* Added to_param call for parameters when composing an url using url_for from something else than strings #812 *Sam Stephenson*. Example:
-
- class Page
-   def initialize(number)
-     @number = number
-   end
-   # ...
-   def to_param
-     @number.to_s
-   end
- end
-
- You can now use instances of Page with url_for:
-
- class BarController < ApplicationController
-   def baz
-     page = Page.new(4)
-     url = url_for :page => page # => "http://foo/bar/baz?page=4"
-   end
- end
-
-* Fixed form helpers to query Model#id_before_type_cast instead of Model#id as a temporary workaround for Ruby 1.8.2 warnings #818 *DeLynn B*
-
-* Fixed TextHelper#markdown to use blank? instead of empty? so it can deal with nil strings passed #814 *Johan Sörensen*
-
-* Added TextHelper#simple_format as a non-dependency text presentation helper #814 *Johan Sörensen*
-
-* Added that the html options disabled, readonly, and multiple can all be treated as booleans. So specifying <tt>disabled => :true</tt> will give <tt>disabled="disabled"</tt>. #809 *mindel*
-
-* Added path collection syntax for Routes that will gobble up the rest of the url and pass it on to the controller #830 *rayners*. Example:
-
- map.connect 'categories/*path_info', :controller => 'categories', :action => 'show'
-
- A request for /categories/top-level-cat, would give @params[:path_info] with "top-level-cat".
- A request for /categories/top-level-cat/level-1-cat, would give @params[:path_info] with "top-level-cat/level-1-cat" and so forth.
-
- The @params[:path_info] return is really an array, but where to_s has been overwritten to do join("/").
-
-* Fixed options_for_select on selected line issue #624 *Florian Weber*
-
-* Added CaptureHelper with CaptureHelper#capture and CaptureHelper#content_for. See documentation in helper #837 *Tobias Lütke*
-
-* Fixed :anchor use in url_for #821 *Nicholas Seckar*
-
-* Removed the reliance on PATH_INFO as it was causing problems for caching and inhibited the new non-vhost support #822 *Nicholas Seckar*
-
-* Added assigns shortcut for @response.template.assigns to controller test cases *Jeremy Kemper*. Example:
-
- Before:
-
- def test_list
- assert_equal 5, @response.template.assigns['recipes'].size
- assert_equal 8, @response.template.assigns['categories'].size
- end
-
- After:
-
- def test_list
- assert_equal 5, assigns(:recipes).size
- assert_equal 8, assigns(:categories).size
- end
-
-* Added TagHelper#image_tag and deprecated UrlHelper#link_image_to (recommended approach is to combine image_tag and link_to instead)
-
-* Fixed textilize to be resilient to getting nil parsed (by using Object#blank? instead of String#empty?)
-
-* Fixed that the :multipart option in FormTagHelper#form_tag would be ignored *Yonatan Feldman*
-
-
-## 1.5.1 (7th March, 2005) ##
-
-* Fixed that the routes.rb file wouldn't be found on symlinked setups due to File.expand_path #793 *piotr@t-p-l.com*
-
-* Changed ActiveRecordStore to use Marshal instead of YAML as the latter proved troublesome in persisting circular dependencies. Updating existing applications MUST clear their existing session table from data to start using this updated store #739 *Jamis Buck*
-
-* Added shortcut :id assignment to render_component and friends (before you had to go through :params) #784 *Lucas Carlson*
-
-* Fixed that map.connect should convert arguments to strings #780 *Nicholas Seckar*
-
-* Added UrlHelper#link_to_if/link_to_unless to enable other conditions that just link_to_unless_current #757 *mindel*
-
-* Fixed that single quote was not escaped in a UrlHelper#link_to javascript confirm #549 *Scott Barron*
-
-* Removed the default border on link_image_to (it broke xhtml strict) -- can be specified with :border => 0 #517 *?/caleb*
-
-* Fixed that form helpers would treat string and symbol keys differently in html_options (and possibly create duplicate entries) #112 *Jeremy Kemper*
-
-* Fixed that broken pipe errors (clients disconnecting in mid-request) could bring down a fcgi process
-
-* Added the original exception message to session recall errors (so you can see which class wasnt required)
-
-* Fixed that RAILS_ROOT might not be defined when AP was loaded, so do a late initialization of the ROUTE_FILE #761 *Scott Barron*
-
-* Fix request.path_info and clear up LoadingModule behavior #754 *Nicholas Seckar*
-
-* Fixed caching to be aware of extensions (so you can cache files like api.wsdl or logo.png) #734 *Nicholas Seckar*
-
-* Fixed that Routes would raise NameErrors if a controller component contains characters that are not valid constant names #733 *Nicholas Seckar*
-
-* Added PATH_INFO access from the request that allows urls like the following to be interpreted by rails: http://www.example.com/dispatcher.cgi/controller/action -- that makes it possible to use rails as a CGI under lighttpd and would also allow (for example) Rublog to be ported to rails without breaking existing links to Rublog-powered blogs. #728 *Jamis Buck*
-
-* Fixed that caching the root would result in .html not index.html #731, #734 *alisdair/Nicholas Seckar*
-
-
-## 1.5.0 (24th February, 2005) ##
-
-* Added Routing as a replacement for mod_rewrite pretty urls [Nicholas Seckar]. Read more in ActionController::Base.url_for and on http://manuals.rubyonrails.com/read/book/9
-
-* Added components that allows you to call other actions for their rendered response while execution another action. You can either delegate the entire response rendering or you can mix a partial response in with your other content. Read more on http://manuals.rubyonrails.com/read/book/14
-
-*  Fixed that proxy IPs do not follow all RFC1918 nets #251 *caleb@aei-tech.com*
-
-* Added Base#render_to_string to parse a template and get the result back as a string #479
-
-* Fixed that send_file/data can work even if render* has been called before in action processing to render the content of a file to be send for example #601
-
-* Added FormOptionsHelper#time_zone_select and FormOptionsHelper#time_zone_options_for_select to work with the new value object TimeZone in Active Support #688 *Jamis Buck*
-
-* Added FormHelper#file_field and FormTagHelper#file_field_tag for creating file upload fields
-
-* Added :order option for date_select that allows control over the order in which the date dropdowns is used and which of them should be used #619 [Tim Bates]. Examples:
-
- date_select("post", "written_on", :order => [:day, :month, :year])
- date_select("user", "birthday", :order => [:month, :day])
-
-* Added ActionView::Base.register_template_handler for easy integration of an alternative template language to ERb and Builder. See test/controller/custom_handler_test.rb for a usage example #656 *Jamis Buck*
-
-* Added AssetTagHelper that provides methods for linking a HTML page together with other assets, such as javascripts, stylesheets, and feeds.
-
-* Added FormTagHelper that provides a number of methods for creating form tags that doesn't rely on conventions with an object assigned to the template like FormHelper does. With the FormTagHelper, you provide the names and values yourself.
-
-* Added Afghanistan, Iran, and Iraq to the countries list used by FormOptions#country_select and FormOptions#country_options_for_select
-
-* Renamed link_to_image to link_image_to (since thats what it actually does) -- kept alias for the old method name
-
-* Fixed textilize for RedCloth3 to keep doing hardbreaks
-
-* Fixed that assert_template_xpath_matches did not indicate when a path was not found #658 *Eric Hodel*
-
-* Added TextHelper#auto_link to turn email addresses and urls into ahrefs
-
-* Fixed that on validation errors, scaffold couldn't find template #654 *mindel*
-
-* Added Base#hide_action(*names) to hide public methods from a controller that would otherwise have been callable through the URL. For the majority of cases, its preferred just to make the methods you don't want to expose protected or private (so they'll automatically be hidden) -- but if you must have a public method, this is a way to make it uncallable. Base#hidden_actions retrieve the list of all hidden actions for the controller #644 *Nicholas Seckar*
-
-* Fixed that a bunch of methods from ActionController::Base was accessible as actions (callable through a URL) when they shouldn't have been #644 *Nicholas Seckar*
-
-* Added UrlHelper#current_page?(options) method to check if the url_for options passed corresponds to the current page
-
-* Fixed https handling on other ports than 443 *Alan Gano*
-
-* Added follow_redirect method for functional tests that'll get-request the redirect that was made. Example:
-
- def test_create_post
- post :create, "post" => { "title" => "Exciting!" }
- assert_redirected_to :action => "show"
-
- follow_redirect
- assert_rendered_file "post/show"
- end
-
- Limitation: Only works for redirects to other actions within the same controller.
-
-* Fixed double requiring of models with the same name as the controller
-
-* Fixed that query params could be forced to nil on a POST due to the raw post fix #562 *moriq@moriq.com*
-
-* Fixed that cookies shouldn't be frozen in TestRequest #571 *Eric Hodel*
-
-
-## 1.4.0 (January 25th, 2005) ##
-
-* Fixed problems with ActiveRecordStore under the development environment in Rails
-
-* Fixed the ordering of attributes in the xml-decleration of Builder #540 *woeye*
-
-* Added @request.raw_post as a convenience access to @request.env['RAW_POST_DATA'] #534 *Tobias Lütke*
-
-* Added support for automatic id-based indexing for lists of items #532 [dblack]. Example:
-
- <% @students.each do |@student| %>
- <%= text_field "student[]", "first_name", :size => "20" %>
- <%= text_field "student[]", "last_name" %>
- <%= text_field "student[]", "grade", :size => "5" %>
- <% end %>
-
- ...would produce, for say David Black with id 123 and a grace of C+:
-
- <input id="student_123_first_name" name="student[123][first_name]" size="20" size="30" type="text" value="David" />
- <input id="student_123_last_name" name="student[123][last_name]" size="30" type="text" value="Black" />
- <input id="student_123_grade" name="student[123][grade]" size="5" type="text" value="C+" />
-
-* Added :application_prefix to url_for and friends that makes it easier to setup Rails in non-vhost environments #516 *Jamis Buck*
-
-* Added :encode option to mail_to that'll allow you to masquarede the email address behind javascript or hex encoding #494 *Lucas Carlson*
-
-* Fixed that the content-header was being set to application/octet_stream instead of application/octet-stream on send_date/file *Alexey*
-
-* Removed the need for passing the binding when using CacheHelper#cache
-
-* Added TestResponse#binary_content that'll return as a string the data sent through send_data/send_file for testing #500 *Alexey*
-
-* Added @request.env['RAW_POST_DATA'] for people who need access to the data before Ruby's CGI has parsed it #505 *Jeremy Kemper*
-
-* Fixed that a default fragment store wan't being set to MemoryStore as intended.
-
-* Fixed that all redirect and render calls now return true, so you can use the pattern of "do and return". Example:
-
- def show
- redirect_to(:action => "login") and return unless @person.authenticated?
- render_text "I won't happen unless the person is authenticated"
- end
-
-* Added that renders and redirects called in before_filters will have the same effect as returning false: stopping the chain. Example:
-
- class WeblogController
- before_filter { |c| c.send(:redirect_to_url("http://www.farfaraway.com")}) }
-
- def hello
- render_text "I will never be called"
- end
- end
-
-
-* Added that only one render or redirect can happen per action. The first call wins and subsequent calls are ignored. Example:
-
- def do_something
- redirect_to :action => "elsewhere"
- render_action "overthere"
- end
-
- Only the redirect happens. The rendering call is simply ignored.
-
-
-## 1.3.1 (January 18th, 2005) ##
-
-* Fixed a bug where cookies wouldn't be set if a symbol was used instead of a string as the key
-
-* Added assert_cookie_equal to assert the contents of a named cookie
-
-* Fixed bug in page caching that prevented it from working at all
-
-
-## 1.3.0 (January 17th, 2005) ##
-
-* Added an extensive caching module that offers three levels of granularity (page, action, fragment) and a variety of stores.
- Read more in ActionController::Caching.
-
-* Added the option of passing a block to ActiveRecordHelper#form in order to add more to the auto-generated form #469 *dom@sisna.com*
-
- form("entry", :action => "sign") do |form|
- form << content_tag("b", "Department")
- form << collection_select("department", "id", @departments, "id", "name")
- end
-
-* Added arrays as a value option for params in url_for and friends #467 [Eric Anderson]. Example:
-
- url_for(:controller => 'user', :action => 'delete', :params => { 'username' => %( paul john steve ) } )
- # => /user/delete?username[]=paul&username[]=john&username[]=steve
-
-* Fixed that controller tests can now assert on the use of cookies #466 *Alexey*
-
-* Fixed that send_file would "remember" all the files sent by adding to the headers again and again #458 *Jeremy Kemper*
-
-* Fixed url rewriter confusion when the controller or action name was a substring of the controller_prefix or action_prefix
-
-* Added conditional layouts like <tt>layout "weblog_standard", :except => :rss</tt> #452 *Marcel Molina Jr.*
-
-* Fixed that MemCacheStore wasn't included by default and added default MemCache object pointing to localhost #447 *Lucas Carlson*
-
-* Added fourth argument to render_collection_of_partials that allows you to specify local_assigns -- just like render_partial #432 *Ryan Davis*
-
-* Fixed that host would choke when cgi.host returned nil #432 *Tobias Lütke*
-
-* Added that form helpers now take an index option #448 *Tim Bates*
-
- Example:
- text_field "person", "name", "index" => 3
-
- Becomes:
- <input type="text" name="person[3][name]" id="person_3_name" value="<%= @person.name %>" />
-
-* Fixed three issues with retrying breakpoints #417 *Florian Gross*
-
- 1. Don't screw up pages that use multiple values for the same parameter (?foo=bar&foo=qux was converted to ?foo=barqux)
- 2. Don't screw up all forms when you click the "Retry with Breakpoint" link multiple times instead of reloading
- (This caused the parameters to be added multiple times for GET forms leading to trouble.)
- 3. Don't add ?BP-RETRY=1 multiple times
-
-* Added that all renders and redirects now return false, so they can be used as the last line in before_filters to stop execution.
-
- Before:
- def authenticate
- unless @session[:authenticated]
- redirect_to :controller => "account", :action => "login"
- return false
- end
- end
-
- After:
- def authenticate
- redirect_to(:controller => "account", :action => "login") unless @session[:authenticated]
- end
-
-* Added conditional filters #431 [Marcel Molina Jr.]. Example:
-
- class JournalController < ActionController::Base
- # only require authentication if the current action is edit or delete
- before_filter :authorize, :only_on => [ :edit, :delete ]
-
- private
- def authorize
- # redirect to login unless authenticated
- end
- end
-
-* Added Base#render_nothing as a cleaner way of doing render_text "" when you're not interested in returning anything but an empty response.
-
-* Added the possibility of passing nil to UrlHelper#link_to to use the link itself as the name
-
-
-## 1.2.0 (January 4th, 2005) ##
-
-* Added MemCacheStore for storing session data in Danga's MemCache system *Bob Cottrell*
- Depends on: MemCached server (http://www.danga.com/memcached/), MemCache client (http://raa.ruby-lang.org/project/memcache/)
-
-* Added thread-safety to the DRbStore #66, #389 *Ben Stiglitz*
-
-* Added DateHelper#select_time and DateHelper#select_second #373 *Scott Baron*
-
-* Added :host and :protocol options to url_for and friends to redirect to another host and protocol than the current.
-
-* Added class declaration for the MissingFile exception #388 *Kent Sibilev*
-
-* Added "short hypertext note with a hyperlink to the new URI(s)" to redirects to fulfill compliance with RFC 2616 (HTTP/1.1) section 10.3.3 #397 *Tim Bates*
-
-* Added second boolean parameter to Base.redirect_to_url and Response#redirect to control whether the redirect is permanent or not (301 vs 302) #375 *Hodel*
-
-* Fixed redirects when the controller and action is named the same. Still haven't fixed same controller, module, and action, though #201 *Josh Peek*
-
-* Fixed problems with running multiple functional tests in Rails under 1.8.2 by including hack for test/unit weirdness
-
-* Fixed that @request.remote_ip didn't work in the test environment #369 *Bruno Mattarollo*
-
-
-## 1.1.0 ##
-
-* Added search through session to clear out association caches at the end of each request. This makes it possible to place Active Record objects
- in the session without worrying about stale data in the associations (the main object is still subject to caching, naturally) #347 *Tobias Lütke*
-
-* Added more informative exception when using helper :some_helper and the helper requires another file that fails, you'll get an
- error message tells you what file actually failed to load, rather than falling back on assuming it was the helper file itself #346 *dblack*
-
-* Added use of *_before_type_cast for all input and text fields. This is helpful for getting "100,000" back on a integer-based
- validation where the value would normally be "100".
-
-* Added Request#port_string to get something like ":8080" back on 8080 and "" on 80 (or 443 with https).
-
-* Added Request#domain (returns string) and Request#subdomains (returns array).
-
-* Added POST support for the breakpoint retries, so form processing that raises an exception can be retried with the original request *Florian Gross*
-
-* Fixed regression with Base#reset_session that wouldn't use the DEFAULT_SESSION_OPTIONS *adam@the-kramers.net*
-
-* Fixed error rendering of rxml documents to not just swallow the exception and return 0 (still not guessing the right line, but hey)
-
-* Fixed that textilize and markdown would instantiate their engines even on empty strings. This also fixes #333 *Ulysses*
-
-* Fixed UrlHelper#link_to_unless so it doesn't care if the id is a string or fixnum *Ryan Davis*
-
-
-## 1.0.1 ##
-
-* Fixed a bug that would cause an ApplicationController to require itself three times and hence cause filters to be run three times *evl*
-
-
-## 1.0 ##
-
-* Added that controllers will now attempt to require a model dependency with their name and in a singular attempt for their name.
- So both PostController and PostsController will automatically have the post.rb model required. If no model is found, no error is raised,
- as it is then expected that no match is available and the programmer will have included his own models.
-
-* Fixed DateHelper#date_select so that you can pass include_blank as an option even if you don't use start_year and end_year #59 *what-a-day*
-
-* Added that controllers will now search for a layout in $template_root/layouts/$controller_name.r(html|xml), so PostsController will look
- for layouts/posts.rhtml or layouts/posts.rxml and automatically configure this layout if found #307 *Marcel Molina Jr.*
-
-* Added FormHelper#radio_button to work with radio buttons like its already possible with check boxes *Michael Koziarski*
-
-* Added TemplateError#backtrace that makes it much easier to debug template errors from unit and functional tests
-
-* Added display of error messages with scaffolded form pages
-
-* Added option to ERB templates to swallow newlines by using <% if something -%> instead of just <% if something %>. Example:
-
- class SomeController < ApplicationController
- <% if options[:scaffold] %>
- scaffold :<%= singular_name %>
- <% end %>
- helper :post
-
- ...produces this on post as singular_name:
-
- class SomeController < ApplicationController
-
- scaffold :post
-
- helper :post
-
- ...where as:
-
- class SomeController < ApplicationController
- <% if options[:scaffold] -%>
- scaffold :<%= singular_name %>
- <% end -%>
- helper :post
-
- ...produces:
-
- class SomeController < ApplicationController
- scaffold :post
- helper :post
-
- *This undocumented gem for ERb was uncovered by bitsweat*
-
-* Fixed CgiRequest so that it'll now accept session options with Symbols as keys (as the documentation points out) *Suggested by Andreas*
-
-* Added that render_partial will always by default include a counter with value 1 unless there is a counter passed in via the
- local_assigns hash that overrides it. As a result, render_collection_of_partials can still be written in terms of render_partial
- and partials that make use of a counter can be called without problems from both render_collection_of_partials as well as
- render_partial #295 *Marcel Molina Jr.*
-
-* Fixed CgiRequest#out to fall back to #write if $stdout doesn't have #syswrite *Jeremy Kemper*
-
-* Fixed all helpers so that they use XHTML compliant double quotes for values instead of single quotes *htonl/Jeremy Kemper*
-
-* Added link_to_image(src, options = {}, html_options = {}). Documentation:
-
- Creates a link tag to the image residing at the +src+ using an URL created by the set of +options+. See the valid options in
- link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to
- get a link tag that just points without consideration. The <tt>html_options</tt> works jointly for the image and ahref tag by
- letting the following special values enter the options on the image and the rest goes to the ahref:
-
- ::alt: If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension)
- ::size: Supplied as "XxY", so "30x45" becomes width="30" and height="45"
- ::align: Sets the alignment, no special features
-
- The +src+ can be supplied as a...
- * full path, like "/my_images/image.gif"
- * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
- * file name without extension, like "logo", that gets expanded to "/images/logo.png"
-
-* Fixed to_input_field_tag so it no longer explicitly uses InstanceTag.value if value was specified in the options hash *evl*
-
-* Added the possibility of having validate be protected for assert_(in)valid_column #263 *Tobias Lütke*
-
-* Added that ActiveRecordHelper#form now calls url_for on the :action option.
-
-* Added all the HTTP methods as alternatives to the generic "process" for functional testing #276 *Tobias Lütke*. Examples:
-
- # Calls Controller#miletone with a GET request
- process :milestone
-
- # Calls Controller#miletone with a POST request that has parameters
- post :milestone, { "name" => "David" }
-
- # Calls Controller#milestone with a HEAD request that has both parameters and session data
- head :milestone, { "id" => 1 }, { "user_id" => 23 }
-
- This is especially useful for testing idiomatic REST web services.
-
-* Added proper handling of HEAD requests, so that content isn't returned (Request#head? added as well) #277 *Eric Hodel*
-
-* Added indifference to whether @headers["Content-Type"], @headers["Content-type"], or @headers["content-type"] is used.
-
-* Added TestSession#session_id that returns an empty string to make it easier to functional test applications that doesn't use
- cookie-based sessions #275 *jcf*
-
-* Fixed that cached template loading would still check the file system to see if the file existed #258 *Andreas Schwarz*
-
-* Added options to tailor header tag, div id, and div class on ActiveRecordHelper#error_messages_for *Josh Peek*
-
-* Added graceful handling of non-alphanumeric names and misplaced brackets in input parameters *Jeremy Kemper*
-
-* Added a new container for cookies that makes them more intuative to use. The old methods of cookie and @cookies have been deprecated.
-
- Examples for writing:
-
- cookies["user_name"] = "david" # => Will set a simple session cookie
- cookies["login"] = { "value" => "XJ-122", "expires" => Time.now + 360} # => Will set a cookie that expires in 1 hour
-
- Examples for reading:
-
- cookies["user_name"] # => "david"
- cookies.size # => 2
-
- Read more in ActionController::Cookies
-
- NOTE: If you were using the old accessor (cookies instead of @cookies), this could potentially break your code -- if you expect a full cookie object!
-
-* Added the opportunity to defined method_missing on a controller which will handle all requests for actions not otherwise defined #223 *timb*
-
-* Fixed AbstractRequest#remote_ip for users going through proxies - Patch #228 *Eric Hodel*
-
-* Added Request#ssl? which is shorthand for @request.protocol == "https://"
-
-* Added the choice to call form_tag with no arguments (resulting in a form posting to current action) *Jeremy Kemper*
-
-* Upgraded to Builder 1.2.1
-
-* Added :module as an alias for :controller_prefix to url_for and friends, so you can do redirect_to(:module => "shop", :controller => "purchases")
- and go to /shop/purchases/
-
-* Added support for controllers in modules through @params["module"].
-
-* Added reloading for dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development.
- This is turned on by default, but can be turned off with ActionController::Base.reload_dependencies = false in production environments.
-
- NOTE: This will only have an effect if you use the new model, service, and observer class methods to mark dependencies. All libraries loaded through
- require will be "forever" cached. You can, however, use ActionController::Base.load_or_require("library") to get this behavior outside of the new
- dependency style.
-
-* Added that controllers will automatically require their own helper if possible. So instead of doing:
-
- class MsgController < ApplicationController
- helper :msg
- end
-
- ...you can just do:
-
- class MsgController < ApplicationController
- end
-
-* Added dependencies_on(layer) to query the dependencies of a controller. Examples:
-
- MsgController.dependencies_on(:model) # => [ :post, :comment, :attachment ]
- MsgController.dependencies_on(:service) # => [ :notification_service ]
- MsgController.dependencies_on(:observer) # => [ :comment_observer ]
-
-* Added a new dependency model with the class methods model, service, and observer. Example:
-
- class MsgController < ApplicationController
- model :post, :comment, :attachment
- service :notification_service
- observer :comment_observer
- end
-
- These new "keywords" remove the need for explicitly calling 'require' in most cases. The observer method even instantiates the
- observer as well as requiring it.
-
-* Fixed that link_to would escape & in the url again after url_for already had done so
-
-
-## 0.9.5 (28) ##
-
-* Added helper_method to designate that a given private or protected method you should available as a helper in the view. *Jeremy Kemper*
-
-* Fixed assert_rendered_file so it actually verifies if that was the rendered file *htonl*
-
-* Added the option for sharing partial spacer templates just like partials themselves *radsaq*
-
-* Fixed that Russia was named twice in country_select *alexey*
-
-* Fixed request_origin to use remote_ip instead of remote_addr *Jeremy Kemper*
-
-* Fixed link_to breakage when nil was passed for html_options *alexey*
-
-* Fixed redirect_to on a virtual server setup with apache with a port other than the default where it would forget the port number *seanohalpin*
-
-* Fixed that auto-loading webrick on Windows would cause file uploads to fail *Jeremy Kemper*
-
-* Fixed issues with sending files on WEBrick by setting the proper binmode *Jeremy Kemper*
-
-* Added send_data as an alternative to send_file when the stream is not read off the filesystem but from a database or generated live *Jeremy Kemper*
-
-* Added a new way to include helpers that doesn't require the include hack and can go without the explicit require. *Jeremy Kemper*
-
- Before:
-
- module WeblogHelper
- def self.included(controller) #:nodoc:
- controller.ancestors.include?(ActionController::Base) ? controller.add_template_helper(self) : super
- end
- end
-
- require 'weblog_helper'
- class WeblogController < ActionController::Base
- include WeblogHelper
- end
-
- After:
-
- module WeblogHelper
- end
-
- class WeblogController < ActionController::Base
- helper :weblog
- end
-
-* Added a default content-type of "text/xml" to .rxml renders *Ryan Platte*
-
-* Fixed that when /controller/index was requested by the browser, url_for would generates wrong URLs *Ryan Platte*
-
-* Fixed a bug that would share cookies between users when using FastCGI and mod_ruby *The Robot Co-op*
-
-* Added an optional third hash parameter to the process method in functional tests that takes the session data to be used *alexey*
-
-* Added UrlHelper#mail_to to make it easier to create mailto: style ahrefs
-
-* Added better error messages for layouts declared with the .rhtml extension (which they shouldn't) *geech*
-
-* Added another case to DateHelper#distance_in_minutes to return "less than a minute" instead of "0 minutes" and "1 minute" instead of "1 minutes"
-
-* Added a hidden field to checkboxes generated with FormHelper#check_box that will make sure that the unchecked value (usually 0)
- is sent even if the checkbox is not checked. This relieves the controller from doing custom checking if the checkbox wasn't
- checked. BEWARE: This might conflict with your run-on-the-mill work-around code. *Tobias Lütke*
-
-* Fixed error_message_on to just use the first if more than one error had been added *Marcel Molina Jr.*
-
-* Fixed that URL rewriting with /controller/ was working but /controller was not and that you couldn't use :id on index *geech*
-
-* Fixed a bug with link_to where the :confirm option wouldn't be picked up if the link was a straight url instead of an option hash
-
-* Changed scaffolding of forms to use <label> tags instead of <b> to please W3C *evl*
-
-* Added DateHelper#distance_of_time_in_words_to_now(from_time) that works like distance_of_time_in_words,
- but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
-
-* Added assert_flash_equal(expected, key, message), assert_session_equal(expected, key, message),
- assert_assigned_equal(expected, key, message) to test the contents of flash, session, and template assigns.
-
-* Improved the failure report on assert_success when the action triggered a redirection *alexey*.
-
-* Added "markdown" to accompany "textilize" as a TextHelper method for converting text to HTML using the Markdown syntax.
- BlueCloth must be installed in order for this method to become available.
-
-* Made sure that an active session exists before we attempt to delete it *Samuel*
-
-* Changed link_to with Javascript confirmation to use onclick instead of onClick for XHTML validity *Scott Barron*
-
-
-## 0.9.0 (43) ##
-
-* Added support for Builder-based templates for files with the .rxml extension. These new templates are an alternative to ERb that
- are especially useful for generating XML content, such as this RSS example from Basecamp:
-
- xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
- xml.channel do
- xml.title(@feed_title)
- xml.link(@url)
- xml.description "Basecamp: Recent items"
- xml.language "en-us"
- xml.ttl "40"
-
- for item in @recent_items
- xml.item do
- xml.title(item_title(item))
- xml.description(item_description(item)) if item_description(item)
- xml.pubDate(item_pubDate(item))
- xml.guid(@person.firm.account.url + @recent_items.url(item))
- xml.link(@person.firm.account.url + @recent_items.url(item))
-
- xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
- end
- end
- end
- end
-
- ...which will generate something like:
-
- <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
- <channel>
- <title>Web Site Redesign</title>
- <link>http://www.basecamphq.com/clients/travelcenter/1/</link>
- <description>Basecamp: Recent items</description>
- <language>en-us</language>
- <ttl>40</ttl>
- <item>
- <title>Post: don't you know</title>
- <description>&amp;lt;p&amp;gt;deeper and down&amp;lt;/p&amp;gt;</description>
- <pubDate>Fri, 20 Aug 2004 21:13:50 CEST</pubDate>
- <guid>http://www.basecamphq.com/clients/travelcenter/1/msg/assets/96976/comments</guid>
- <link>http://www.basecamphq.com/clients/travelcenter/1/msg/assets/96976/comments</link>
- <dc:creator>David H. Heinemeier</dc:creator>
- </item>
- <item>
- <title>Milestone completed: Design Comp 2</title>
- <pubDate>Mon, 9 Aug 2004 14:42:06 CEST</pubDate>
- <guid>http://www.basecamphq.com/clients/travelcenter/1/milestones/#49</guid>
- <link>http://www.basecamphq.com/clients/travelcenter/1/milestones/#49</link>
- </item>
- </channel>
- </rss>
-
- The "xml" local variable is automatically available in .rxml templates. You construct the template by calling a method with the name
- of the tag you want. Options for the tag can be specified as a hash parameter to that method.
-
- Builder-based templates can be mixed and matched with the regular ERb ones. The only thing that differentiates them is the extension.
- No new methods have been added to the public interface to handle them.
-
- Action Pack ships with a version of Builder, but it will use the RubyGems version if you have one installed.
-
- Read more about Builder on: http://onestepback.org/index.cgi/Tech/Ruby/StayingSimple.rdoc
-
- *Builder is created by Jim Weirich*
-
-* Added much improved support for functional testing *what-a-day*.
-
- # Old style
- def test_failing_authenticate
- @request.request_uri = "/login/authenticate"
- @request.action = "authenticate"
- @request.request_parameters["user_name"] = "nop"
- @request.request_parameters["password"] = ""
-
- response = LoginController.process_test(@request)
-
- assert_equal "The username and/or password you entered is invalid.", response.session["flash"]["alert"]
- assert_equal "http://37signals.basecamp.com/login/", response.headers["location"]
- end
-
- # New style
- def test_failing_authenticate
- process :authenticate, "user_name" => "nop", "password" => ""
- assert_flash_has 'alert'
- assert_redirected_to :action => "index"
- end
-
- See a full example on http://codepaste.org/view/paste/334
-
-* Increased performance by up to 100% with a revised cookie class that fixes the performance problems with the
- default one that ships with 1.8.1 and below. It replaces the inheritance on SimpleDelegator with DelegateClass(Array)
- following the suggestion from Matz on:
- http://groups.google.com/groups?th=e3a4e68ba042f842&seekm=c3sioe%241qvm%241%40news.cybercity.dk#link14
-
-* Added caching for compiled ERb templates. On Basecamp, it gave between 8.5% and 71% increase in performance *Andreas Schwarz*.
-
-* Added implicit counter variable to render_collection_of_partials [Marcel Molina Jr.]. From the docs:
-
- <%= render_collection_of_partials "ad", @advertisements %>
-
- This will render "advertiser/_ad.rhtml" and pass the local variable +ad+ to the template for display. An iteration counter
- will automatically be made available to the template with a name of the form +partial_name_counter+. In the case of the
- example above, the template would be fed +ad_counter+.
-
-* Fixed problems with two sessions being maintained on reset_session that would particularly screw up ActiveRecordStore.
-
-* Fixed reset_session to start an entirely new session instead of merely deleting the old. So you can now safely access @session
- after calling reset_ression and expect it to work.
-
-* Added @request.get?, @request.post?, @request.put?, @request.delete? as convenience query methods for @request.method *geech*
-
-* Added @request.method that'll return a symbol representing the HTTP method, such as :get, :post, :put, :delete *geech*
-
-* Changed @request.remote_ip and @request.host to work properly even when a proxy is in front of the application *geech*
-
-* Added JavaScript confirm feature to link_to. Documentation:
-
- The html_options have a special feature for creating javascript confirm alerts where if you pass
- :confirm => 'Are you sure?', the link will be guarded with a JS popup asking that question.
- If the user accepts, the link is processed, otherwise not.
-
-* Added link_to_unless_current as a UrlHelper method *Sam Stephenson*. Documentation:
-
- Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current
- controller, action, and id are the same as the link's, in which case only the name is returned (or the
- given block is yielded, if one exists). This is useful for creating link bars where you don't want to link
- to the page currently being viewed.
-
-* Fixed that UrlRewriter (the driver for url_for, link_to, etc) would blow up when the anchor was an integer *alexey*
-
-* Added that layouts defined with no directory defaults to layouts. So layout "weblog/standard" will use
- weblog/standard (as always), but layout "standard" will use layouts/standard.
-
-* Fixed that partials (or any template starting with an underscore) was publically viewable *Marten*
-
-* Added HTML escaping to text_area helper.
-
-* Added :overwrite_params to url_for and friends to keep the parameters as they were passed to the current action and only overwrite a subset.
- The regular :params will clear the slate so you need to manually add in existing parameters if you want to reuse them. *raphinou*
-
-* Fixed scaffolding problem with composite named objects *Moo Jester*
-
-* Added the possibility for shared partials. Example:
-
- <%= render_partial "advertisement/ad", ad %>
-
- This will render the partial "advertisement/_ad.rhtml" regardless of which controller this is being called from.
-
- *Jacob Fugal*
-
-* Fixed crash when encountering forms that have empty-named fields *James Prudente*
-
-* Added check_box form helper method now accepts true/false as well as 1/0 *what-a-day*
-
-* Fixed the lacking creation of all directories with install.rb *Dave Steinberg*
-
-* Fixed that date_select returns valid XHTML selected options *Andreas Schwarz*
-
-* Fixed referencing an action with the same name as a controller in url_for *what-a-day*
-
-* Fixed the destructive nature of Base#attributes= on the argument *Kevin Watt*
-
-* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue.
-
-* Added SessionRestoreError that is raised when a session being restored holds objects where there is no class available.
-
-* Added block as option for inline filters. So what used to be written as:
-
- before_filter Proc { |controller| return false if controller.params["stop_action"] }
-
- ...can now be as:
-
- before_filter { |controller| return false if controller.params["stop_action"] }
-
- *Jeremy Kemper*
-
-* Made the following methods public (was protected): url_for, controller_class_name, controller_name, action_name
- This makes it easier to write filters without cheating around the encapsulation with send.
-
-* ActionController::Base#reset_session now sticks even if you access @session afterwards *Kent Sibilev*
-
-* Improved the exception logging so the log file gets almost as much as in-browser debugging.
-
-* Changed base class setup from AbstractTemplate/ERbTemplate to ActionView::Base. This change should be harmless unless you were
- accessing Action View directly in which case you now need to reference the Base class.\
-
-* Added that render_collection_of_partials returns nil if the collection is empty. This makes showing a “no items” message easier.
- For example: <%= render_collection_of_partials("message", @messages) || "No messages found." %> *Sam Stephenson*
-
-* Added :month_before_year as an option to date_select to get the month select before the year. Especially useful for credit card forms.
-
-* Added :add_month_numbers to select_month to get options like "3 - March".
-
-* Removed Base.has_active_layout? as it couldn't answer the question without the instance. Use Base#active_layout instead.
-
-* Removed redundant call to update on ActionController::Base#close_session *Andreas Schwarz*
-
-* Fixed that DRb Store accidently started its own server (instead of just client) *Andreas*
-
-* Fixed strip_links so it now works across multiple lines *Chad Fowler*
-
-* Fixed the TemplateError exception to show the proper trace on to_s (useful for unit test debugging)
-
-* Implemented class inheritable attributes without eval *Caio Chassot*
-
-* Made TextHelper#concat accept binding as it would otherwise not work
-
-* The FormOptionsHelper will now call to_s on the keys and values used to generate options
-
-
-## 0.8.5 ##
-
-* Introduced passing of locally scoped variables between templates:
-
- You can pass local variables to sub templates by using a hash of with the variable
- names as keys and the objects as values:
-
- <%= render "shared/header", { "headline" => "Welcome", "person" => person } %>
-
- These can now be accessed in shared/header with:
-
- Headline: <%= headline %>
- First name: <%= person.first_name %>
-
-* Introduced the concept of partials as a certain type of sub templates:
-
- There's also a convenience method for rendering sub templates within the current
- controller that depends on a single object (we call this kind of sub templates for
- partials). It relies on the fact that partials should follow the naming convention
- of being prefixed with an underscore -- as to separate them from regular templates
- that could be rendered on their own. In the template for Advertiser#buy, we could have:
-
- <% for ad in @advertisements %>
- <%= render_partial "ad", ad %>
- <% end %>
-
- This would render "advertiser/_ad.rhtml" and pass the local variable +ad+
- for the template to display.
-
- == Rendering a collection of partials
-
- The example of partial use describes a familar pattern where a template needs
- to iterate over an array and render a sub template for each of the elements.
- This pattern has been implemented as a single method that accepts an array and
- renders a partial by the same name of as the elements contained within. So the
- three-lined example in "Using partials" can be rewritten with a single line:
-
- <%= render_collection_of_partials "ad", @advertisements %>
-
- So this will render "advertiser/_ad.rhtml" and pass the local variable +ad+ for
- the template to display.
-
-* Improved send_file by allowing a wide range of options to be applied *Jeremy Kemper*:
-
- Sends the file by streaming it 4096 bytes at a time. This way the
- whole file doesn't need to be read into memory at once. This makes
- it feasible to send even large files.
-
- Be careful to sanitize the path parameter if it coming from a web
- page. send_file(@params['path'] allows a malicious user to
- download any file on your server.
-
- Options:
- * <tt>:filename</tt> - specifies the filename the browser will see.
- Defaults to File.basename(path).
- * <tt>:type</tt> - specifies an HTTP content type.
- Defaults to 'application/octet-stream'.
- * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
- Valid values are 'inline' and 'attachment' (default).
- * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream
- the file. Defaults to 4096.
-
- The default Content-Type and Content-Disposition headers are
- set to download arbitrary binary files in as many browsers as
- possible. IE versions 4, 5, 5.5, and 6 are all known to have
- a variety of quirks (especially when downloading over SSL).
-
- Simple download:
- send_file '/path/to.zip'
-
- Show a JPEG in browser:
- send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
-
- Read about the other Content-* HTTP headers if you'd like to
- provide the user with more information (such as Content-Description).
- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
-
- Also be aware that the document may be cached by proxies and browsers.
- The Pragma and Cache-Control headers declare how the file may be cached
- by intermediaries. They default to require clients to validate with
- the server before releasing cached responses. See
- http://www.mnot.net/cache_docs/ for an overview of web caching and
- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
- for the Cache-Control header spec.
-
-* Added pluralize method to the TextHelper that makes it easy to get strings like "1 message", "3 messages"
-
-* Added proper escaping for the rescues *Andreas Schwarz*
-
-* Added proper escaping for the option and collection tags *Andreas Schwarz*
-
-* Fixed NaN errors on benchmarking *Jim Weirich*
-
-* Fixed query string parsing for URLs that use the escaped versions of & or ; as part of a key or value
-
-* Fixed bug with custom Content-Type headers being in addition to rather than instead of the default header.
- (This bug didn't matter with neither CGI or mod_ruby, but FCGI exploded on it) *With help from Ara T. Howard*
-
-
-## 0.8.0 ##
-
-* Added select, collection_select, and country_select to make it easier for Active Records to set attributes through
- drop-down lists of options. Example:
-
- <%= select "person", "gender", %w( Male Female ) %>
-
- ...would give the following:
-
- <select name="person[gender]" id="person_gender"><option>Male</option><option>Female</option></select>
-
-* Added an option for getting multiple values on a single form name into an array instead of having the last one overwrite.
- This is especially useful for groups of checkboxes, which can now be written as:
-
- <input type="checkbox" name="rights[]" value="CREATE" />
- <input type="checkbox" name="rights[]" value="UPDATE" />
- <input type="checkbox" name="rights[]" value="DELETE" />
-
- ...and retrieved in the controller action with:
-
- @params["rights"] # => [ "CREATE", "UPDATE", "DELETE" ]
-
- The old behavior (where the last one wins, "DELETE" in the example) is still available. Just don't add "[]" to the
- end of the name. *Scott Baron*
-
-* Added send_file which uses the new render_text block acceptance to make it feasible to send large files.
- The files is sent with a bunch of voodoo HTTP headers required to get arbitrary files to download as
- expected in as many browsers as possible (eg, IE hacks). Example:
-
- def play_movie
- send_file "/movies/that_movie.avi"
- end
-
- *Jeremy Kemper*
-
-* render_text now accepts a block for deferred rendering. Useful for streaming large files, displaying
- a “please wait” message during a complex search, etc. Streaming example:
-
- render_text do |response|
- File.open(path, 'rb') do |file|
- while buf = file.read(1024)
- print buf
- end
- end
- end
-
- *Jeremy Kemper*
-
-* Added a new Tag Helper that can generate generic tags programmatically insted of through HTML. Example:
-
- tag("br", "clear" => "all") => <br clear="all" />
-
- ...that's usually not terribly interesting (unless you have a lot of options already in a hash), but it
- gives way for more specific tags, like the new form tag:
-
- form_tag({ :controller => "weblog", :action => "update" }, { :multipart => "true", "style" => "width: 200px"}) =>
- <form action="/weblog/update" enctype="multipart/formdata" style="width: 200px">
-
- There's even a "pretty" version for people who don't like to open tags in code and close them in HTML:
-
- <%= start_form_tag :action => "update" %>
- # all the input fields
- <%= end_form_tag %>
-
- (end_form_tag just returns "</form>")
-
-* The selected parameter in options_for_select may now also an array of values to be selected when
- using a multiple select. Example:
-
- options_for_select([ "VISA", "Mastercard", "Discover" ], ["VISA", "Discover"]) =>
- <option selected>VISA</option>\n<option>Mastercard</option>\n<option selected>Discover</option>
-
- *Scott Baron*
-
-* Changed the URL rewriter so controller_prefix and action_prefix can be used in isolation. You can now do:
-
- url_for(:controller_prefix => "clients")
-
- ...or:
-
- url_for(:action_prefix => "category/messages")
-
- Neither would have worked in isolation before (:controller_prefix required a :controller and :action_prefix required an :action)
-
-* Started process of a cleaner separation between Action Controller and ERb-based Action Views by introducing an
- abstract base class for views. And Amita adapter could be fitted in more easily now.
-
-* The date helper methods date_select and datetime_select now also use the field error wrapping
- (div with class fieldWithErrors by default).
-
-* The date helper methods date_select and datetime_select can now discard selects
-
-* Added option on AbstractTemplate to specify a different field error wrapping. Example:
-
- ActionView::AbstractTemplate.field_error_proc = Proc.new do |html, instance|
- "<p>#{instance.method_name + instance.error_message}</p><div style='background-color: red'>#{html}</div>"
- end
-
- ...would give the following on a Post#title (text field) error:
-
- <p>Title can't be empty</p>
- <div style='background-color: red'>
- <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
- </div>
-
-* The UrlHelper methods url_for and link_to will now by default only return paths, not complete URIs.
- That should make it easier to fit a Rails application behind a proxy or load-balancer.
- You can overwrite this by passing :only_path => false as part of the options. *Suggested by U235*
-
-* Fixed bug with having your own layout for use with scaffolding *Kevin Radloff*
-
-* Fixed bug where redirect_to_path didn't append the port on non-standard ports *dhawkins*
-
-* Scaffolding plays nicely with single-table inheritance (LoadErrors are caught) *Jeremy Kemper*
-
-* Scaffolding plays nice with plural models like Category/categories *Jeremy Kemper*
-
-* Fixed missing suffix appending in scaffolding *Kevin Radloff*
-
-
-## 0.7.9 ##
-
-* The "form" method now present boolean fields from PostgreSQL as drop-down menu. *Scott*
-
-* Scaffolding now automatically attempts to require the class that's being scaffolded.
-
-* Scaffolding will use the current active layout, instead of its own, if one has been specified. Example:
-
- class WeblogController < ActionController::Base
- layout "layouts/weblog"
- scaffold :post
- end
-
- *Suggested by Scott*
-
-* Changed url_for (and all the that drives, like redirect_to, link_to, link_for) so you can pass it a symbol instead of a hash.
- This symbol is a method reference which is then called to calculate the url. Example:
-
- class WeblogController < ActionController::Base
- def update
- # do some update
- redirect_to :dashboard_url
- end
-
- protected
- def dashboard_url
- if @project.active?
- url_for :controller => "project", :action => "dashboard"
- else
- url_for :controller => "account", :action => "dashboard"
- end
- end
- end
-
-* Added default_url_options to specialize behavior for all url_for (and friends) calls:
-
- Overwrite to implement a number of default options that all url_for-based methods will use.
- The default options should come in form of a hash, just like the one you would use for
- url_for directly. Example:
-
- def default_url_options(options)
- { :controller_prefix => @project.active? ? "projects/" : "accounts/" }
- end
-
- As you can infer from the example, this is mostly useful for situations where you want to
- centralize dynamic dissions about the urls as they stem from the business domain. Please note
- that any individual url_for call can always override the defaults set by this method.
-
-
-* Changed url_for so that an "id" passed in the :params is not treated special. You need to use the dedicated :id to get
- the special auto path-params treatment. Considering the url http://localhost:81/friends/list
-
- url_for(:action => "show", :params => { "id" => 5 })
- ...used to give http://localhost:81/friends/show/5
- ......now gives http://localhost:81/friends/show?id=5
-
- If you want the automated id behavior, do:
-
- url_for(:action => "show", :id => 5 )
- ....which gives http://localhost:81/friends/show/5
-
-
-* Fixed problem with anchor being inserted before path parameters with url_for (and friends)
-
-
-## 0.7.8 ##
-
-* Fixed session bug where you couldn't store any objects that didn't exist in the standard library
- (such as Active Record objects).
-
-* Added reset_session method for Action Controller objects to clear out all objects in the session.
-
-* Fixed that exceptions raised during filters are now also caught by the default rescues
-
-* Added new around_filter for doing before and after filtering with a single object *Florian Weber*:
-
- class WeblogController < ActionController::Base
- around_filter BenchmarkingFilter.new
-
- # Before this action is performed, BenchmarkingFilter#before(controller) is executed
- def index
- end
- # After this action has been performed, BenchmarkingFilter#after(controller) is executed
- end
-
- class BenchmarkingFilter
- def initialize
- @runtime
- end
-
- def before
- start_timer
- end
-
- def after
- stop_timer
- report_result
- end
- end
-
-* Added the options for specifying a different name and id for the form helper methods than what is guessed *Florian Weber*:
-
- text_field "post", "title"
- ...just gives: <input id="post_title" name="post[title]" size="30" type="text" value="" />
-
- text_field "post", "title", "id" => "title_for_post", "name" => "first_post_title"
- ...can now give: <input id="title_for_post" name="first_post_title" size="30" type="text" value="" />
-
-* Added DebugHelper with a single "debug" method for doing pretty dumps of objects in the view
- (now used in the default rescues to better present the contents of session and template variables)
-
-* Added note to log about the templates rendered within layouts (before just the layout was shown)
-
-* Fixed redirects on https setups *Andreas*
-
-* Fixed scaffolding problem on the edit action when using :suffix => true *Scott*
-
-* Fixed scaffolding problem where implementing list.rhtml wouldn't work for the index action
-
-* URLs generated now uses &amp; instead of just & so pages using it can validate with W3C *Spotted by Andreas*
-
-
-## 0.7.7 ##
-
-* Fixed bug in CGI extension that prevented multipart forms from working
-
-
-## 0.7.6 ##
-
-* Included ERB::Util so all templates can easily escape HTML content with <%=h @person.content %>
-
-* All requests are now considered local by default, so everyone will be exposed to detailed debugging screens on errors.
- When the application is ready to go public, set ActionController::Base.consider_all_requests_local to false,
- and implement the protected method local_request? in the controller to determine when debugging screens should be shown.
-
-* Fixed three bugs with the url_for/redirect_to/link_to handling. Considering the url http://localhost:81/friends/show/1
-
- url_for(:action => "list")
- ...used to give http://localhost:81/friends/list/1
- ......now gives http://localhost:81/friends/list
-
- url_for(:controller => "friends", :action => "destroy", :id => 5)
- ...used to give http://localhost:81/friends/destroy
- ......now gives http://localhost:81/friends/destroy/5
-
- Considering the url http://localhost:81/teachers/show/t
-
- url_for(:action => "list", :id => 5)
- ...used to give http://localhost:81/5eachers/list/t
- ......now gives http://localhost:81/teachers/list/5
-
- *Reported by David Morton & Radsaq*
-
-* Logs exception to logfile in addition to showing them for local requests
-
-* Protects the eruby load behind a begin/rescue block. eRuby is not required to run ActionController.
-
-* Fixed install.rb to also install clean_logger and the templates
-
-* Added ActiveRecordStore as a session option. Read more in lib/action_controller/session/active_record_store.rb *Tim Bates*
-
-* Change license to MIT License (and included license file in package)
-
-* Application error page now returns status code 500 instead of 200
-
-* Fixed using Procs as layout handlers *Florian Weber*
-
-* Fixed bug with using redirects ports other than 80
-
-* Added index method that calls list on scaffolding
-
-
-## 0.7.5 ##
-
-* First public release
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/actionpack/CHANGELOG.md) for previous changes.
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 1fdc57e14d..ccd0193515 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -28,291 +28,6 @@ by default and Action View rendering is implicitly triggered by Action
Controller. However, these modules are designed to function on their own and
can be used outside of Rails.
-A short rundown of some of the major features:
-
-* Actions grouped in controller as methods instead of separate command objects
- and can therefore share helper methods
-
- class CustomersController < ActionController::Base
- def show
- @customer = find_customer
- end
-
- def update
- @customer = find_customer
- if @customer.update_attributes(params[:customer])
- redirect_to :action => "show"
- else
- render :action => "edit"
- end
- end
-
- private
- def find_customer
- Customer.find params[:id]
- end
- end
-
- {Learn more}[link:classes/ActionController/Base.html]
-
-
-* ERB templates (static content mixed with dynamic output from ruby)
-
- <% @posts.each do |post| %>
- Title: <%= post.title %>
- <% end %>
-
- All post titles: <%= @posts.collect{ |p| p.title }.join(", ") %>
-
- <% unless @person.is_client? %>
- Not for clients to see...
- <% end %>
-
- {Learn more}[link:classes/ActionView.html]
-
-
-* "Builder" templates (great for XML content, like RSS)
-
- xml.rss("version" => "2.0") do
- xml.channel do
- xml.title(@feed_title)
- xml.link(@url)
- xml.description "Basecamp: Recent items"
- xml.language "en-us"
- xml.ttl "40"
-
- @recent_items.each do |item|
- xml.item do
- xml.title(item_title(item))
- xml.description(item_description(item))
- xml.pubDate(item_pubDate(item))
- xml.guid(@recent_items.url(item))
- xml.link(@recent_items.url(item))
- end
- end
- end
- end
-
- {Learn more}[link:classes/ActionView/Base.html]
-
-
-* Filters for pre- and post-processing of the response
-
- class WeblogController < ActionController::Base
- # filters as methods
- before_filter :authenticate, :cache, :audit
-
- # filter as a proc
- after_filter { |c| c.response.body = Gzip::compress(c.response.body) }
-
- # class filter
- after_filter LocalizeFilter
-
- def index
- # Before this action is run, the user will be authenticated, the cache
- # will be examined to see if a valid copy of the results already
- # exists, and the action will be logged for auditing.
-
- # After this action has run, the output will first be localized then
- # compressed to minimize bandwidth usage
- end
-
- private
- def authenticate
- # Implement the filter with full access to both request and response
- end
- end
-
- {Learn more}[link:classes/ActionController/Filters/ClassMethods.html]
-
-
-* Helpers for forms, dates, action links, and text
-
- <%= text_field_tag "post", "title", "size" => 30 %>
- <%= link_to "New post", :controller => "post", :action => "new" %>
- <%= truncate(post.title, :length => 25) %>
-
- {Learn more}[link:classes/ActionView/Helpers.html]
-
-
-* Layout sharing for template reuse
-
- class WeblogController < ActionController::Base
- layout "weblog_layout"
-
- def hello_world
- end
- end
-
- Layout file (called weblog_layout):
- <html><body><%= yield %></body></html>
-
- Template for hello_world action:
- <h1>Hello world</h1>
-
- Result of running hello_world action:
- <html><body><h1>Hello world</h1></body></html>
-
- {Learn more}[link:classes/ActionController/Layout/ClassMethods.html]
-
-
-* Routing makes pretty URLs incredibly easy
-
- match 'clients/:client_name/:project_name/:controller/:action'
-
- Accessing "/clients/37signals/basecamp/project/index" calls ProjectController#index with
- { "client_name" => "37signals", "project_name" => "basecamp" } in `params`
-
- From that action, you can write the redirect in a number of ways:
-
- redirect_to(:action => "edit") =>
- /clients/37signals/basecamp/project/edit
-
- redirect_to(:client_name => "nextangle", :project_name => "rails") =>
- /clients/nextangle/rails/project/index
-
- {Learn more}[link:classes/ActionDispatch/Routing.html]
-
-
-* Easy testing of both controller and rendered template through ActionController::TestCase
-
- class LoginControllerTest < ActionController::TestCase
- def test_failing_authenticate
- process :authenticate, :user_name => "nop", :password => ""
- assert flash.has_key?(:alert)
- assert_redirected_to :action => "index"
- end
- end
-
- {Learn more}[link:classes/ActionController/TestCase.html]
-
-
-* Automated benchmarking and integrated logging
-
- Started GET "/weblog" for 127.0.0.1 at Fri May 28 00:41:55
- Processing by WeblogController#index as HTML
- Rendered weblog/index.html.erb within layouts/application (25.7ms)
- Completed 200 OK in 29.3ms
-
- If Active Record is used as the model, you'll have the database debugging
- as well:
-
- Started POST "/posts" for 127.0.0.1 at Sat Jun 19 14:04:23
- Processing by PostsController#create as HTML
- Parameters: {"post"=>{"title"=>"this is good"}}
- SQL (0.6ms) INSERT INTO posts (title) VALUES('this is good')
- Redirected to http://example.com/posts/5
- Completed 302 Found in 221ms (Views: 215ms | ActiveRecord: 0.6ms)
-
- You specify a logger through a class method, such as:
-
- ActionController::Base.logger = ActiveSupport::Logger.new("Application Log")
- ActionController::Base.logger = Log4r::Logger.new("Application Log")
-
-
-* Caching at three levels of granularity (page, action, fragment)
-
- class WeblogController < ActionController::Base
- caches_page :show
- caches_action :account
-
- def show
- # the output of the method will be cached as
- # ActionController::Base.page_cache_directory + "/weblog/show.html"
- # and the web server will pick it up without even hitting Rails
- end
-
- def account
- # the output of the method will be cached in the fragment store
- # but Rails is hit to retrieve it, so filters are run
- end
-
- def update
- List.update(params[:list][:id], params[:list])
- expire_page :action => "show", :id => params[:list][:id]
- expire_action :action => "account"
- redirect_to :action => "show", :id => params[:list][:id]
- end
- end
-
- {Learn more}[link:classes/ActionController/Caching.html]
-
-
-* Powerful debugging mechanism for local requests
-
- All exceptions raised on actions performed on the request of a local user
- will be presented with a tailored debugging screen that includes exception
- message, stack trace, request parameters, session contents, and the
- half-finished response.
-
- {Learn more}[link:classes/ActionController/Rescue.html]
-
-
-== Simple example (from outside of Rails)
-
-This example will implement a simple weblog system using inline templates and
-an Active Record model. So let's build that WeblogController with just a few
-methods:
-
- require 'action_controller'
- require 'post'
-
- class WeblogController < ActionController::Base
- layout "weblog/layout"
-
- def index
- @posts = Post.all
- end
-
- def show
- @post = Post.find(params[:id])
- end
-
- def new
- @post = Post.new
- end
-
- def create
- @post = Post.create(params[:post])
- redirect_to :action => "show", :id => @post.id
- end
- end
-
- WeblogController::Base.view_paths = [ File.dirname(__FILE__) ]
- WeblogController.process_cgi if $0 == __FILE__
-
-The last two lines are responsible for telling ActionController where the
-template files are located and actually running the controller on a new
-request from the web-server (e.g., Apache).
-
-And the templates look like this:
-
- weblog/layout.html.erb:
- <html><body>
- <%= yield %>
- </body></html>
-
- weblog/index.html.erb:
- <% @posts.each do |post| %>
- <p><%= link_to(post.title, :action => "show", :id => post.id) %></p>
- <% end %>
-
- weblog/show.html.erb:
- <p>
- <b><%= @post.title %></b><br/>
- <b><%= @post.content %></b>
- </p>
-
- weblog/new.html.erb:
- <%= form "post" %>
-
-This simple setup will list all the posts in the system on the index page,
-which is called by accessing /weblog/. It uses the form builder for the Active
-Record model to make the new screen, which in turn hands everything over to
-the create action (that's the default target for the form builder when given a
-new model). After creating the post, it'll redirect to the show page using
-an URL such as /weblog/5 (where 5 is the id of the post).
-
== Download and installation
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index 6075e2f02b..dde51da497 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -22,7 +22,7 @@ Gem::Specification.new do |s|
s.add_dependency('builder', '~> 3.0.0')
s.add_dependency('rack', '~> 1.4.1')
s.add_dependency('rack-test', '~> 0.6.1')
- s.add_dependency('journey', '~> 1.0.1')
+ s.add_dependency('journey', '~> 2.0.0')
s.add_dependency('erubis', '~> 2.7.0')
s.add_development_dependency('activemodel', version)
diff --git a/actionpack/examples/performance.rb b/actionpack/examples/performance.rb
deleted file mode 100644
index 8ea4758961..0000000000
--- a/actionpack/examples/performance.rb
+++ /dev/null
@@ -1,185 +0,0 @@
-ENV['RAILS_ENV'] ||= 'production'
-
-require File.expand_path('../../../load_paths', __FILE__)
-require 'action_pack'
-require 'action_controller'
-require 'action_view'
-require 'active_model'
-require 'benchmark'
-
-MyHash = Class.new(Hash)
-
-Hash.class_eval do
- extend ActiveModel::Naming
- include ActiveModel::Conversion
-end
-
-class Runner
- def initialize(app, output)
- @app, @output = app, output
- end
-
- def puts(*)
- super if @output
- end
-
- def call(env)
- env['n'].to_i.times { @app.call(env) }
- @app.call(env).tap { |response| report(env, response) }
- end
-
- def report(env, response)
- return unless ENV["DEBUG"]
- out = env['rack.errors']
- out.puts response[0], response[1].to_yaml, '---'
- response[2].each { |part| out.puts part }
- out.puts '---'
- end
-
- def self.puts(*)
- super if @output
- end
-
- def self.print(*)
- super if @output
- end
-
- def self.app_and_env_for(action, n)
- env = Rack::MockRequest.env_for("/")
- env.merge!('n' => n, 'rack.input' => StringIO.new(''), 'rack.errors' => $stdout)
- app = lambda { |env| BasePostController.action(action).call(env) }
- return app, env
- end
-
- $ran = []
-
- def self.run(action, n, output = true)
- print "."
- STDOUT.flush
- @output = output
- label = action.to_s
- app, env = app_and_env_for(action, n)
- t = Benchmark.realtime { new(app, output).call(env) }
- $ran << [label, (t * 1000).to_i.to_s] if output
- end
-
- def self.done
- puts
- header, content = "", ""
- $ran.each do |k,v|
- size = [k.size, v.size].max + 1
- header << format("%#{size}s", k)
- content << format("%#{size}s", v)
- end
- puts header
- puts content
- end
-end
-
-ActionController::Base.logger = nil
-ActionController::Base.config.compile_methods!
-ActionView::Resolver.caching = ENV["RAILS_ENV"] == "production"
-
-class BasePostController < ActionController::Base
- append_view_path "#{File.dirname(__FILE__)}/views"
-
- def overhead
- self.response_body = ''
- end
-
- def index
- render :text => ''
- end
-
- $OBJECT = {:name => "Hello my name is omg", :address => "333 omg"}
-
- def partial
- render :partial => "/collection", :object => $OBJECT
- end
-
- def partial_10
- render :partial => "/ten_partials"
- end
-
- def partial_100
- render :partial => "/hundred_partials"
- end
-
- $COLLECTION1 = []
- 10.times do |i|
- $COLLECTION1 << { :name => "Hello my name is omg", :address => "333 omg" }
- end
-
- def coll_10
- render :partial => "/collection", :collection => $COLLECTION1
- end
-
- $COLLECTION2 = []
- 100.times do |i|
- $COLLECTION2 << { :name => "Hello my name is omg", :address => "333 omg" }
- end
-
- def coll_100
- render :partial => "/collection", :collection => $COLLECTION2
- end
-
- def uniq_100
- render :partial => $COLLECTION2
- end
-
- $COLLECTION3 = []
- 50.times do |i|
- $COLLECTION3 << {:name => "Hello my name is omg", :address => "333 omg"}
- $COLLECTION3 << MyHash.new(:name => "Hello my name is omg", :address => "333 omg")
- end
-
- def diff_100
- render :partial => $COLLECTION3
- end
-
- def template_1
- render :template => "template"
- end
-
- module Foo
- def omg
- "omg"
- end
- end
-
- helper Foo
-end
-
-N = (ENV['N'] || 1000).to_i
-# ActionController::Base.use_accept_header = false
-
-def run_all!(times, verbose)
- Runner.run(:overhead, times, verbose)
- Runner.run(:index, times, verbose)
- Runner.run(:template_1, times, verbose)
- Runner.run(:partial, times, verbose)
- Runner.run(:partial_10, times, verbose)
- Runner.run(:coll_10, times, verbose)
- Runner.run(:partial_100, times, verbose)
- Runner.run(:coll_100, times, verbose)
- Runner.run(:uniq_100, times, verbose)
- Runner.run(:diff_100, times, verbose)
-end
-
-if ENV["PROFILE"]
- Runner.run(ENV["PROFILE"].to_sym, 1, false)
- require "ruby-prof"
- RubyProf.start
- Runner.run(ENV["PROFILE"].to_sym, N, true)
- result = RubyProf.stop
- printer = RubyProf::CallStackPrinter.new(result)
- printer.print(File.open("output.html", "w"))
-else
- run_all!(1, false)
-
- (ENV["M"] || 1).to_i.times do
- $ran = []
- run_all!(N, true)
- Runner.done
- end
-end \ No newline at end of file
diff --git a/actionpack/examples/views/_collection.erb b/actionpack/examples/views/_collection.erb
deleted file mode 100644
index cee3fe64c0..0000000000
--- a/actionpack/examples/views/_collection.erb
+++ /dev/null
@@ -1,3 +0,0 @@
-<%= collection[:name] %>
-<%= collection[:address] %>
-<%= omg %> \ No newline at end of file
diff --git a/actionpack/examples/views/_hello.erb b/actionpack/examples/views/_hello.erb
deleted file mode 100644
index 5ab2f8a432..0000000000
--- a/actionpack/examples/views/_hello.erb
+++ /dev/null
@@ -1 +0,0 @@
-Hello \ No newline at end of file
diff --git a/actionpack/examples/views/_hundred_partials.erb b/actionpack/examples/views/_hundred_partials.erb
deleted file mode 100644
index 35c2a6c9d3..0000000000
--- a/actionpack/examples/views/_hundred_partials.erb
+++ /dev/null
@@ -1,3 +0,0 @@
-<% 100.times do %>
- <%= render :partial => "/collection", :object => $OBJECT %>
-<% end %> \ No newline at end of file
diff --git a/actionpack/examples/views/_partial.erb b/actionpack/examples/views/_partial.erb
deleted file mode 100644
index 3ca8e80b52..0000000000
--- a/actionpack/examples/views/_partial.erb
+++ /dev/null
@@ -1,10 +0,0 @@
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
-<%= "Hello" %>
diff --git a/actionpack/examples/views/_ten_partials.erb b/actionpack/examples/views/_ten_partials.erb
deleted file mode 100644
index fd02991e22..0000000000
--- a/actionpack/examples/views/_ten_partials.erb
+++ /dev/null
@@ -1,10 +0,0 @@
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %>
-<%= render :partial => '/collection', :object => $OBJECT %> \ No newline at end of file
diff --git a/actionpack/examples/views/hashes/_hash.erb b/actionpack/examples/views/hashes/_hash.erb
deleted file mode 100644
index c100a290bd..0000000000
--- a/actionpack/examples/views/hashes/_hash.erb
+++ /dev/null
@@ -1,3 +0,0 @@
-<%= hash[:name] %>
-<%= hash[:address] %>
-<%= omg %> \ No newline at end of file
diff --git a/actionpack/examples/views/my_hashes/_my_hash.erb b/actionpack/examples/views/my_hashes/_my_hash.erb
deleted file mode 100644
index e25d84101a..0000000000
--- a/actionpack/examples/views/my_hashes/_my_hash.erb
+++ /dev/null
@@ -1,3 +0,0 @@
-<%= my_hash[:name] %>
-<%= my_hash[:address] %>
-<%= omg %> \ No newline at end of file
diff --git a/actionpack/examples/views/template.html.erb b/actionpack/examples/views/template.html.erb
deleted file mode 100644
index 5ab2f8a432..0000000000
--- a/actionpack/examples/views/template.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-Hello \ No newline at end of file
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb
index b95ea5f0b2..867a7954e0 100644
--- a/actionpack/lib/abstract_controller.rb
+++ b/actionpack/lib/abstract_controller.rb
@@ -1,9 +1,6 @@
require 'action_pack'
-require 'active_support/concern'
-require 'active_support/dependencies/autoload'
-require 'active_support/core_ext/class/attribute'
+require 'active_support/rails'
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/anonymous'
require 'active_support/i18n'
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index d63d17f4c5..d3929b685c 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -32,9 +32,9 @@ module AbstractController
# @current_user ||= User.find_by_id(session[:user])
# end
#
- # def logged_in?
- # current_user != nil
- # end
+ # def logged_in?
+ # current_user != nil
+ # end
# end
#
# In a view:
diff --git a/actionpack/lib/abstract_controller/translation.rb b/actionpack/lib/abstract_controller/translation.rb
index 6d68cf4944..b6c484d188 100644
--- a/actionpack/lib/abstract_controller/translation.rb
+++ b/actionpack/lib/abstract_controller/translation.rb
@@ -1,6 +1,12 @@
module AbstractController
module Translation
def translate(*args)
+ key = args.first
+ if key.is_a?(String) && (key[0] == '.')
+ key = "#{ controller_path.gsub('/', '.') }.#{ action_name }#{ key }"
+ args[0] = key
+ end
+
I18n.translate(*args)
end
alias :t :translate
@@ -10,4 +16,4 @@ module AbstractController
end
alias :l :localize
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 7c10fcbb8a..8c1f548e47 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -1,5 +1,7 @@
+require 'active_support/rails'
require 'abstract_controller'
require 'action_dispatch'
+require 'action_controller/metal/live'
module ActionController
extend ActiveSupport::Autoload
@@ -46,18 +48,26 @@ module ActionController
eager_autoload do
autoload :RecordIdentifier
end
+
+ def self.eager_load!
+ super
+ ActionController::Caching.eager_load!
+ HTML.eager_load!
+ end
end
# All of these simply register additional autoloads
require 'action_view'
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
+
+ActiveSupport.on_load(:action_view) do
+ ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor)
+end
# Common Active Support usage in Action Controller
-require 'active_support/concern'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/name_error'
require 'active_support/core_ext/uri'
require 'active_support/inflector'
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 71425cd542..f829f5e8a2 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -88,15 +88,6 @@ module ActionController
#
# Do not put secret information in cookie-based sessions!
#
- # Other options for session storage:
- #
- # * ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and,
- # unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set
- #
- # MyApplication::Application.config.session_store :active_record_store
- #
- # in your <tt>config/initializers/session_store.rb</tt> and run <tt>script/rails g session_migration</tt>.
- #
# == Responses
#
# Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 9118806059..be29099fbe 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -48,11 +48,10 @@ module ActionController #:nodoc:
config.cache_store = ActiveSupport::Cache.lookup_store(store)
end
- private
-
- def cache_configured?
- perform_caching && cache_store
- end
+ private
+ def cache_configured?
+ perform_caching && cache_store
+ end
end
include RackDelegation
@@ -73,14 +72,14 @@ module ActionController #:nodoc:
request.get? && response.status == 200
end
- protected
- # Convenience accessor
- def cache(key, options = {}, &block)
- if cache_configured?
- cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
- else
- yield
+ protected
+ # Convenience accessor
+ def cache(key, options = {}, &block)
+ if cache_configured?
+ cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
+ else
+ yield
+ end
end
- end
end
end
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index abeb49d16f..9c77b0ccf4 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -5,48 +5,18 @@ module ActionController #:nodoc:
# useful when certain elements of an action change frequently or
# depend on complicated state while other parts rarely change or
# can be shared amongst multiple parties. The caching is done using
- # the <tt>cache</tt> helper available in the Action View. A
- # template with fragment caching might look like:
+ # the <tt>cache</tt> helper available in the Action View. See
+ # ActionView::Helpers::CacheHelper for more information.
#
- # <b>Hello <%= @name %></b>
+ # While it's strongly recommended that you use key-based cache
+ # expiration (see links in CacheHelper for more information),
+ # it is also possible to manually expire caches. For example:
#
- # <% cache do %>
- # All the topics in the system:
- # <%= render :partial => "topic", :collection => Topic.all %>
- # <% end %>
- #
- # This cache will bind the name of the action that called it, so if
- # this code was part of the view for the topics/list action, you
- # would be able to invalidate it using:
- #
- # expire_fragment(:controller => "topics", :action => "list")
- #
- # This default behavior is limited if you need to cache multiple
- # fragments per action or if the action itself is cached using
- # <tt>caches_action</tt>. To remedy this, there is an option to
- # qualify the name of the cached fragment by using the
- # <tt>:action_suffix</tt> option:
- #
- # <% cache(:action => "list", :action_suffix => "all_topics") do %>
- #
- # That would result in a name such as
- # <tt>/topics/list/all_topics</tt>, avoiding conflicts with the
- # action cache and with any fragments that use a different suffix.
- # Note that the URL doesn't have to really exist or be callable
- # - the url_for system is just used to generate unique cache names
- # that we can refer to when we need to expire the cache.
- #
- # The expiration call for this example is:
- #
- # expire_fragment(:controller => "topics",
- # :action => "list",
- # :action_suffix => "all_topics")
+ # expire_fragment("name_of_cache")
module Fragments
# Given a key (as described in <tt>expire_fragment</tt>), returns
# a key suitable for use in reading, writing, or expiring a
- # cached fragment. If the key is a hash, the generated key is the
- # return value of url_for on that hash (without the protocol).
- # All keys are prefixed with <tt>views/</tt> and uses
+ # cached fragment. All keys are prefixed with <tt>views/</tt> and uses
# ActiveSupport::Cache.expand_cache_key for the expansion.
def fragment_cache_key(key)
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
diff --git a/actionpack/lib/action_controller/caching/sweeping.rb b/actionpack/lib/action_controller/caching/sweeping.rb
index 39da15e26a..73291ce083 100644
--- a/actionpack/lib/action_controller/caching/sweeping.rb
+++ b/actionpack/lib/action_controller/caching/sweeping.rb
@@ -68,14 +68,14 @@ module ActionController #:nodoc:
def after(controller)
self.controller = controller
callback(:after) if controller.perform_caching
- # Clean up, so that the controller can be collected after this request
- self.controller = nil
end
def around(controller)
before(controller)
yield
after(controller)
+ ensure
+ clean_up
end
protected
@@ -90,6 +90,11 @@ module ActionController #:nodoc:
end
private
+ def clean_up
+ # Clean up, so that the controller can be collected after this request
+ self.controller = nil
+ end
+
def callback(timing)
controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}"
action_callback_method_name = "#{controller_callback_method_name}_#{controller.action_name}"
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 0fb419f941..a7c0e971e7 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActionController
class LogSubscriber < ActiveSupport::LogSubscriber
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 92433ab462..b38f990efa 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/blank'
require 'action_dispatch/middleware/stack'
module ActionController
@@ -187,7 +185,7 @@ module ActionController
end
def performed?
- !!response_body
+ response_body || (response && response.committed?)
end
def dispatch(name, request) #:nodoc:
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index 2193dde667..7521deaaca 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/class/attribute'
+
module ActionController
module ConditionalGet
extend ActiveSupport::Concern
@@ -5,6 +7,33 @@ module ActionController
include RackDelegation
include Head
+ included do
+ class_attribute :etaggers
+ self.etaggers = []
+ end
+
+ module ClassMethods
+ # Allows you to consider additional controller-wide information when generating an etag.
+ # For example, if you serve pages tailored depending on who's logged in at the moment, you
+ # may want to add the current user id to be part of the etag to prevent authorized displaying
+ # of cached pages.
+ #
+ # === Example
+ #
+ # class InvoicesController < ApplicationController
+ # etag { current_user.try :id }
+ #
+ # def show
+ # # Etag will differ even for the same invoice when it's viewed by a different current_user
+ # @invoice = Invoice.find(params[:id])
+ # fresh_when(@invoice)
+ # end
+ # end
+ def etag(&etagger)
+ self.etaggers += [etagger]
+ end
+ end
+
# Sets the etag, last_modified, or both on the response and renders a
# <tt>304 Not Modified</tt> response if the request is already fresh.
#
@@ -42,12 +71,12 @@ module ActionController
options.assert_valid_keys(:etag, :last_modified, :public)
else
record = record_or_options
- options = { :etag => record, :last_modified => record.try(:updated_at) }.merge(additional_options)
+ options = { etag: record, last_modified: record.try(:updated_at) }.merge(additional_options)
end
- response.etag = options[:etag] if options[:etag]
- response.last_modified = options[:last_modified] if options[:last_modified]
- response.cache_control[:public] = true if options[:public]
+ response.etag = combine_etags(options[:etag]) if options[:etag]
+ response.last_modified = options[:last_modified] if options[:last_modified]
+ response.cache_control[:public] = true if options[:public]
head :not_modified if request.fresh?(response)
end
@@ -133,5 +162,11 @@ module ActionController
def expires_now #:doc:
response.cache_control.replace(:no_cache => true)
end
+
+
+ private
+ def combine_etags(etag)
+ [ etag, *etaggers.map { |etagger| instance_exec(&etagger) }.compact ]
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb
index 379ff97048..5422cb93c4 100644
--- a/actionpack/lib/action_controller/metal/data_streaming.rb
+++ b/actionpack/lib/action_controller/metal/data_streaming.rb
@@ -76,8 +76,8 @@ module ActionController #:nodoc:
end
# Avoid having to pass an open file handle as the response body.
- # Rack::Sendfile will usually intercepts the response and just uses
- # the path directly, so no reason to open the file.
+ # Rack::Sendfile will usually intercept the response and uses
+ # the path directly, so there is no reason to open the file.
class FileBody #:nodoc:
attr_reader :to_path
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
index 8fd8f4797c..3c9d0c86a7 100644
--- a/actionpack/lib/action_controller/metal/exceptions.rb
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -16,6 +16,9 @@ module ActionController
end
end
+ class ActionController::UrlGenerationError < RoutingError #:nodoc:
+ end
+
class MethodNotAllowed < ActionControllerError #:nodoc:
def initialize(*allowed_methods)
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
diff --git a/actionpack/lib/action_controller/metal/flash.rb b/actionpack/lib/action_controller/metal/flash.rb
index 47e71371e3..b078beb675 100644
--- a/actionpack/lib/action_controller/metal/flash.rb
+++ b/actionpack/lib/action_controller/metal/flash.rb
@@ -3,10 +3,10 @@ module ActionController #:nodoc:
extend ActiveSupport::Concern
included do
- class_attribute :_flash_types, :instance_methods => false
+ class_attribute :_flash_types, instance_accessor: false
self._flash_types = []
- delegate :flash, :to => :request
+ delegate :flash, to: :request
add_flash_types(:alert, :notice)
end
@@ -14,7 +14,7 @@ module ActionController #:nodoc:
def add_flash_types(*types)
types.each do |type|
next if _flash_types.include?(type)
-
+
define_method(type) do
request.flash[type]
end
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
index 77d799a38a..e905a3cf1d 100644
--- a/actionpack/lib/action_controller/metal/force_ssl.rb
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -32,7 +32,7 @@ module ActionController
# ==== Options
# * <tt>host</tt> - Redirect to a different host name
# * <tt>only</tt> - The callback should be run only for this action
- # * <tt>except<tt> - The callback should be run for all actions except this action
+ # * <tt>except</tt> - The callback should be run for all actions except this action
# * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
# will be called only when it returns a true value.
# * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 2fcd933d32..747e1273be 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -29,19 +29,19 @@ module ActionController
self.status = status
self.location = url_for(location) if location
- if include_content_headers?(self.status)
+ if include_content?(self.status)
self.content_type = content_type || (Mime[formats.first] if formats)
+ self.response_body = " "
else
headers.delete('Content-Type')
headers.delete('Content-Length')
+ self.response_body = ""
end
-
- self.response_body = " "
end
private
# :nodoc:
- def include_content_headers?(status)
+ def include_content?(status)
case status
when 100..199
false
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index 66cdfd40ff..d2cbbd3330 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
module ActionController
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
diff --git a/actionpack/lib/action_controller/metal/hide_actions.rb b/actionpack/lib/action_controller/metal/hide_actions.rb
index b55c4643be..420b22cf56 100644
--- a/actionpack/lib/action_controller/metal/hide_actions.rb
+++ b/actionpack/lib/action_controller/metal/hide_actions.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
module ActionController
# Adds the ability to prevent public methods on a controller to be called as actions.
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index a0d1064094..03b8d8db1a 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -1,5 +1,4 @@
require 'base64'
-require 'active_support/core_ext/object/blank'
module ActionController
# Makes it dead easy to do HTTP Basic, Digest and Token authentication.
@@ -194,7 +193,7 @@ module ActionController
return false unless password
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
- uri = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url
+ uri = credentials[:uri]
[true, false].any? do |trailing_question_mark|
[true, false].any? do |password_is_ha1|
@@ -229,9 +228,9 @@ module ActionController
end
def decode_credentials(header)
- Hash[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
+ HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
key, value = pair.split('=', 2)
- [key.strip.to_sym, value.to_s.gsub(/^"|"$/,'').delete('\'')]
+ [key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
end]
end
@@ -372,7 +371,7 @@ module ActionController
# def test_access_granted_from_xml
# get(
# "/notes/1.xml", nil,
- # :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
+ # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
# )
#
# assert_equal 200, status
@@ -436,10 +435,12 @@ module ActionController
values = Hash[$1.split(',').map do |value|
value.strip! # remove any spaces between commas and values
key, value = value.split(/\=\"?/) # split key=value pairs
- value.chomp!('"') # chomp trailing " in value
- value.gsub!(/\\\"/, '"') # unescape remaining quotes
- [key, value]
- end]
+ if value
+ value.chomp!('"') # chomp trailing " in value
+ value.gsub!(/\\\"/, '"') # unescape remaining quotes
+ [key, value]
+ end
+ end.compact]
[values.delete("token"), values.with_indifferent_access]
end
end
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index 640ebf5f00..ca4ae532ca 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -11,6 +11,7 @@ module ActionController
extend ActiveSupport::Concern
include AbstractController::Logger
+ include ActionController::RackDelegation
attr_internal :view_runtime
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
new file mode 100644
index 0000000000..32e5afa335
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -0,0 +1,141 @@
+require 'action_dispatch/http/response'
+require 'delegate'
+
+module ActionController
+ # Mix this module in to your controller, and all actions in that controller
+ # will be able to stream data to the client as it's written.
+ #
+ # class MyController < ActionController::Base
+ # include ActionController::Live
+ #
+ # def stream
+ # response.headers['Content-Type'] = 'text/event-stream'
+ # 100.times {
+ # response.stream.write "hello world\n"
+ # sleep 1
+ # }
+ # response.stream.close
+ # end
+ # end
+ #
+ # There are a few caveats with this use. You *cannot* write headers after the
+ # response has been committed (Response#committed? will return truthy).
+ # Calling +write+ or +close+ on the response stream will cause the response
+ # object to be committed. Make sure all headers are set before calling write
+ # or close on your stream.
+ #
+ # You *must* call close on your stream when you're finished, otherwise the
+ # socket may be left open forever.
+ #
+ # The final caveat is that your actions are executed in a separate thread than
+ # the main thread. Make sure your actions are thread safe, and this shouldn't
+ # be a problem (don't share state across threads, etc).
+ module Live
+ class Buffer < ActionDispatch::Response::Buffer #:nodoc:
+ def initialize(response)
+ super(response, SizedQueue.new(10))
+ end
+
+ def write(string)
+ unless @response.committed?
+ @response.headers["Cache-Control"] = "no-cache"
+ @response.headers.delete "Content-Length"
+ end
+
+ super
+ end
+
+ def each
+ while str = @buf.pop
+ yield str
+ end
+ end
+
+ def close
+ super
+ @buf.push nil
+ end
+ end
+
+ class Response < ActionDispatch::Response #:nodoc: all
+ class Header < DelegateClass(Hash)
+ def initialize(response, header)
+ @response = response
+ super(header)
+ end
+
+ def []=(k,v)
+ if @response.committed?
+ raise ActionDispatch::IllegalStateError, 'header already sent'
+ end
+
+ super
+ end
+
+ def merge(other)
+ self.class.new @response, __getobj__.merge(other)
+ end
+
+ def to_hash
+ __getobj__.dup
+ end
+ end
+
+ def commit!
+ headers.freeze
+ super
+ end
+
+ private
+
+ def build_buffer(response, body)
+ buf = Live::Buffer.new response
+ body.each { |part| buf.write part }
+ buf
+ end
+
+ def merge_default_headers(original, default)
+ Header.new self, super
+ end
+ end
+
+ def process(name)
+ t1 = Thread.current
+ locals = t1.keys.map { |key| [key, t1[key]] }
+
+ # This processes the action in a child thread. It lets us return the
+ # response code and headers back up the rack stack, and still process
+ # the body in parallel with sending data to the client
+ Thread.new {
+ t2 = Thread.current
+ t2.abort_on_exception = true
+
+ # Since we're processing the view in a different thread, copy the
+ # thread locals from the main thread to the child thread. :'(
+ locals.each { |k,v| t2[k] = v }
+
+ begin
+ super(name)
+ ensure
+ @_response.commit!
+ end
+ }
+
+ @_response.await_commit
+ end
+
+ def response_body=(body)
+ super
+ response.stream.close if response
+ end
+
+ def set_response!(request)
+ if request.env["HTTP_VERSION"] == "HTTP/1.0"
+ super
+ else
+ @_response = Live::Response.new
+ @_response.request = request
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 0b800c3c62..18ae2c3bfc 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -1,6 +1,4 @@
require 'abstract_controller/collector'
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/inclusion'
module ActionController #:nodoc:
module MimeResponds
@@ -182,7 +180,8 @@ module ActionController #:nodoc:
# end
# end
#
- # Be sure to check respond_with and respond_to documentation for more examples.
+ # Be sure to check the documentation of +respond_with+ and
+ # <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
def respond_to(*mimes, &block)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
@@ -342,9 +341,9 @@ module ActionController #:nodoc:
config = self.class.mimes_for_respond_to[mime]
if config[:except]
- !action.in?(config[:except])
+ !config[:except].include?(action)
elsif config[:only]
- action.in?(config[:only])
+ config[:only].include?(action)
else
true
end
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
index aa67fa7f23..2736948ce0 100644
--- a/actionpack/lib/action_controller/metal/params_wrapper.rb
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/anonymous'
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index 1927c8bdc7..78aeeef2bf 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/blank'
require 'set'
module ActionController
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 53534c0307..d5f1cbc1a8 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
require 'action_controller/metal/exceptions'
module ActionController #:nodoc:
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index 83407846dc..42a0959a58 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -90,7 +90,7 @@ module ActionController #:nodoc:
#
# def create
# @project = Project.find(params[:project_id])
- # @task = @project.comments.build(params[:task])
+ # @task = @project.tasks.build(params[:task])
# flash[:notice] = 'Task was successfully created.' if @task.save
# respond_with(@project, @task, :status => 201)
# end
@@ -102,7 +102,7 @@ module ActionController #:nodoc:
#
# def create
# @project = Project.find(params[:project_id])
- # @task = @project.comments.build(params[:task])
+ # @task = @project.tasks.build(params[:task])
# respond_with(@project, @task, :status => 201) do |format|
# if @task.save
# flash[:notice] = 'Task was successfully created.'
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
index eeb37db2e7..9f3c997024 100644
--- a/actionpack/lib/action_controller/metal/streaming.rb
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -139,9 +139,6 @@ module ActionController #:nodoc:
# session or flash after the template starts rendering will not propagate
# to the client.
#
- # If you try to modify cookies, session or flash, an <tt>ActionDispatch::ClosedError</tt>
- # will be raised, showing those objects are closed for modification.
- #
# == Middlewares
#
# Middlewares that need to manipulate the body won't work with streaming.
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index e28c05cc2d..0cdd17bc2e 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -27,12 +27,18 @@ module ActionController
:host => request.host,
:port => request.optional_port,
:protocol => request.protocol,
- :_path_segments => request.symbolized_path_parameters
+ :_recall => request.symbolized_path_parameters
).freeze
- if _routes.equal?(env["action_dispatch.routes"])
+ if (same_origin = _routes.equal?(env["action_dispatch.routes"])) ||
+ (script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
+ (original_script_name = env['SCRIPT_NAME'])
@_url_options.dup.tap do |options|
- options[:script_name] = request.script_name.dup
+ if original_script_name
+ options[:original_script_name] = original_script_name
+ else
+ options[:script_name] = same_origin ? request.script_name.dup : script_name
+ end
options.freeze
end
else
diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb
index 851a2c4aee..3ecc105e22 100644
--- a/actionpack/lib/action_controller/railtie.rb
+++ b/actionpack/lib/action_controller/railtie.rb
@@ -9,6 +9,8 @@ module ActionController
class Railtie < Rails::Railtie #:nodoc:
config.action_controller = ActiveSupport::OrderedOptions.new
+ config.eager_load_namespaces << ActionController
+
initializer "action_controller.assets_config", :group => :all do |app|
app.config.action_controller.assets_dir ||= app.config.paths["public"].first
end
diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb
index d3ac406618..bffd2a02d0 100644
--- a/actionpack/lib/action_controller/record_identifier.rb
+++ b/actionpack/lib/action_controller/record_identifier.rb
@@ -1,83 +1,20 @@
-require 'active_support/core_ext/module'
-require 'action_controller/model_naming'
+require 'active_support/deprecation'
+require 'action_view/record_identifier'
module ActionController
- # The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
- # pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to
- # a higher logical level.
- #
- # # routes
- # resources :posts
- #
- # # view
- # <%= div_for(post) do %> <div id="post_45" class="post">
- # <%= post.body %> What a wonderful world!
- # <% end %> </div>
- #
- # # controller
- # def update
- # post = Post.find(params[:id])
- # post.update_attributes(params[:post])
- #
- # redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
- # end
- #
- # As the example above shows, you can stop caring to a large extent what the actual id of the post is.
- # You just know that one is being assigned and that the subsequent calls in redirect_to expect that
- # same naming convention and allows you to write less code if you follow it.
module RecordIdentifier
- extend self
+ MESSAGE = 'method will no longer be included by default in controllers since Rails 4.1. ' +
+ 'If you would like to use it in controllers, please include ' +
+ 'ActionView::RecodIdentifier module.'
- include ModelNaming
-
- JOIN = '_'.freeze
- NEW = 'new'.freeze
-
- # The DOM class convention is to use the singular form of an object or class.
- #
- # dom_class(post) # => "post"
- # dom_class(Person) # => "person"
- #
- # If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
- #
- # dom_class(post, :edit) # => "edit_post"
- # dom_class(Person, :edit) # => "edit_person"
- def dom_class(record_or_class, prefix = nil)
- singular = model_name_from_record_or_class(record_or_class).param_key
- prefix ? "#{prefix}#{JOIN}#{singular}" : singular
- end
-
- # The DOM id convention is to use the singular form of an object or class with the id following an underscore.
- # If no id is found, prefix with "new_" instead.
- #
- # dom_id(Post.find(45)) # => "post_45"
- # dom_id(Post.new) # => "new_post"
- #
- # If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
- #
- # dom_id(Post.find(45), :edit) # => "edit_post_45"
- # dom_id(Post.new, :custom) # => "custom_post"
def dom_id(record, prefix = nil)
- if record_id = record_key_for_dom_id(record)
- "#{dom_class(record, prefix)}#{JOIN}#{record_id}"
- else
- dom_class(record, prefix || NEW)
- end
+ ActiveSupport::Deprecation.warn 'dom_id ' + MESSAGE
+ ActionView::RecordIdentifier.dom_id(record, prefix)
end
- protected
-
- # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
- # This can be overwritten to customize the default generated string representation if desired.
- # If you need to read back a key from a dom_id in order to query for the underlying database record,
- # you should write a helper like 'person_record_from_dom_id' that will extract the key either based
- # on the default implementation (which just joins all key attributes with '_') or on your own
- # overwritten version of the method. By default, this implementation passes the key string through a
- # method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
- # make sure yourself that your dom ids are valid, in case you overwrite this method.
- def record_key_for_dom_id(record)
- key = convert_to_model(record).to_key
- key ? key.join('_') : key
+ def dom_class(record, prefix = nil)
+ ActiveSupport::Deprecation.warn 'dom_class ' + MESSAGE
+ ActionView::RecordIdentifier.dom_class(record, prefix)
end
end
end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 0498b9d138..bb693c6494 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -1,7 +1,5 @@
require 'rack/session/abstract/id'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/module/anonymous'
module ActionController
@@ -220,14 +218,7 @@ module ActionController
class TestResponse < ActionDispatch::TestResponse
def recycle!
- @status = 200
- @header = {}
- @writer = lambda { |x| @body << x }
- @block = nil
- @length = 0
- @body = []
- @charset = @content_type = nil
- @request = @template = nil
+ initialize
end
end
@@ -358,7 +349,7 @@ module ActionController
# Use AS::TestCase for the base class when describing a model
register_spec_type(self) do |desc|
- desc < ActionController::Base
+ Class === desc && desc < ActionController::Base
end
module Behavior
@@ -524,20 +515,36 @@ module ActionController
end
def setup_controller_request_and_response
- @request = TestRequest.new
- @response = TestResponse.new
+ @request = build_request
+ @response = build_response
@response.request = @request
+ @controller = nil unless defined? @controller
+
if klass = self.class.controller_class
- @controller ||= klass.new rescue nil
+ unless @controller
+ begin
+ @controller = klass.new
+ rescue
+ warn "could not construct controller #{klass}" if $VERBOSE
+ end
+ end
end
- if defined?(@controller) && @controller
+ if @controller
@controller.request = @request
@controller.params = {}
end
end
+ def build_request
+ TestRequest.new
+ end
+
+ def build_response
+ TestResponse.new
+ end
+
included do
include ActionController::TemplateAssertions
include ActionDispatch::Assertions
@@ -574,7 +581,7 @@ module ActionController
:only_path => true,
:action => action,
:relative_url_root => nil,
- :_path_segments => @request.symbolized_path_parameters)
+ :_recall => @request.symbolized_path_parameters)
url, query_string = @routes.url_for(options).split("?", 2)
diff --git a/actionpack/lib/action_controller/vendor/html-scanner.rb b/actionpack/lib/action_controller/vendor/html-scanner.rb
index 879b31e60e..896208bc05 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner.rb
@@ -1,20 +1,5 @@
-$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner"
+require 'action_view/vendor/html-scanner'
+require 'active_support/deprecation'
-module HTML
- extend ActiveSupport::Autoload
-
- eager_autoload do
- autoload :CDATA, 'html/node'
- autoload :Document, 'html/document'
- autoload :FullSanitizer, 'html/sanitizer'
- autoload :LinkSanitizer, 'html/sanitizer'
- autoload :Node, 'html/node'
- autoload :Sanitizer, 'html/sanitizer'
- autoload :Selector, 'html/selector'
- autoload :Tag, 'html/node'
- autoload :Text, 'html/node'
- autoload :Tokenizer, 'html/tokenizer'
- autoload :Version, 'html/version'
- autoload :WhiteListSanitizer, 'html/sanitizer'
- end
-end
+ActiveSupport::Deprecation.warn 'Vendored html-scanner was moved to action_view, please require "action_view/vendor/html-scanner" instead. ' +
+ 'This file will be removed in Rails 4.1'
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 1e4ac70f3d..0ec355246e 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -22,11 +22,10 @@
#++
require 'active_support'
-require 'active_support/dependencies/autoload'
+require 'active_support/rails'
require 'active_support/core_ext/module/attribute_accessors'
require 'action_pack'
-require 'active_model'
require 'rack'
module Rack
@@ -36,9 +35,14 @@ end
module ActionDispatch
extend ActiveSupport::Autoload
- autoload_under 'http' do
- autoload :Request
- autoload :Response
+ class IllegalStateError < StandardError
+ end
+
+ eager_autoload do
+ autoload_under 'http' do
+ autoload :Request
+ autoload :Response
+ end
end
autoload_under 'middleware' do
@@ -97,3 +101,8 @@ module ActionDispatch
end
autoload :Mime, 'action_dispatch/http/mime_type'
+
+ActiveSupport.on_load(:action_view) do
+ ActionView::Base.default_formats ||= Mime::SET.symbols
+ ActionView::Template::Types.delegate_to Mime
+end
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index 0b895e7860..a7f93b780e 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActionDispatch
module Http
@@ -86,21 +85,29 @@ module ActionDispatch
CACHE_CONTROL = "Cache-Control".freeze
SPESHUL_KEYS = %w[extras no-cache max-age public must-revalidate]
+ def cache_control_segments
+ if cache_control = self[CACHE_CONTROL]
+ cache_control.delete(' ').split(',')
+ else
+ []
+ end
+ end
+
def cache_control_headers
cache_control = {}
- if cc = self[CACHE_CONTROL]
- cc.delete(' ').split(',').each do |segment|
- directive, argument = segment.split('=', 2)
- case directive
- when *SPESHUL_KEYS
- key = directive.tr('-', '_')
- cache_control[key.to_sym] = argument || true
- else
- cache_control[:extras] ||= []
- cache_control[:extras] << segment
- end
+
+ cache_control_segments.each do |segment|
+ directive, argument = segment.split('=', 2)
+
+ if SPESHUL_KEYS.include? directive
+ key = directive.tr('-', '_')
+ cache_control[key.to_sym] = argument || true
+ else
+ cache_control[:extras] ||= []
+ cache_control[:extras] << segment
end
end
+
cache_control
end
diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb
index 6413929be3..47cf41cfa3 100644
--- a/actionpack/lib/action_dispatch/http/filter_parameters.rb
+++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/object/duplicable'
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index e31f3b823d..0f98e84788 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -80,6 +80,27 @@ module ActionDispatch
@env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
end
+ # Sets the \formats by string extensions. This differs from #format= by allowing you
+ # to set multiple, ordered formats, which is useful when you want to have a fallback.
+ #
+ # In this example, the :iphone format will be used if it's available, otherwise it'll fallback
+ # to the :html format.
+ #
+ # class ApplicationController < ActionController::Base
+ # before_filter :adjust_format_for_iphone_with_html_fallback
+ #
+ # private
+ # def adjust_format_for_iphone_with_html_fallback
+ # request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
+ # end
+ # end
+ def formats=(extensions)
+ parameters[:format] = extensions.first.to_s
+ @env["action_dispatch.request.formats"] = extensions.collect do |extension|
+ Mime::Type.lookup_by_extension(extension)
+ end
+ end
+
# Receives an array of mimes and return the first user sent mime that
# matches the order array.
#
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index fe39c220a5..3c1f1458ea 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -1,11 +1,10 @@
require 'set'
require 'active_support/core_ext/class/attribute_accessors'
-require 'active_support/core_ext/object/blank'
module Mime
class Mimes < Array
def symbols
- @symbols ||= map {|m| m.to_sym }
+ @symbols ||= map { |m| m.to_sym }
end
%w(<< concat shift unshift push pop []= clear compact! collect!
@@ -24,14 +23,16 @@ module Mime
EXTENSION_LOOKUP = {}
LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }
- def self.[](type)
- return type if type.is_a?(Type)
- Type.lookup_by_extension(type.to_s)
- end
+ class << self
+ def [](type)
+ return type if type.is_a?(Type)
+ Type.lookup_by_extension(type)
+ end
- def self.fetch(type)
- return type if type.is_a?(Type)
- EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
+ def fetch(type)
+ return type if type.is_a?(Type)
+ EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
+ end
end
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
@@ -62,32 +63,84 @@ module Mime
# A simple helper class used in parsing the accept header
class AcceptItem #:nodoc:
- attr_accessor :order, :name, :q
+ attr_accessor :index, :name, :q
+ alias :to_s :name
- def initialize(order, name, q=nil)
- @order = order
- @name = name.strip
- q ||= 0.0 if @name == Mime::ALL # default wildcard match to end of list
+ def initialize(index, name, q = nil)
+ @index = index
+ @name = name
+ q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list
@q = ((q || 1.0).to_f * 100).to_i
end
- def to_s
- @name
- end
-
def <=>(item)
- result = item.q <=> q
- result = order <=> item.order if result == 0
+ result = item.q <=> @q
+ result = @index <=> item.index if result == 0
result
end
def ==(item)
- name == (item.respond_to?(:name) ? item.name : item)
+ @name == item.to_s
end
end
- class << self
+ class AcceptList < Array #:nodoc:
+ def assort!
+ sort!
+
+ # Take care of the broken text/xml entry by renaming or deleting it
+ if text_xml_idx && app_xml_idx
+ app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two
+ exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
+ delete_at(text_xml_idx) # delete text_xml from the list
+ elsif text_xml_idx
+ text_xml.name = Mime::XML.to_s
+ end
+
+ # Look for more specific XML-based types and sort them ahead of app/xml
+ if app_xml_idx
+ idx = app_xml_idx
+
+ while idx < length
+ type = self[idx]
+ break if type.q < app_xml.q
+
+ if type.name.ends_with? '+xml'
+ self[app_xml_idx], self[idx] = self[idx], app_xml
+ @app_xml_idx = idx
+ end
+ idx += 1
+ end
+ end
+ map! { |i| Mime::Type.lookup(i.name) }.uniq!
+ to_a
+ end
+
+ private
+ def text_xml_idx
+ @text_xml_idx ||= index('text/xml')
+ end
+
+ def app_xml_idx
+ @app_xml_idx ||= index(Mime::XML.to_s)
+ end
+
+ def text_xml
+ self[text_xml_idx]
+ end
+
+ def app_xml
+ self[app_xml_idx]
+ end
+
+ def exchange_xml_items
+ self[app_xml_idx], self[text_xml_idx] = text_xml, app_xml
+ @app_xml_idx, @text_xml_idx = text_xml_idx, app_xml_idx
+ end
+ end
+
+ class << self
TRAILING_STAR_REGEXP = /(text|application)\/\*/
PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/
@@ -126,75 +179,30 @@ module Mime
def parse(accept_header)
if accept_header !~ /,/
accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first
- if accept_header =~ TRAILING_STAR_REGEXP
- parse_data_with_trailing_star($1)
- else
- [Mime::Type.lookup(accept_header)]
- end
+ parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)]
else
- # keep track of creation order to keep the subsequent sort stable
- list, index = [], 0
- accept_header.split(/,/).each do |header|
+ list, index = AcceptList.new, 0
+ accept_header.split(',').each do |header|
params, q = header.split(PARAMETER_SEPARATOR_REGEXP)
if params.present?
params.strip!
- if params =~ TRAILING_STAR_REGEXP
- parse_data_with_trailing_star($1).each do |m|
- list << AcceptItem.new(index, m.to_s, q)
- index += 1
- end
- else
- list << AcceptItem.new(index, params, q)
- index += 1
- end
- end
- end
- list.sort!
-
- # Take care of the broken text/xml entry by renaming or deleting it
- text_xml = list.index("text/xml")
- app_xml = list.index(Mime::XML.to_s)
-
- if text_xml && app_xml
- # set the q value to the max of the two
- list[app_xml].q = [list[text_xml].q, list[app_xml].q].max
-
- # make sure app_xml is ahead of text_xml in the list
- if app_xml > text_xml
- list[app_xml], list[text_xml] = list[text_xml], list[app_xml]
- app_xml, text_xml = text_xml, app_xml
- end
-
- # delete text_xml from the list
- list.delete_at(text_xml)
+ params = parse_trailing_star(params) || [params]
- elsif text_xml
- list[text_xml].name = Mime::XML.to_s
- end
-
- # Look for more specific XML-based types and sort them ahead of app/xml
-
- if app_xml
- idx = app_xml
- app_xml_type = list[app_xml]
-
- while(idx < list.length)
- type = list[idx]
- break if type.q < app_xml_type.q
- if type.name =~ /\+xml$/
- list[app_xml], list[idx] = list[idx], list[app_xml]
- app_xml = idx
+ params.each do |m|
+ list << AcceptItem.new(index, m.to_s, q)
+ index += 1
end
- idx += 1
end
end
-
- list.map! { |i| Mime::Type.lookup(i.name) }.uniq!
- list
+ list.assort!
end
end
+ def parse_trailing_star(accept_header)
+ parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP
+ end
+
# For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS,
# Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>.
#
@@ -274,18 +282,18 @@ module Mime
@@html_types.include?(to_sym) || @string =~ /html/
end
- def respond_to?(method, include_private = false) #:nodoc:
- super || method.to_s =~ /(\w+)\?$/
- end
-
private
def method_missing(method, *args)
- if method.to_s =~ /(\w+)\?$/
- $1.downcase.to_sym == to_sym
+ if method.to_s.ends_with? '?'
+ method[0..-2].downcase.to_sym == to_sym
else
super
end
end
+
+ def respond_to_missing?(method, include_private = false) #:nodoc:
+ method.to_s.ends_with? '?'
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index bcfd0b0d00..9a7b5bc8c7 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -4,6 +4,11 @@ require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
module Http
module Parameters
+ def initialize(env)
+ super
+ @symbolized_path_params = nil
+ end
+
# Returns both GET and POST \parameters in a single hash.
def parameters
@env["action_dispatch.request.parameters"] ||= begin
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 8cea17c7a6..b8ebeb408f 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -38,6 +38,17 @@ module ActionDispatch
METHOD
end
+ def initialize(env)
+ super
+ @method = nil
+ @request_method = nil
+ @remote_ip = nil
+ @original_fullpath = nil
+ @fullpath = nil
+ @ip = nil
+ @uuid = nil
+ end
+
def key?(key)
@env.key?(key)
end
@@ -119,9 +130,9 @@ module ActionDispatch
end
# Is this a HEAD request?
- # Equivalent to <tt>request.method_symbol == :head</tt>.
+ # Equivalent to <tt>request.request_method_symbol == :head</tt>.
def head?
- HTTP_METHOD_LOOKUP[method] == :head
+ HTTP_METHOD_LOOKUP[request_method] == :head
end
# Provides access to the request's HTTP headers, for example:
@@ -216,8 +227,11 @@ module ActionDispatch
# TODO This should be broken apart into AD::Request::Session and probably
# be included by the session middleware.
def reset_session
- session.destroy if session && session.respond_to?(:destroy)
- self.session = {}
+ if session && session.respond_to?(:destroy)
+ session.destroy
+ else
+ self.session = {}
+ end
@env['action_dispatch.request.flash_hash'] = nil
end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index cc46f9983c..11b7534ea4 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -1,7 +1,6 @@
require 'digest/md5'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/class/attribute_accessors'
+require 'monitor'
module ActionDispatch # :nodoc:
# Represents an HTTP response generated by a controller action. Use it to
@@ -41,7 +40,7 @@ module ActionDispatch # :nodoc:
alias_method :headers, :header
delegate :[], :[]=, :to => :@header
- delegate :each, :to => :@body
+ delegate :each, :to => :@stream
# Sets the HTTP response's content MIME type. For example, in the controller
# you could write this:
@@ -59,15 +58,55 @@ module ActionDispatch # :nodoc:
LOCATION = "Location".freeze
cattr_accessor(:default_charset) { "utf-8" }
+ cattr_accessor(:default_headers)
include Rack::Response::Helpers
include ActionDispatch::Http::Cache::Response
+ include MonitorMixin
+
+ class Buffer # :nodoc:
+ def initialize(response, buf)
+ @response = response
+ @buf = buf
+ @closed = false
+ end
+
+ def write(string)
+ raise IOError, "closed stream" if closed?
+
+ @response.commit!
+ @buf.push string
+ end
+
+ def each(&block)
+ @buf.each(&block)
+ end
+
+ def close
+ @response.commit!
+ @closed = true
+ end
+
+ def closed?
+ @closed
+ end
+ end
+
+ attr_reader :stream
def initialize(status = 200, header = {}, body = [])
+ super()
+
+ header = merge_default_headers(header, self.class.default_headers)
+
self.body, self.header, self.status = body, header, status
@sending_file = false
- @blank = false
+ @blank = false
+ @cv = new_cond
+ @committed = false
+ @content_type = nil
+ @charset = nil
if content_type = self[CONTENT_TYPE]
type, charset = content_type.split(/;\s*charset=/)
@@ -80,6 +119,23 @@ module ActionDispatch # :nodoc:
yield self if block_given?
end
+ def await_commit
+ synchronize do
+ @cv.wait_until { @committed }
+ end
+ end
+
+ def commit!
+ synchronize do
+ @committed = true
+ @cv.broadcast
+ end
+ end
+
+ def committed?
+ @committed
+ end
+
def status=(status)
@status = Rack::Utils.status_code(status)
end
@@ -105,14 +161,14 @@ module ActionDispatch # :nodoc:
def respond_to?(method)
if method.to_sym == :to_path
- @body.respond_to?(:to_path)
+ stream.respond_to?(:to_path)
else
super
end
end
def to_path
- @body.to_path
+ stream.to_path
end
def body
@@ -126,11 +182,17 @@ module ActionDispatch # :nodoc:
def body=(body)
@blank = true if body == EMPTY
- @body = body.respond_to?(:each) ? body : [body]
+ if body.respond_to?(:to_path)
+ @stream = body
+ else
+ @stream = build_buffer self, munge_body_object(body)
+ end
end
def body_parts
- @body
+ parts = []
+ @stream.each { |x| parts << x }
+ parts
end
def set_cookie(key, value)
@@ -151,21 +213,11 @@ module ActionDispatch # :nodoc:
end
def close
- @body.close if @body.respond_to?(:close)
+ stream.close if stream.respond_to?(:close)
end
def to_a
- assign_default_content_type_and_charset!
- handle_conditional_get!
-
- @header[SET_COOKIE] = @header[SET_COOKIE].join("\n") if @header[SET_COOKIE].respond_to?(:join)
-
- if [204, 304].include?(@status)
- @header.delete CONTENT_TYPE
- [@status, @header, []]
- else
- [@status, @header, self]
- end
+ rack_response @status, @header.to_hash
end
alias prepare! to_a
alias to_ary to_a # For implicit splat on 1.9.2
@@ -189,7 +241,21 @@ module ActionDispatch # :nodoc:
private
- def assign_default_content_type_and_charset!
+ def merge_default_headers(original, default)
+ return original unless default.respond_to?(:merge)
+
+ default.merge(original)
+ end
+
+ def build_buffer(response, body)
+ Buffer.new response, body
+ end
+
+ def munge_body_object(body)
+ body.respond_to?(:each) ? body : [body]
+ end
+
+ def assign_default_content_type_and_charset!(headers)
return if headers[CONTENT_TYPE].present?
@content_type ||= Mime::HTML
@@ -200,5 +266,19 @@ module ActionDispatch # :nodoc:
headers[CONTENT_TYPE] = type
end
+
+ def rack_response(status, header)
+ assign_default_content_type_and_charset!(header)
+ handle_conditional_get!
+
+ header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
+
+ if [204, 304].include?(@status)
+ header.delete CONTENT_TYPE
+ [status, header, []]
+ else
+ [status, header, self]
+ end
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 4266ec042e..8aa02ec482 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -87,6 +87,12 @@ module ActionDispatch
end
end
+ def initialize(env)
+ super
+ @protocol = nil
+ @port = nil
+ end
+
# Returns the complete URL used for this request.
def url
protocol + host_with_port + fullpath
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
index 338b116940..852f1cf6f5 100644
--- a/actionpack/lib/action_dispatch/middleware/callbacks.rb
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/module/delegation'
module ActionDispatch
# Provide callbacks to be executed before and after the request dispatch.
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 771f075275..ba5d332d49 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -1,5 +1,5 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/module/attribute_accessors'
module ActionDispatch
class Request < Rack::Request
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index b903f98761..0f0589a844 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -1,5 +1,7 @@
require 'action_dispatch/http/request'
require 'action_dispatch/middleware/exception_wrapper'
+require 'action_dispatch/routing/inspector'
+
module ActionDispatch
# This middleware is responsible for logging exceptions and
@@ -7,8 +9,9 @@ module ActionDispatch
class DebugExceptions
RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates')
- def initialize(app)
- @app = app
+ def initialize(app, routes_app = nil)
+ @app = app
+ @routes_app = routes_app
end
def call(env)
@@ -39,7 +42,8 @@ module ActionDispatch
:exception => wrapper.exception,
:application_trace => wrapper.application_trace,
:framework_trace => wrapper.framework_trace,
- :full_trace => wrapper.full_trace
+ :full_trace => wrapper.full_trace,
+ :routes => formatted_routes(exception)
)
file = "rescues/#{wrapper.rescue_template}"
@@ -78,5 +82,13 @@ module ActionDispatch
def stderr_logger
@stderr_logger ||= ActiveSupport::Logger.new($stderr)
end
+
+ def formatted_routes(exception)
+ return false unless @routes_app.respond_to?(:routes)
+ if exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)
+ inspector = ActionDispatch::Routing::RoutesInspector.new
+ inspector.format(@routes_app.routes.routes).join("\n")
+ end
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/head.rb b/actionpack/lib/action_dispatch/middleware/head.rb
deleted file mode 100644
index f1906a3ab3..0000000000
--- a/actionpack/lib/action_dispatch/middleware/head.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module ActionDispatch
- class Head
- def initialize(app)
- @app = app
- end
-
- def call(env)
- if env["REQUEST_METHOD"] == "HEAD"
- env["REQUEST_METHOD"] = "GET"
- env["rack.methodoverride.original_method"] = "HEAD"
- status, headers, _ = @app.call(env)
- [status, headers, []]
- else
- @app.call(env)
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb
index 6fff94707c..44290445d4 100644
--- a/actionpack/lib/action_dispatch/middleware/request_id.rb
+++ b/actionpack/lib/action_dispatch/middleware/request_id.rb
@@ -1,6 +1,5 @@
require 'securerandom'
require 'active_support/core_ext/string/access'
-require 'active_support/core_ext/object/blank'
module ActionDispatch
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index 64159fa8e7..7c12590c49 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -3,7 +3,6 @@ require 'rack/request'
require 'rack/session/abstract/id'
require 'action_dispatch/middleware/cookies'
require 'action_dispatch/request/session'
-require 'active_support/core_ext/object/blank'
module ActionDispatch
module Session
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index 7efc094f98..019849ef95 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/object/blank'
require 'action_dispatch/middleware/session/abstract_store'
require 'rack/session/cookie'
@@ -45,6 +44,14 @@ module ActionDispatch
include StaleSessionCheck
include SessionObject
+ # Override rack's method
+ def destroy_session(env, session_id, options)
+ new_sid = super
+ # Reset hash and Assign the new session id
+ env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {}
+ new_sid
+ end
+
private
def unpacked_cookie_data(env)
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
index 177d383e94..8c594c1523 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
@@ -10,8 +10,14 @@
</ol>
</p>
<% end %>
+<%= render :template => "rescues/_trace" %>
+
+<h2>
+ Routes
+</h2>
+
<p>
- Try running <code>rake routes</code> for more information on available routes.
+ Routes match in priority from top to bottom
</p>
-<%= render :template => "rescues/_trace" %>
+<p><pre><%= @routes %></pre></p>
diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb
index 62f906219c..ccc0435a39 100644
--- a/actionpack/lib/action_dispatch/railtie.rb
+++ b/actionpack/lib/action_dispatch/railtie.rb
@@ -19,10 +19,19 @@ module ActionDispatch
:verbose => false
}
+ config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff'
+ }
+
+ config.eager_load_namespaces << ActionDispatch
+
initializer "action_dispatch.configure" do |app|
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
+ ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers
ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb
index d8bcc28613..a05a23d953 100644
--- a/actionpack/lib/action_dispatch/request/session.rb
+++ b/actionpack/lib/action_dispatch/request/session.rb
@@ -2,7 +2,7 @@ require 'rack/session/abstract/id'
module ActionDispatch
class Request < Rack::Request
- # SessionHash is responsible to lazily load the session from store.
+ # Session is responsible for lazily loading the session from store.
class Session # :nodoc:
ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc:
ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc:
@@ -70,9 +70,12 @@ module ActionDispatch
def destroy
clear
options = self.options || {}
- @by.send(:destroy_session, @env, options[:id], options)
- options[:id] = nil
+ new_sid = @by.send(:destroy_session, @env, options[:id], options)
+ options[:id] = new_sid # Reset session id with a new value or nil
+
+ # Load the new sid to be written with the response
@loaded = false
+ load_for_write!
end
def [](key)
diff --git a/railties/lib/rails/application/routes_inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index 6b2caf8277..bc7229b6a1 100644
--- a/railties/lib/rails/application/routes_inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -1,7 +1,7 @@
require 'delegate'
-module Rails
- class Application
+module ActionDispatch
+ module Routing
class RouteWrapper < SimpleDelegator
def endpoint
rack_app ? rack_app.inspect : "#{controller}##{action}"
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 53a4afecb3..ddb34a2394 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,7 +1,6 @@
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/enumerable'
require 'active_support/inflector'
require 'action_dispatch/routing/redirection'
@@ -262,7 +261,7 @@ module ActionDispatch
# for root cases, where the latter is the correct one.
def self.normalize_path(path)
path = Journey::Router::Utils.normalize_path(path)
- path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^/]+\)$}
+ path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
path
end
@@ -404,6 +403,10 @@ module ActionDispatch
#
# # Matches any request starting with 'path'
# match 'path' => 'c#a', :anchor => false
+ #
+ # [:format]
+ # Allows you to specify the default value for optional +format+
+ # segment or disable it by supplying +false+.
def match(path, options=nil)
end
@@ -430,6 +433,10 @@ module ActionDispatch
if options
path = options.delete(:at)
else
+ unless Hash === app
+ raise ArgumentError, "must be called with mount point"
+ end
+
options = app
app, path = options.find { |k, v| k.respond_to?(:call) }
options.delete(app) if app
@@ -437,9 +444,10 @@ module ActionDispatch
raise "A rack application must be specified" unless path
- options[:as] ||= app_name(app)
+ options[:as] ||= app_name(app)
+ options[:via] ||= :all
- match(path, options.merge(:to => app, :anchor => false, :format => false, :via => :all))
+ match(path, options.merge(:to => app, :anchor => false, :format => false))
define_generate_prefix(app, options[:as])
self
@@ -749,7 +757,7 @@ module ActionDispatch
#
# Routes can also be constrained to an IP or a certain range of IP addresses:
#
- # constraints(:ip => /192.168.\d+.\d+/) do
+ # constraints(:ip => /192\.168\.\d+\.\d+/) do
# resources :posts
# end
#
@@ -902,7 +910,7 @@ module ActionDispatch
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
# a path appended since they fit properly in their scope level.
VALID_ON_OPTIONS = [:new, :collection, :member]
- RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param]
+ RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns]
CANONICAL_ACTIONS = %w(index create new show update destroy)
class Resource #:nodoc:
@@ -913,7 +921,7 @@ module ActionDispatch
@path = (options[:path] || @name).to_s
@controller = (options[:controller] || @name).to_s
@as = options[:as]
- @param = options[:param] || :id
+ @param = (options[:param] || :id).to_sym
@options = options
end
@@ -961,12 +969,18 @@ module ActionDispatch
"#{path}/:#{param}"
end
+ alias :shallow_scope :member_scope
+
def new_scope(new_path)
"#{path}/#{new_path}"
end
+ def nested_param
+ :"#{singular}_#{param}"
+ end
+
def nested_scope
- "#{path}/:#{singular}_#{param}"
+ "#{path}/:#{nested_param}"
end
end
@@ -1033,6 +1047,8 @@ module ActionDispatch
resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
yield if block_given?
+ concerns(options[:concerns]) if options[:concerns]
+
collection do
post :create
end if parent_resource.actions.include?(:create)
@@ -1176,6 +1192,10 @@ module ActionDispatch
# sekret_comment PATCH/PUT /comments/:id(.:format)
# sekret_comment DELETE /comments/:id(.:format)
#
+ # [:format]
+ # Allows you to specify the default value for optional +format+
+ # segment or disable it by supplying +false+.
+ #
# === Examples
#
# # routes call <tt>Admin::PostsController</tt>
@@ -1193,6 +1213,8 @@ module ActionDispatch
resource_scope(:resources, Resource.new(resources.pop, options)) do
yield if block_given?
+ concerns(options[:concerns]) if options[:concerns]
+
collection do
get :index if parent_resource.actions.include?(:index)
post :create if parent_resource.actions.include?(:create)
@@ -1477,18 +1499,18 @@ module ActionDispatch
def nested_options #:nodoc:
options = { :as => parent_resource.member_name }
options[:constraints] = {
- :"#{parent_resource.singular}_id" => id_constraint
- } if id_constraint?
+ parent_resource.nested_param => param_constraint
+ } if param_constraint?
options
end
- def id_constraint? #:nodoc:
- @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
+ def param_constraint? #:nodoc:
+ @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
end
- def id_constraint #:nodoc:
- @scope[:constraints][:id]
+ def param_constraint #:nodoc:
+ @scope[:constraints][parent_resource.param]
end
def canonical_action?(action, flag) #:nodoc:
@@ -1501,7 +1523,7 @@ module ActionDispatch
def path_for_action(action, path) #:nodoc:
prefix = shallow_scoping? ?
- "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]
+ "#{@scope[:shallow_path]}/#{parent_resource.shallow_scope}" : @scope[:path]
if canonical_action?(action, path.blank?)
prefix.to_s
@@ -1563,15 +1585,122 @@ module ActionDispatch
end
end
+ # Routing Concerns allow you to declare common routes that can be reused
+ # inside others resources and routes.
+ #
+ # concern :commentable do
+ # resources :comments
+ # end
+ #
+ # concern :image_attachable do
+ # resources :images, only: :index
+ # end
+ #
+ # These concerns are used in Resources routing:
+ #
+ # resources :messages, concerns: [:commentable, :image_attachable]
+ #
+ # or in a scope or namespace:
+ #
+ # namespace :posts do
+ # concerns :commentable
+ # end
+ module Concerns
+ # Define a routing concern using a name.
+ #
+ # Concerns may be defined inline, using a block, or handled by
+ # another object, by passing that object as the second parameter.
+ #
+ # The concern object, if supplied, should respond to <tt>call</tt>,
+ # which will receive two parameters:
+ #
+ # * The current mapper
+ # * A hash of options which the concern object may use
+ #
+ # Options may also be used by concerns defined in a block by accepting
+ # a block parameter. So, using a block, you might do something as
+ # simple as limit the actions available on certain resources, passing
+ # standard resource options through the concern:
+ #
+ # concern :commentable do |options|
+ # resources :comments, options
+ # end
+ #
+ # resources :posts, concerns: :commentable
+ # resources :archived_posts do
+ # # Don't allow comments on archived posts
+ # concerns :commentable, only: [:index, :show]
+ # end
+ #
+ # Or, using a callable object, you might implement something more
+ # specific to your application, which would be out of place in your
+ # routes file.
+ #
+ # # purchasable.rb
+ # class Purchasable
+ # def initialize(defaults = {})
+ # @defaults = defaults
+ # end
+ #
+ # def call(mapper, options = {})
+ # options = @defaults.merge(options)
+ # mapper.resources :purchases
+ # mapper.resources :receipts
+ # mapper.resources :returns if options[:returnable]
+ # end
+ # end
+ #
+ # # routes.rb
+ # concern :purchasable, Purchasable.new(returnable: true)
+ #
+ # resources :toys, concerns: :purchasable
+ # resources :electronics, concerns: :purchasable
+ # resources :pets do
+ # concerns :purchasable, returnable: false
+ # end
+ #
+ # Any routing helpers can be used inside a concern. If using a
+ # callable, they're accessible from the Mapper that's passed to
+ # <tt>call</tt>.
+ def concern(name, callable = nil, &block)
+ callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
+ @concerns[name] = callable
+ end
+
+ # Use the named concerns
+ #
+ # resources :posts do
+ # concerns :commentable
+ # end
+ #
+ # concerns also work in any routes helper that you want to use:
+ #
+ # namespace :posts do
+ # concerns :commentable
+ # end
+ def concerns(*args)
+ options = args.extract_options!
+ args.flatten.each do |name|
+ if concern = @concerns[name]
+ concern.call(self, options)
+ else
+ raise ArgumentError, "No concern named #{name} was found!"
+ end
+ end
+ end
+ end
+
def initialize(set) #:nodoc:
@set = set
@scope = { :path_names => @set.resources_path_names }
+ @concerns = {}
end
include Base
include HttpHelpers
include Redirection
include Scoping
+ include Concerns
include Resources
end
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 1d6ca0c78d..1fe40d8458 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -1,6 +1,5 @@
require 'journey'
require 'forwardable'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/remove_method'
@@ -162,19 +161,12 @@ module ActionDispatch
end
private
- def url_helper_name(name, only_path)
- if only_path
- :"#{name}_path"
- else
- :"#{name}_url"
- end
- end
def define_named_route_methods(name, route)
- [true, false].each do |only_path|
- hash = route.defaults.merge(:use_route => name, :only_path => only_path)
- define_url_helper route, name, hash
- end
+ define_url_helper route, :"#{name}_path",
+ route.defaults.merge(:use_route => name, :only_path => true)
+ define_url_helper route, :"#{name}_url",
+ route.defaults.merge(:use_route => name, :only_path => false)
end
# Create a url helper allowing ordered parameters to be associated
@@ -191,11 +183,9 @@ module ActionDispatch
# foo_url(bar, baz, bang, :sort_by => 'baz')
#
def define_url_helper(route, name, options)
- selector = url_helper_name(name, options[:only_path])
-
@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
- remove_possible_method :#{selector}
- def #{selector}(*args)
+ remove_possible_method :#{name}
+ def #{name}(*args)
if #{optimize_helper?(route)} && args.size == #{route.required_parts.size} && !args.last.is_a?(Hash) && optimize_routes_generation?
options = #{options.inspect}
options.merge!(url_options) if respond_to?(:url_options)
@@ -207,7 +197,7 @@ module ActionDispatch
end
END_EVAL
- helpers << selector
+ helpers << name
end
# Clause check about when we need to generate an optimized helper.
@@ -236,7 +226,7 @@ module ActionDispatch
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
- attr_accessor :default_url_options, :request_class, :valid_conditions
+ attr_accessor :default_url_options, :request_class
alias :routes :set
@@ -248,13 +238,7 @@ module ActionDispatch
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
-
self.request_class = request_class
- @valid_conditions = { :controller => true, :action => true }
- request_class.public_instance_methods.each { |m|
- @valid_conditions[m] = true
- }
- @valid_conditions.delete(:id)
@append = []
@prepend = []
@@ -333,7 +317,7 @@ module ActionDispatch
end
end
- MountedHelpers.class_eval <<-RUBY
+ MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def #{name}
@#{name} ||= _#{name}
end
@@ -385,7 +369,7 @@ module ActionDispatch
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
- conditions = build_conditions(conditions, valid_conditions, path.names.map { |x| x.to_sym })
+ conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name && !named_routes[name]
@@ -422,21 +406,22 @@ module ActionDispatch
end
private :build_path
- def build_conditions(current_conditions, req_predicates, path_values)
+ def build_conditions(current_conditions, path_values)
conditions = current_conditions.dup
- verbs = conditions[:request_method] || []
-
# Rack-Mount requires that :request_method be a regular expression.
# :request_method represents the HTTP verb that matches this route.
#
# Here we munge values before they get sent on to rack-mount.
+ verbs = conditions[:request_method] || []
unless verbs.empty?
conditions[:request_method] = %r[^#{verbs.join('|')}$]
end
- conditions.delete_if { |k,v| !(req_predicates.include?(k) || path_values.include?(k)) }
- conditions
+ conditions.keep_if do |k, _|
+ k == :action || k == :controller ||
+ @request_class.public_method_defined?(k) || path_values.include?(k)
+ end
end
private :build_conditions
@@ -453,12 +438,11 @@ module ActionDispatch
attr_reader :options, :recall, :set, :named_route
- def initialize(options, recall, set, extras = false)
+ def initialize(options, recall, set)
@named_route = options.delete(:use_route)
@options = options.dup
@recall = recall.dup
@set = set
- @extras = extras
normalize_options!
normalize_controller_action_id!
@@ -477,9 +461,7 @@ module ActionDispatch
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
- if named_route_exists?
- @options[key] = @recall.delete(key) if segment_keys.include?(key)
- else
+ if !named_route_exists? || segment_keys.include?(key)
@options[key] = @recall.delete(key)
end
end
@@ -543,20 +525,12 @@ module ActionDispatch
recall[:action] = options.delete(:action) if options[:action] == 'index'
end
+ # Generates a path from routes, returns [path, params]
+ # if no path is returned the formatter will raise Journey::Router::RoutingError
def generate
- path, params = @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
-
- raise_routing_error unless path
-
- return [path, params.keys] if @extras
-
- [path, params]
- rescue Journey::Router::RoutingError
- raise_routing_error
- end
-
- def raise_routing_error
- raise ActionController::RoutingError, "No route matches #{options.inspect}"
+ @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
+ rescue Journey::Router::RoutingError => e
+ raise ActionController::UrlGenerationError, "No route matches #{options.inspect} #{e.message}"
end
def different_controller?
@@ -581,15 +555,17 @@ module ActionDispatch
end
def generate_extras(options, recall={})
- generate(options, recall, true)
+ path, params = generate(options, recall)
+ return path, params.keys
end
- def generate(options, recall = {}, extras = false)
- Generator.new(options, recall, self, extras).generate
+ def generate(options, recall = {})
+ Generator.new(options, recall, self).generate
end
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
- :trailing_slash, :anchor, :params, :only_path, :script_name]
+ :trailing_slash, :anchor, :params, :only_path, :script_name,
+ :original_script_name]
def mounted?
false
@@ -608,13 +584,19 @@ module ActionDispatch
options = default_url_options.merge(options || {})
user, password = extract_authentication(options)
- path_segments = options.delete(:_path_segments)
- script_name = options.delete(:script_name).presence || _generate_prefix(options)
+ recall = options.delete(:_recall)
+
+ original_script_name = options.delete(:original_script_name).presence
+ script_name = options.delete(:script_name).presence || _generate_prefix(options)
+
+ if script_name && original_script_name
+ script_name = original_script_name + script_name
+ end
path_options = options.except(*RESERVED_OPTIONS)
path_options = yield(path_options) if block_given?
- path, params = generate(path_options, path_segments || {})
+ path, params = generate(path_options, recall || {})
params.merge!(options[:params] || {})
ActionDispatch::Http::URL.url_for(options.merge!({
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index fd3bed7e8f..d4cd537048 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -95,6 +95,8 @@ module ActionDispatch
self.default_url_options = {}
end
+
+ include(*_url_for_modules) if respond_to?(:_url_for_modules)
end
def initialize(*)
@@ -102,7 +104,7 @@ module ActionDispatch
super
end
- # Hook overriden in controller to add request information
+ # Hook overridden in controller to add request information
# with `default_url_options`. Application logic should not
# go into url_options.
def url_options
diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
index 7dc3d0f97c..6c61d4e61a 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
@@ -1,4 +1,4 @@
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
module ActionDispatch
module Assertions
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index b4c8f839ac..b15e0446de 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/inclusion'
module ActionDispatch
module Assertions
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index 41fa3a4b95..9de545b3c5 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -127,16 +127,13 @@ module ActionDispatch
# with a new RouteSet instance.
#
# The new instance is yielded to the passed block. Typically the block
- # will create some routes using <tt>map.draw { map.connect ... }</tt>:
+ # will create some routes using <tt>set.draw { match ... }</tt>:
#
# with_routing do |set|
- # set.draw do |map|
- # map.connect ':controller/:action/:id'
- # assert_equal(
- # ['/content/10/show', {}],
- # map.generate(:controller => 'content', :id => 10, :action => 'show')
- # end
+ # set.draw do
+ # resources :users
# end
+ # assert_equal "/users", users_path
# end
#
def with_routing
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
index 5f9c3bbf48..9388d44eef 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -1,4 +1,4 @@
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
require 'active_support/core_ext/object/inclusion'
#--
diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
index 68f1347e7c..2e38266aba 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/tag.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
@@ -1,4 +1,4 @@
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
module ActionDispatch
module Assertions
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index c5ef46ad30..a8b27ffafd 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -1,7 +1,6 @@
require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/object/inclusion'
require 'active_support/core_ext/object/try'
require 'rack/test'
@@ -346,7 +345,7 @@ module ActionDispatch
define_method(method) do |*args|
reset! unless integration_session
# reset the html_document variable, but only for new get/post calls
- @html_document = nil unless method.in?(["cookies", "assigns"])
+ @html_document = nil unless method == 'cookies' || method == 'assigns'
integration_session.__send__(method, *args).tap do
copy_session_variables!
end
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index 639ae6f398..c63778f870 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/indifferent_access'
require 'rack/utils'
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index 03dfa110e3..091b0d8cd2 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -22,6 +22,7 @@
#++
require 'active_support'
+require 'active_support/rails'
require 'action_pack'
module ActionView
@@ -32,12 +33,14 @@ module ActionView
autoload :Base
autoload :Context
autoload :CompiledTemplates, "action_view/context"
+ autoload :Digestor
autoload :Helpers
autoload :LookupContext
autoload :PathSet
+ autoload :RecordIdentifier
+ autoload :RoutingUrlFor
autoload :Template
-
autoload_under "renderer" do
autoload :Renderer
autoload :AbstractRenderer
@@ -68,6 +71,7 @@ module ActionView
autoload :MissingTemplate
autoload :ActionViewError
autoload :EncodingError
+ autoload :MissingRequestError
autoload :TemplateError
autoload :WrongEncodingError
end
@@ -76,6 +80,11 @@ module ActionView
autoload :TestCase
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
+
+ def self.eager_load!
+ super
+ ActionView::Template.eager_load!
+ end
end
require 'active_support/core_ext/string/output_safety'
diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb
index 81880d17ea..4bbb31b3ee 100644
--- a/actionpack/lib/action_view/asset_paths.rb
+++ b/actionpack/lib/action_view/asset_paths.rb
@@ -1,6 +1,5 @@
require 'zlib'
require 'active_support/core_ext/file'
-require 'action_controller/metal/exceptions'
module ActionView
class AssetPaths #:nodoc:
@@ -98,7 +97,7 @@ module ActionView
end
def invalid_asset_host!(help_message)
- raise ActionController::RoutingError, "This asset host cannot be computed without a request in scope. #{help_message}"
+ raise ActionView::MissingRequestError, "This asset host cannot be computed without a request in scope. #{help_message}"
end
# Pick an asset host for this source. Returns +nil+ if no host is set,
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 7bfbc1f0aa..3464ec523e 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -1,6 +1,4 @@
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/ordered_options'
require 'action_view/log_subscriber'
@@ -148,6 +146,9 @@ module ActionView #:nodoc:
cattr_accessor :prefix_partial_path_with_controller_namespace
@@prefix_partial_path_with_controller_namespace = true
+ # Specify default_formats that can be rendered.
+ cattr_accessor :default_formats
+
class_attribute :_routes
class_attribute :logger
@@ -180,8 +181,6 @@ module ActionView #:nodoc:
def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc:
@_config = ActiveSupport::InheritableOptions.new
- # Handle all these for backwards compatibility.
- # TODO Provide a new API for AV::Base and deprecate this one.
if context.is_a?(ActionView::Renderer)
@view_renderer = context
else
diff --git a/actionpack/lib/action_view/context.rb b/actionpack/lib/action_view/context.rb
index 245849d706..ee263df484 100644
--- a/actionpack/lib/action_view/context.rb
+++ b/actionpack/lib/action_view/context.rb
@@ -26,11 +26,11 @@ module ActionView
# Encapsulates the interaction with the view flow so it
# returns the correct buffer on +yield+. This is usually
- # overwriten by helpers to add more behavior.
+ # overwritten by helpers to add more behavior.
# :api: plugin
def _layout_for(name=nil)
name ||= :layout
view_flow.get(name).html_safe
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/digestor.rb b/actionpack/lib/action_view/digestor.rb
new file mode 100644
index 0000000000..2d7ba856d5
--- /dev/null
+++ b/actionpack/lib/action_view/digestor.rb
@@ -0,0 +1,104 @@
+require 'active_support/core_ext'
+require 'logger'
+
+module ActionView
+ class Digestor
+ EXPLICIT_DEPENDENCY = /# Template Dependency: ([^ ]+)/
+
+ # Matches:
+ # render partial: "comments/comment", collection: commentable.comments
+ # render "comments/comments"
+ # render 'comments/comments'
+ # render('comments/comments')
+ #
+ # render(@topic) => render("topics/topic")
+ # render(topics) => render("topics/topic")
+ # render(message.topics) => render("topics/topic")
+ RENDER_DEPENDENCY = /
+ render\s* # render, followed by optional whitespace
+ \(? # start an optional parenthesis for the render call
+ (partial:|:partial\s+=>)?\s* # naming the partial, used with collection -- 1st capture
+ ([@a-z"'][@a-z_\/\."']+) # the template name itself -- 2nd capture
+ /x
+
+ cattr_accessor(:cache) { Hash.new }
+ cattr_accessor(:logger, instance_reader: true) { ActionView::Base.logger }
+
+ def self.digest(name, format, finder, options = {})
+ cache["#{name}.#{format}"] ||= new(name, format, finder, options).digest
+ end
+
+ attr_reader :name, :format, :finder, :options
+
+ def initialize(name, format, finder, options = {})
+ @name, @format, @finder, @options = name, format, finder, options
+ end
+
+ def digest
+ Digest::MD5.hexdigest("#{source}-#{dependency_digest}").tap do |digest|
+ logger.try :info, "Cache digest for #{name}.#{format}: #{digest}"
+ end
+ rescue ActionView::MissingTemplate
+ logger.try :error, "Couldn't find template for digesting: #{name}.#{format}"
+ ''
+ end
+
+ def dependencies
+ render_dependencies + explicit_dependencies
+ rescue ActionView::MissingTemplate
+ [] # File doesn't exist, so no dependencies
+ end
+
+ def nested_dependencies
+ dependencies.collect do |dependency|
+ dependencies = Digestor.new(dependency, format, finder, partial: true).nested_dependencies
+ dependencies.any? ? { dependency => dependencies } : dependency
+ end
+ end
+
+
+ private
+ def logical_name
+ name.gsub(%r|/_|, "/")
+ end
+
+ def directory
+ name.split("/").first
+ end
+
+ def partial?
+ options[:partial] || name.include?("/_")
+ end
+
+ def source
+ @source ||= finder.find(logical_name, [], partial?, formats: [ format ]).source
+ end
+
+
+ def dependency_digest
+ dependencies.collect do |template_name|
+ Digestor.digest(template_name, format, finder, partial: true)
+ end.join("-")
+ end
+
+ def render_dependencies
+ source.scan(RENDER_DEPENDENCY).
+ collect(&:second).uniq.
+
+ # render(@topic) => render("topics/topic")
+ # render(topics) => render("topics/topic")
+ # render(message.topics) => render("topics/topic")
+ collect { |name| name.sub(/\A@?([a-z]+\.)*([a-z_]+)\z/) { "#{$2.pluralize}/#{$2.singularize}" } }.
+
+ # render("headline") => render("message/headline")
+ collect { |name| name.include?("/") ? name : "#{directory}/#{name}" }.
+
+ # replace quotes from string renders
+ collect { |name| name.gsub(/["']/, "") }
+ end
+
+ def explicit_dependencies
+ source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb
index e27111012d..901f433c70 100644
--- a/actionpack/lib/action_view/helpers/active_model_helper.rb
+++ b/actionpack/lib/action_view/helpers/active_model_helper.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/enumerable'
-require 'active_support/core_ext/object/blank'
module ActionView
# = Active Model Helpers
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index 02c1250c76..db4da6f9c8 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -95,7 +95,7 @@ module ActionView
# have SSL certificates for each of the asset hosts this technique allows you
# to avoid warnings in the client about mixed media.
#
- # ActionController::Base.asset_host = Proc.new { |source, request|
+ # config.action_controller.asset_host = Proc.new { |source, request|
# if request.ssl?
# "#{request.protocol}#{request.host_with_port}"
# else
@@ -209,19 +209,27 @@ module ActionView
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
#
# ==== Examples
- # auto_discovery_link_tag # =>
- # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
- # auto_discovery_link_tag(:atom) # =>
- # <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
- # auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
- # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
- # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
- # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
+ # auto_discovery_link_tag
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
+ # auto_discovery_link_tag(:atom)
+ # # => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
+ # auto_discovery_link_tag(:rss, {:action => "feed"})
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
+ # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"})
+ # # => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
+ # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"})
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
+ # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"})
+ # # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
+ if !(type == :rss || type == :atom) && tag_options[:type].blank?
+ message = "You have passed type other than :rss or :atom to auto_discovery_link_tag and haven't supplied " +
+ "the :type option key. This behavior is deprecated and will be remove in Rails 4.1. You should pass " +
+ ":type option explicitly if you want to use other types, for example: " +
+ "auto_discovery_link_tag(:xml, '/feed.xml', :type => 'application/xml')"
+ ActiveSupport::Deprecation.warn message
+ end
+
tag(
"link",
"rel" => tag_options[:rel] || "alternate",
@@ -360,18 +368,18 @@ module ActionView
# width="30" and height="45". <tt>:size</tt> will be ignored if the
# value is not in the correct format.
#
- # image_tag("icon") # =>
- # <img src="/assets/icon" alt="Icon" />
- # image_tag("icon.png") # =>
- # <img src="/assets/icon.png" alt="Icon" />
- # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
- # <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
- # image_tag("/icons/icon.gif", :size => "16x16") # =>
- # <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
- # image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
- # <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
- # image_tag("/icons/icon.gif", :class => "menu_icon") # =>
- # <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
+ # image_tag("icon")
+ # # => <img src="/assets/icon" alt="Icon" />
+ # image_tag("icon.png")
+ # # => <img src="/assets/icon.png" alt="Icon" />
+ # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry")
+ # # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
+ # image_tag("/icons/icon.gif", :size => "16x16")
+ # # => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
+ # image_tag("/icons/icon.gif", :height => '32', :width => '32')
+ # # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
+ # image_tag("/icons/icon.gif", :class => "menu_icon")
+ # # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
def image_tag(source, options={})
options = options.symbolize_keys
@@ -408,24 +416,24 @@ module ActionView
# width="30" and height="45". <tt>:size</tt> will be ignored if the
# value is not in the correct format.
#
- # video_tag("trailer") # =>
- # <video src="/videos/trailer" />
- # video_tag("trailer.ogg") # =>
- # <video src="/videos/trailer.ogg" />
- # video_tag("trailer.ogg", :controls => true, :autobuffer => true) # =>
- # <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
- # video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png") # =>
- # <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
- # video_tag("/trailers/hd.avi", :size => "16x16") # =>
- # <video src="/trailers/hd.avi" width="16" height="16" />
- # video_tag("/trailers/hd.avi", :height => '32', :width => '32') # =>
- # <video height="32" src="/trailers/hd.avi" width="32" />
- # video_tag("trailer.ogg", "trailer.flv") # =>
- # <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
- # video_tag(["trailer.ogg", "trailer.flv"]) # =>
- # <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
- # video_tag(["trailer.ogg", "trailer.flv"], :size => "160x120") # =>
- # <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag("trailer")
+ # # => <video src="/videos/trailer" />
+ # video_tag("trailer.ogg")
+ # # => <video src="/videos/trailer.ogg" />
+ # video_tag("trailer.ogg", :controls => true, :autobuffer => true)
+ # # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
+ # video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png")
+ # # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
+ # video_tag("/trailers/hd.avi", :size => "16x16")
+ # # => <video src="/trailers/hd.avi" width="16" height="16" />
+ # video_tag("/trailers/hd.avi", :height => '32', :width => '32')
+ # # => <video height="32" src="/trailers/hd.avi" width="32" />
+ # video_tag("trailer.ogg", "trailer.flv")
+ # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag(["trailer.ogg", "trailer.flv"])
+ # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag(["trailer.ogg", "trailer.flv"], :size => "160x120")
+ # # => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
def video_tag(*sources)
multiple_sources_tag('video', sources) do |options|
options[:poster] = path_to_image(options[:poster]) if options[:poster]
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
index 1a54ca2399..e42e49fb04 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/file'
require 'action_view/helpers/tag_helper'
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
index e0dbfe62c6..139f4d19ab 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
require 'active_support/core_ext/file'
require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
@@ -27,7 +26,8 @@ module ActionView
def expand_sources(sources, recursive = false)
if sources.include?(:all)
- all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application'
+ all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application'])
+ add_application_js(all_asset_files, sources)
((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq
else
expanded_sources = sources.inject([]) do |list, source|
@@ -40,7 +40,7 @@ module ActionView
end
def add_application_js(expanded_sources, sources)
- if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}"))
+ if (sources.include?(:defaults) || sources.include?(:all)) && File.exist?(File.join(custom_dir, "application.#{extension}"))
expanded_sources.delete('application')
expanded_sources << "application"
end
@@ -107,8 +107,8 @@ module ActionView
#
# config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js)
#
- # When using <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in
- # <tt>public/javascripts</tt> it will be included as well at the end.
+ # When using <tt>:defaults</tt> or <tt>:all</tt>, if an <tt>application.js</tt> file exists
+ # in <tt>public/javascripts</tt> it will be included as well at the end.
#
# You can modify the HTML attributes of the script tag by passing a hash as the
# last argument.
@@ -134,14 +134,16 @@ module ActionView
# # <script src="/javascripts/rails.js?1284139606"></script>
# # <script src="/javascripts/application.js?1284139606"></script>
#
+ # Note: The application.js file is only referenced if it exists
+ #
# You can also include all JavaScripts in the +javascripts+ directory using <tt>:all</tt> as the source:
#
# javascript_include_tag :all
# # => <script src="/javascripts/jquery.js?1284139606"></script>
# # <script src="/javascripts/rails.js?1284139606"></script>
- # # <script src="/javascripts/application.js?1284139606"></script>
# # <script src="/javascripts/shop.js?1284139606"></script>
# # <script src="/javascripts/checkout.js?1284139606"></script>
+ # # <script src="/javascripts/application.js?1284139606"></script>
#
# Note that your defaults of choice will be included first, so they will be available to all subsequently
# included files.
@@ -162,9 +164,9 @@ module ActionView
# javascript_include_tag :all, :cache => true
# # => <script src="/javascripts/jquery.js?1284139606"></script>
# # <script src="/javascripts/rails.js?1284139606"></script>
- # # <script src="/javascripts/application.js?1284139606"></script>
# # <script src="/javascripts/shop.js?1284139606"></script>
# # <script src="/javascripts/checkout.js?1284139606"></script>
+ # # <script src="/javascripts/application.js?1284139606"></script>
#
# # assuming config.perform_caching is true
# javascript_include_tag :all, :cache => true
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
index 91318b2812..e3a86a8889 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
require 'active_support/core_ext/file'
require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
index 33799d7d71..59e1015976 100644
--- a/actionpack/lib/action_view/helpers/cache_helper.rb
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -8,31 +8,104 @@ module ActionView
# fragments, and so on. This method takes a block that contains
# the content you wish to cache.
#
- # See ActionController::Caching::Fragments for usage instructions.
+ # The best way to use this is by doing key-based cache expiration
+ # on top of a cache store like Memcached that'll automatically
+ # kick out old entries. For more on key-based expiration, see:
+ # http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
#
- # If you want to cache a navigation menu, you can do following:
+ # When using this method, you list the cache dependency as the name of the cache, like so:
#
- # <% cache do %>
- # <%= render :partial => "menu" %>
+ # <% cache project do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
# <% end %>
#
- # You can also cache static content:
+ # This approach will assume that when a new topic is added, you'll touch
+ # the project. The cache key generated from this call will be something like:
#
- # <% cache do %>
- # <p>Hello users! Welcome to our website!</p>
+ # views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9
+ # ^class ^id ^updated_at ^template tree digest
+ #
+ # The cache is thus automatically bumped whenever the project updated_at is touched.
+ #
+ # If your template cache depends on multiple sources (try to avoid this to keep things simple),
+ # you can name all these dependencies as part of an array:
+ #
+ # <% cache [ project, current_user ] do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
# <% end %>
#
- # Static content with embedded ruby content can be cached as
- # well:
+ # This will include both records as part of the cache key and updating either of them will
+ # expire the cache.
+ #
+ # ==== Template digest
+ #
+ # The template digest that's added to the cache key is computed by taking an md5 of the
+ # contents of the entire template file. This ensures that your caches will automatically
+ # expire when you change the template file.
+ #
+ # Note that the md5 is taken of the entire template file, not just what's within the
+ # cache do/end call. So it's possible that changing something outside of that call will
+ # still expire the cache.
+ #
+ # Additionally, the digestor will automatically look through your template file for
+ # explicit and implicit dependencies, and include those as part of the digest.
+ #
+ # ==== Implicit dependencies
#
- # <% cache do %>
- # Topics:
- # <%= render :partial => "topics", :collection => @topic_list %>
- # <i>Topics listed alphabetically</i>
- # <% end %>
+ # Most template dependencies can be derived from calls to render in the template itself.
+ # Here are some examples of render calls that Cache Digests knows how to decode:
+ #
+ # render partial: "comments/comment", collection: commentable.comments
+ # render "comments/comments"
+ # render 'comments/comments'
+ # render('comments/comments')
+ #
+ # render "header" => render("comments/header")
+ #
+ # render(@topic) => render("topics/topic")
+ # render(topics) => render("topics/topic")
+ # render(message.topics) => render("topics/topic")
+ #
+ # It's not possible to derive all render calls like that, though. Here are a few examples of things that can't be derived:
+ #
+ # render group_of_attachments
+ # render @project.documents.where(published: true).order('created_at')
+ #
+ # You will have to rewrite those to the explicit form:
+ #
+ # render partial: 'attachments/attachment', collection: group_of_attachments
+ # render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at')
+ #
+ # === Explicit dependencies
+ #
+ # Some times you'll have template dependencies that can't be derived at all. This is typically
+ # the case when you have template rendering that happens in helpers. Here's an example:
+ #
+ # <%= render_sortable_todolists @project.todolists %>
+ #
+ # You'll need to use a special comment format to call those out:
+ #
+ # <%# Template Dependency: todolists/todolist %>
+ # <%= render_sortable_todolists @project.todolists %>
+ #
+ # The pattern used to match these is /# Template Dependency: ([^ ]+)/, so it's important that you type it out just so.
+ # You can only declare one template dependency per line.
+ #
+ # === External dependencies
+ #
+ # If you use a helper method, for example, inside of a cached block and you then update that helper,
+ # you'll have to bump the cache as well. It doesn't really matter how you do it, but the md5 of the template file
+ # must change. One recommendation is to simply be explicit in a comment, like:
+ #
+ # <%# Helper Dependency Updated: May 6, 2012 at 6pm %>
+ # <%= some_helper_method(person) %>
+ #
+ # Now all you'll have to do is change that timestamp when the helper method changes.
def cache(name = {}, options = nil, &block)
if controller.perform_caching
- safe_concat(fragment_for(name, options, &block))
+ safe_concat(fragment_for(fragment_name_with_digest(name), options, &block))
else
yield
end
@@ -58,6 +131,17 @@ module ActionView
controller.write_fragment(name, fragment, options)
end
end
+
+ def fragment_name_with_digest(name)
+ if @virtual_path
+ [
+ *Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name),
+ Digestor.digest(@virtual_path, formats.last.to_sym, lookup_context)
+ ]
+ else
+ name
+ end
+ end
end
end
end
diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb
index 397738dd98..c98101a195 100644
--- a/actionpack/lib/action_view/helpers/capture_helper.rb
+++ b/actionpack/lib/action_view/helpers/capture_helper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
module ActionView
@@ -134,7 +133,7 @@ module ActionView
#
# <%# Add some other content, or use a different template: %>
#
- # <% content_for :navigation, true do %>
+ # <% content_for :navigation, flush: true do %>
# <li><%= link_to 'Login', :action => 'login' %></li>
# <% end %>
#
@@ -148,14 +147,14 @@ module ActionView
#
# WARNING: content_for is ignored in caches. So you shouldn't use it
# for elements that will be fragment cached.
- def content_for(name, content = nil, flush = false, &block)
+ def content_for(name, content = nil, options = {}, &block)
if content || block_given?
if block_given?
- flush = content if content
+ options = content if content
content = capture(&block)
end
if content
- flush ? @view_flow.set(name, content) : @view_flow.append(name, content)
+ options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
end
nil
else
@@ -213,7 +212,7 @@ module ActionView
# Add the output buffer to the response body and start a new one.
def flush_output_buffer #:nodoc:
if output_buffer && !output_buffer.empty?
- response.body_parts << output_buffer
+ response.stream.write output_buffer
self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0]
nil
end
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index 659aacf6d7..795440cacc 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -140,12 +140,19 @@ module ActionView
# Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
#
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
+ # time_ago_in_words(3.minutes.ago) # => 3 minutes
# time_ago_in_words(Time.now - 15.hours) # => about 15 hours
# time_ago_in_words(Time.now) # => less than a minute
# time_ago_in_words(Time.now, :include_seconds => true) # => less than 5 seconds
#
# from_time = Time.now - 3.days - 14.minutes - 25.seconds
# time_ago_in_words(from_time) # => 3 days
+ #
+ # from_time = (3.days + 14.minutes + 25.seconds).ago
+ # time_ago_in_words(from_time) # => 3 days
+ #
+ # Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>.
+ #
def time_ago_in_words(from_time, include_seconds_or_options = {})
distance_of_time_in_words(from_time, Time.now, include_seconds_or_options)
end
@@ -427,6 +434,9 @@ module ActionView
# # Generate a time select field with hours in the AM/PM format
# select_time(my_time, :ampm => true)
#
+ # # Generates a time select field with hours that range from 2 to 14
+ # select_time(my_time, :start_hour => 2, :end_hour => 14)
+ #
# # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
# select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours
@@ -504,6 +514,9 @@ module ActionView
#
# # Generate a select field for hours in the AM/PM format
# select_hour(my_time, :ampm => true)
+ #
+ # # Generates a select field that includes options for hours from 2 to 14.
+ # select_hour(my_time, :start_hour => 2, :end_hour => 14)
def select_hour(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_hour
end
@@ -734,7 +747,11 @@ module ActionView
if @options[:use_hidden] || @options[:discard_hour]
build_hidden(:hour, hour)
else
- build_options_and_select(:hour, hour, :end => 23, :ampm => @options[:ampm])
+ options = {}
+ options[:ampm] = @options[:ampm] || false
+ options[:start] = @options[:start_hour] || 0
+ options[:end] = @options[:end_hour] || 23
+ build_options_and_select(:hour, hour, options)
end
end
@@ -946,12 +963,15 @@ module ActionView
# build_hidden(:year, 2008)
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
def build_hidden(type, value)
- (tag(:input, {
+ select_options = {
:type => "hidden",
:id => input_id_from_type(type),
:name => input_name_from_type(type),
:value => value
- }.merge(@html_options.slice(:disabled))) + "\n").html_safe
+ }.merge(@html_options.slice(:disabled))
+ select_options.merge!(:disabled => 'disabled') if @options[:disabled]
+
+ tag(:input, select_options) + "\n".html_safe
end
# Returns the name attribute for the input tag.
diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb
index 878a8734a4..d8b92c5cab 100644
--- a/actionpack/lib/action_view/helpers/debug_helper.rb
+++ b/actionpack/lib/action_view/helpers/debug_helper.rb
@@ -4,6 +4,9 @@ module ActionView
# Provides a set of methods for making it easier to debug Rails objects.
module Helpers
module DebugHelper
+
+ include TagHelper
+
# Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
# If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
# Useful for inspecting an object at the time of rendering.
@@ -26,10 +29,11 @@ module ActionView
def debug(object)
begin
Marshal::dump(object)
- "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", "&nbsp; ")}</pre>".html_safe
+ object = ERB::Util.html_escape(object.to_yaml).gsub(" ", "&nbsp; ").html_safe
+ content_tag(:pre, object, :class => "debug_dump")
rescue Exception # errors from Marshal or YAML
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
- "<code class='debug_dump'>#{h(object.inspect)}</code>".html_safe
+ content_tag(:code, object.to_yaml, :class => "debug_dump")
end
end
end
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index b34f6c8650..17fe7dc1b4 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -4,15 +4,12 @@ require 'action_view/helpers/tag_helper'
require 'action_view/helpers/form_tag_helper'
require 'action_view/helpers/active_model_helper'
require 'action_view/helpers/tags'
-require 'active_support/core_ext/class/attribute'
+require 'action_view/model_naming'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/array/extract_options'
-require 'active_support/deprecation'
require 'active_support/core_ext/string/inflections'
-require 'action_controller/model_naming'
module ActionView
# = Action View Form Helpers
@@ -118,7 +115,7 @@ module ActionView
include FormTagHelper
include UrlHelper
- include ActionController::ModelNaming
+ include ModelNaming
# Creates a form that allows the user to create or update the attributes
# of a specific model object.
@@ -326,6 +323,24 @@ module ActionView
# ...
# </form>
#
+ # === Setting HTML options
+ #
+ # You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
+ # the HTML key. Example:
+ #
+ # <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # The HTML generated for this would be:
+ #
+ # <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
+ # <div style='margin:0;padding:0;display:inline'>
+ # <input name='_method' type='hidden' value='put' />
+ # </div>
+ # ...
+ # </form>
+ #
# === Removing hidden model id's
#
# The form_for method automatically includes the model id as a hidden field in the form.
@@ -408,10 +423,12 @@ module ActionView
object = nil
else
object = record.is_a?(Array) ? record.last : record
+ raise ArgumentError, "First argument in form cannot contain nil or be empty" if object.blank?
object_name = options[:as] || model_name_from_record_or_class(object).param_key
apply_form_for_options!(record, object, options)
end
+ options[:html][:data] = options.delete(:data) if options.has_key?(:data)
options[:html][:remote] = options.delete(:remote) if options.has_key?(:remote)
options[:html][:method] = options.delete(:method) if options.has_key?(:method)
options[:html][:authenticity_token] = options.delete(:authenticity_token)
@@ -703,15 +720,15 @@ module ActionView
# label(:post, :title)
# # => <label for="post_title">Title</label>
#
- # You can localize your labels based on model and attribute names.
- # For example you can define the following in your locale (e.g. en.yml)
+ # You can localize your labels based on model and attribute names.
+ # For example you can define the following in your locale (e.g. en.yml)
#
# helpers:
# label:
# post:
# body: "Write your entire text here"
#
- # Which then will result in
+ # Which then will result in
#
# label(:post, :body)
# # => <label for="post_body">Write your entire text here</label>
@@ -1139,7 +1156,7 @@ module ActionView
end
class FormBuilder
- include ActionController::ModelNaming
+ include ModelNaming
# The methods which wrap a form helper call.
class_attribute :field_helpers
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index eef426703d..2bb526a539 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -1,7 +1,6 @@
require 'cgi'
require 'erb'
require 'action_view/helpers/form_helper'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
module ActionView
@@ -353,7 +352,7 @@ module ActionView
html_attributes[:disabled] = 'disabled' if disabled && option_value_selected?(value, disabled)
html_attributes[:value] = value
- content_tag(:option, text, html_attributes)
+ content_tag_string(:option, text, html_attributes)
end.join("\n").html_safe
end
@@ -502,14 +501,14 @@ module ActionView
#
# Possible output:
# <optgroup label="---------">
+ # <option value="US">United States</option>
+ # <option value="Canada">Canada</option>
+ # </optgroup>
+ # <optgroup label="---------">
# <option value="Denmark">Denmark</option>
# <option value="Germany">Germany</option>
# <option value="France">France</option>
# </optgroup>
- # <optgroup label="---------">
- # <option value="US">United States</option>
- # <option value="Canada">Canada</option>
- # </optgroup>
#
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
# wrap the output in an appropriate <tt><select></tt> tag.
@@ -709,9 +708,11 @@ module ActionView
private
def option_html_attributes(element)
- return {} unless Array === element
-
- Hash[element.select { |e| Hash === e }.reduce({}, :merge).map { |k, v| [k, ERB::Util.html_escape(v.to_s)] }]
+ if Array === element
+ element.select { |e| Hash === e }.reduce({}, :merge!)
+ else
+ {}
+ end
end
def option_text_and_value(option)
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 1a0019a48c..f16e33d08d 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -1,13 +1,12 @@
require 'cgi'
require 'action_view/helpers/tag_helper'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/module/attribute_accessors'
module ActionView
# = Action View Form Tag Helpers
module Helpers
- # Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like
+ # Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like
# FormHelper does. Instead, you provide the names and values manually.
#
# NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
@@ -118,7 +117,12 @@ module ActionView
# select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, :disabled => true
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
# # <option>Paris</option><option>Rome</option></select>
+ #
+ # select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
+ # # => <select id="credit_card" name="credit_card"><option>VISA</option>
+ # # <option selected="selected">MasterCard</option></select>
def select_tag(name, option_tags = nil, options = {})
+ option_tags ||= ""
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
if options.delete(:include_blank)
@@ -382,11 +386,18 @@ module ActionView
# Creates a submit button with the text <tt>value</tt> as the caption.
#
# ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
# * <tt>:confirm => 'question?'</tt> - If present the unobtrusive JavaScript
# drivers will provide a prompt with the question specified. If the user accepts,
# the form is processed normally, otherwise no action is taken.
- # * <tt>:disabled</tt> - If true, the user will not be able to use this input.
- # * Any other key creates standard HTML options for the tag.
+ # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
+ # disabled version of the submit button when the form is submitted. This feature is
+ # provided by the unobtrusive JavaScript driver.
#
# ==== Examples
# submit_tag
@@ -407,13 +418,21 @@ module ActionView
# submit_tag "Edit", :class => "edit_button"
# # => <input class="edit_button" name="commit" type="submit" value="Edit" />
#
- # submit_tag "Save", :confirm => "Are you sure?"
+ # submit_tag "Save", :data => { :confirm => "Are you sure?" }
# # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
#
def submit_tag(value = "Save changes", options = {})
options = options.stringify_keys
+ if disable_with = options.delete("disable_with")
+ ActiveSupport::Deprecation.warn ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead"
+
+ options["data-disable-with"] = disable_with
+ end
+
if confirm = options.delete("confirm")
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead'"
+
options["data-confirm"] = confirm
end
@@ -428,13 +447,21 @@ module ActionView
# so this helper will also accept a block.
#
# ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If true, the user will not be able to
+ # use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
# * <tt>:confirm => 'question?'</tt> - If present, the
# unobtrusive JavaScript drivers will provide a prompt with
# the question specified. If the user accepts, the form is
# processed normally, otherwise no action is taken.
- # * <tt>:disabled</tt> - If true, the user will not be able to
- # use this input.
- # * Any other key creates standard HTML options for the tag.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
#
# ==== Examples
# button_tag
@@ -447,12 +474,23 @@ module ActionView
# # <strong>Ask me!</strong>
# # </button>
#
+ # button_tag "Checkout", :data => { disable_with => "Please wait..." }
+ # # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
+ #
def button_tag(content_or_options = nil, options = nil, &block)
options = content_or_options if block_given? && content_or_options.is_a?(Hash)
options ||= {}
options = options.stringify_keys
+ if disable_with = options.delete("disable_with")
+ ActiveSupport::Deprecation.warn ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead"
+
+ options["data-disable-with"] = disable_with
+ end
+
if confirm = options.delete("confirm")
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead'"
+
options["data-confirm"] = confirm
end
@@ -466,11 +504,15 @@ module ActionView
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
#
# ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
# * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm
# prompt with the question specified. If the user accepts, the form is
# processed normally, otherwise no action is taken.
- # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
- # * Any other key creates standard HTML options for the tag.
#
# ==== Examples
# image_submit_tag("login.png")
@@ -485,12 +527,14 @@ module ActionView
# image_submit_tag("agree.png", :disabled => true, :class => "agree_disagree_button")
# # => <input class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
#
- # image_submit_tag("save.png", :confirm => "Are you sure?")
+ # image_submit_tag("save.png", :data => { :confirm => "Are you sure?" })
# # => <input src="/images/save.png" data-confirm="Are you sure?" type="image" />
def image_submit_tag(source, options = {})
options = options.stringify_keys
if confirm = options.delete("confirm")
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead'"
+
options["data-confirm"] = confirm
end
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
index cc20518b93..9f8cd8caaa 100644
--- a/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -67,6 +67,46 @@ module ActionView
def javascript_cdata_section(content) #:nodoc:
"\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
end
+
+ # Returns a button whose +onclick+ handler triggers the passed JavaScript.
+ #
+ # The helper receives a name, JavaScript code, and an optional hash of HTML options. The
+ # name is used as button label and the JavaScript code goes into its +onclick+ attribute.
+ # If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+.
+ #
+ # button_to_function "Greeting", "alert('Hello world!')", :class => "ok"
+ # # => <input class="ok" onclick="alert('Hello world!');" type="button" value="Greeting" />
+ #
+ def button_to_function(name, function=nil, html_options={})
+ message = "button_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead."
+ ActiveSupport::Deprecation.warn message
+
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
+
+ tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick))
+ end
+
+ # Returns a link whose +onclick+ handler triggers the passed JavaScript.
+ #
+ # The helper receives a name, JavaScript code, and an optional hash of HTML options. The
+ # name is used as the link text and the JavaScript code goes into the +onclick+ attribute.
+ # If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+. Once all
+ # the JavaScript is set, the helper appends "; return false;".
+ #
+ # The +href+ attribute of the tag is set to "#" unless +html_options+ has one.
+ #
+ # link_to_function "Greeting", "alert('Hello world!')", :class => "nav_link"
+ # # => <a class="nav_link" href="#" onclick="alert('Hello world!'); return false;">Greeting</a>
+ #
+ def link_to_function(name, function, html_options={})
+ message = "link_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead."
+ ActiveSupport::Deprecation.warn message
+
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;"
+ href = html_options[:href] || '#'
+
+ content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick))
+ end
end
end
end
diff --git a/actionpack/lib/action_view/helpers/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb
index 9b35f076e5..dded9aab7c 100644
--- a/actionpack/lib/action_view/helpers/record_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb
@@ -1,10 +1,8 @@
-require 'action_controller/record_identifier'
-
module ActionView
# = Action View Record Tag Helpers
module Helpers
module RecordTagHelper
- include ActionController::RecordIdentifier
+ include ActionView::RecordIdentifier
# Produces a wrapper DIV element with id and class parameters that
# relate to the specified Active Record object. Usage example:
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
index a727b910e5..9c76c26ace 100644
--- a/actionpack/lib/action_view/helpers/sanitize_helper.rb
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -1,5 +1,5 @@
require 'active_support/core_ext/object/try'
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
module ActionView
# = Action View Sanitize Helpers
@@ -78,7 +78,7 @@ module ActionView
# strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# # => Welcome to my website!
def strip_tags(html)
- self.class.full_sanitizer.sanitize(html).try(:html_safe)
+ self.class.full_sanitizer.sanitize(html)
end
# Strips all link tags from +text+ leaving just the link text.
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
index 9572f1c192..3327c69d61 100644
--- a/actionpack/lib/action_view/helpers/tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
require 'set'
diff --git a/actionpack/lib/action_view/helpers/tags/base.rb b/actionpack/lib/action_view/helpers/tags/base.rb
index e077cd5b3c..192f5eebaa 100644
--- a/actionpack/lib/action_view/helpers/tags/base.rb
+++ b/actionpack/lib/action_view/helpers/tags/base.rb
@@ -137,10 +137,10 @@ module ActionView
def add_options(option_tags, options, value = nil)
if options[:include_blank]
- option_tags = content_tag('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
+ option_tags = content_tag_string('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
end
if value.blank? && options[:prompt]
- option_tags = content_tag('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
+ option_tags = content_tag_string('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
end
option_tags
end
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 0cc0d069ea..0f599d5f41 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/filters'
require 'active_support/core_ext/array/extract_options'
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index 736f9fa2f0..3f65791aa0 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -2,7 +2,6 @@ require 'action_view/helpers/javascript_helper'
require 'active_support/core_ext/array/access'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/string/output_safety'
-require 'action_dispatch'
module ActionView
# = Action View URL Helpers
@@ -20,103 +19,34 @@ module ActionView
extend ActiveSupport::Concern
- include ActionDispatch::Routing::UrlFor
include TagHelper
- # We need to override url_options, _routes_context
- # and optimize_routes_generation? to consider the controller.
-
- def url_options #:nodoc:
- return super unless controller.respond_to?(:url_options)
- controller.url_options
- end
-
- def _routes_context #:nodoc:
- controller
- end
- protected :_routes_context
-
- def optimize_routes_generation? #:nodoc:
- controller.respond_to?(:optimize_routes_generation?) ?
- controller.optimize_routes_generation? : super
+ module ClassMethods
+ def _url_for_modules
+ ActionView::RoutingUrlFor
+ end
end
- protected :optimize_routes_generation?
- # Returns the URL for the set of +options+ provided. This takes the
- # same options as +url_for+ in Action Controller (see the
- # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
- # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
- # instead of the fully qualified URL like "http://example.com/controller/action".
- #
- # ==== Options
- # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
- # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
- # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
- # is currently not recommended since it breaks caching.
- # * <tt>:host</tt> - Overrides the default (current) host if provided.
- # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
- # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
- # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
- #
- # ==== Relying on named routes
- #
- # Passing a record (like an Active Record) instead of a Hash as the options parameter will
- # trigger the named route for that record. The lookup will happen on the name of the class. So passing a
- # Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
- # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
- #
- # ==== Examples
- # <%= url_for(:action => 'index') %>
- # # => /blog/
- #
- # <%= url_for(:action => 'find', :controller => 'books') %>
- # # => /books/find
- #
- # <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %>
- # # => https://www.example.com/members/login/
- #
- # <%= url_for(:action => 'play', :anchor => 'player') %>
- # # => /messages/play/#player
- #
- # <%= url_for(:action => 'jump', :anchor => 'tax&ship') %>
- # # => /testing/jump/#tax&ship
- #
- # <%= url_for(Workshop.new) %>
- # # relies on Workshop answering a persisted? call (and in this case returning false)
- # # => /workshops
- #
- # <%= url_for(@workshop) %>
- # # calls @workshop.to_param which by default returns the id
- # # => /workshops/5
- #
- # # to_param can be re-defined in a model to provide different URL names:
- # # => /workshops/1-workshop-name
- #
- # <%= url_for("http://www.example.com") %>
- # # => http://www.example.com
- #
- # <%= url_for(:back) %>
- # # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
- # # => http://www.example.com
- #
- # <%= url_for(:back) %>
- # # if request.env["HTTP_REFERER"] is not set or is blank
- # # => javascript:history.back()
- def url_for(options = nil)
+ # Basic implementation of url_for to allow use helpers without routes existence
+ def url_for(options = nil) # :nodoc:
case options
when String
options
- when nil, Hash
- options ||= {}
- options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys)
- super
when :back
- controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
+ _back_url
else
- polymorphic_path(options)
+ raise ArgumentError, "arguments passed to url_for can't be handled. Please require " +
+ "routes or provide your own implementation"
end
end
+ def _back_url # :nodoc:
+ referrer = controller.respond_to?(:request) && controller.request.env["HTTP_REFERER"]
+ referrer || 'javascript:history.back()'
+ end
+ protected :_back_url
+
+
# Creates a link tag of the given +name+ using a URL created by the set of +options+.
# See the valid options in the documentation for +url_for+. It's also possible to
# pass a String instead of an options hash, which generates a link tag that uses the
@@ -132,8 +62,7 @@ module ActionView
# # posts_path
#
# link_to(body, url_options = {}, html_options = {})
- # # url_options, except :confirm or :method,
- # # is passed to url_for
+ # # url_options, except :method, is passed to url_for
#
# link_to(options = {}, html_options = {}) do
# # name
@@ -144,9 +73,7 @@ module ActionView
# end
#
# ==== Options
- # * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
- # driver to prompt with the question specified. If the user accepts, the link is
- # processed normally, otherwise no action is taken.
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
# * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
# create an HTML form and immediately submit the form for processing using
# the HTTP verb specified. Useful for having links perform a POST operation
@@ -163,6 +90,16 @@ module ActionView
# completion of the Ajax request and performing JavaScript operations once
# they're complete
#
+ # ==== Data attributes
+ #
+ # * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
+ # driver to prompt with the question specified. If the user accepts, the link is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
# ==== Examples
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
@@ -226,13 +163,15 @@ module ActionView
# link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
# # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>
#
- # The two options specific to +link_to+ (<tt>:confirm</tt> and <tt>:method</tt>) are used as follows:
+ # The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
#
- # link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
- # # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
+ # link_to("Destroy", "http://www.example.com", :method => :delete)
+ # # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
#
- # link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")
- # # => <a href='http://www.example.com' rel="nofollow" data-method="delete" data-confirm="Are you sure?">Destroy</a>
+ # You can also use custom data attributes using the <tt>:data</tt> option:
+ #
+ # link_to "Visit Other Site", "http://www.rubyonrails.org/", :data => { :confirm => "Are you sure?" }
+ # # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
def link_to(name = nil, options = nil, html_options = nil, &block)
html_options, options = options, name if block_given?
options ||= {}
@@ -255,10 +194,9 @@ module ActionView
# to allow styling of the form itself and its children. This can be changed
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
# the form submission and input element behavior using +html_options+.
- # This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
- # described in the +link_to+ documentation. If no <tt>:method</tt> modifier
- # is given, it will default to performing a POST operation. You can also
- # disable the button by passing <tt>:disabled => true</tt> in +html_options+.
+ # This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
+ # If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
+ # You can also disable the button by passing <tt>:disabled => true</tt> in +html_options+.
# If you are using RESTful routes, you can pass the <tt>:method</tt>
# to change the HTTP verb used to submit the form.
#
@@ -269,15 +207,23 @@ module ActionView
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
# <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
- # * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
- # prompt with the question specified. If the user accepts, the link is
- # processed normally, otherwise no action is taken.
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behavior. By default this behavior is an ajax submit.
# * <tt>:form</tt> - This hash will be form attributes
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
# be placed
#
+ # ==== Data attributes
+ #
+ # * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
+ # prompt with the question specified. If the user accepts, the link is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
# ==== Examples
# <%= button_to "New", :action => "new" %>
# # => "<form method="post" action="/controller/new" class="button_to">
@@ -311,7 +257,7 @@ module ActionView
#
#
# <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
- # :confirm => "Are you sure?", :method => :delete %>
+ # :method => :delete, :data => { :confirm => "Are you sure?" } %>
# # => "<form method="post" action="/images/delete/1" class="button_to">
# # <div>
# # <input type="hidden" name="_method" value="delete" />
@@ -321,12 +267,12 @@ module ActionView
# # </form>"
#
#
- # <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
- # :method => "delete", :remote => true) %>
+ # <%= button_to('Destroy', 'http://www.example.com',
+ # :method => "delete", :remote => true, :data => { :confirm' => 'Are you sure?', :disable_with => 'loading...' }) %>
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
# # <div>
# # <input name='_method' value='delete' type='hidden' />
- # # <input value='Destroy' type='submit' data-confirm='Are you sure?' />
+ # # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
# # </div>
# # </form>"
@@ -627,12 +573,24 @@ module ActionView
html_options = html_options.stringify_keys
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
+ disable_with = html_options.delete("disable_with")
confirm = html_options.delete('confirm')
method = html_options.delete('method')
- html_options["data-confirm"] = confirm if confirm
+ if confirm
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead"
+
+ html_options["data-confirm"] = confirm
+ end
+
add_method_to_attributes!(html_options, method) if method
+ if disable_with
+ ActiveSupport::Deprecation.warn ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead"
+
+ html_options["data-disable-with"] = disable_with
+ end
+
html_options
else
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index 00989ec405..af367ac28d 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/remove_method'
module ActionView
@@ -44,7 +43,7 @@ module ActionView
end
register_detail(:locale) { [I18n.locale, I18n.default_locale].uniq }
- register_detail(:formats) { Mime::SET.symbols }
+ register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] }
register_detail(:handlers){ Template::Handlers.extensions }
class DetailsKey #:nodoc:
@@ -96,7 +95,7 @@ module ActionView
# Helpers related to template lookup using the lookup context information.
module ViewPaths
- attr_reader :view_paths
+ attr_reader :view_paths, :html_fallback_for_js
# Whenever setting view paths, makes a copy so we can manipulate then in
# instance objects as we wish.
@@ -184,7 +183,10 @@ module ActionView
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*"
- values << :html if values == [:js]
+ if values == [:js]
+ values << :html
+ @html_fallback_for_js = true
+ end
end
super(values)
end
diff --git a/actionpack/lib/action_view/model_naming.rb b/actionpack/lib/action_view/model_naming.rb
new file mode 100644
index 0000000000..e09ebd60df
--- /dev/null
+++ b/actionpack/lib/action_view/model_naming.rb
@@ -0,0 +1,12 @@
+module ActionView
+ module ModelNaming
+ # Converts the given object to an ActiveModel compliant one.
+ def convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
+
+ def model_name_from_record_or_class(record_or_class)
+ (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
index 9f5e3be454..2d36deaa78 100644
--- a/actionpack/lib/action_view/railtie.rb
+++ b/actionpack/lib/action_view/railtie.rb
@@ -9,6 +9,8 @@ module ActionView
config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) }
config.action_view.embed_authenticity_token_in_remote_forms = false
+ config.eager_load_namespaces << ActionView
+
initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
ActiveSupport.on_load(:action_view) do
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
diff --git a/actionpack/lib/action_view/record_identifier.rb b/actionpack/lib/action_view/record_identifier.rb
new file mode 100644
index 0000000000..2953654972
--- /dev/null
+++ b/actionpack/lib/action_view/record_identifier.rb
@@ -0,0 +1,84 @@
+require 'active_support/core_ext/module'
+require 'action_view/model_naming'
+
+module ActionView
+ # The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
+ # pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to
+ # a higher logical level.
+ #
+ # # routes
+ # resources :posts
+ #
+ # # view
+ # <%= div_for(post) do %> <div id="post_45" class="post">
+ # <%= post.body %> What a wonderful world!
+ # <% end %> </div>
+ #
+ # # controller
+ # def update
+ # post = Post.find(params[:id])
+ # post.update_attributes(params[:post])
+ #
+ # redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
+ # end
+ #
+ # As the example above shows, you can stop caring to a large extent what the actual id of the post is.
+ # You just know that one is being assigned and that the subsequent calls in redirect_to expect that
+ # same naming convention and allows you to write less code if you follow it.
+ module RecordIdentifier
+ extend self
+ extend ModelNaming
+
+ include ModelNaming
+
+ JOIN = '_'.freeze
+ NEW = 'new'.freeze
+
+ # The DOM class convention is to use the singular form of an object or class.
+ #
+ # dom_class(post) # => "post"
+ # dom_class(Person) # => "person"
+ #
+ # If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
+ #
+ # dom_class(post, :edit) # => "edit_post"
+ # dom_class(Person, :edit) # => "edit_person"
+ def dom_class(record_or_class, prefix = nil)
+ singular = model_name_from_record_or_class(record_or_class).param_key
+ prefix ? "#{prefix}#{JOIN}#{singular}" : singular
+ end
+
+ # The DOM id convention is to use the singular form of an object or class with the id following an underscore.
+ # If no id is found, prefix with "new_" instead.
+ #
+ # dom_id(Post.find(45)) # => "post_45"
+ # dom_id(Post.new) # => "new_post"
+ #
+ # If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
+ #
+ # dom_id(Post.find(45), :edit) # => "edit_post_45"
+ # dom_id(Post.new, :custom) # => "custom_post"
+ def dom_id(record, prefix = nil)
+ if record_id = record_key_for_dom_id(record)
+ "#{dom_class(record, prefix)}#{JOIN}#{record_id}"
+ else
+ dom_class(record, prefix || NEW)
+ end
+ end
+
+ protected
+
+ # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
+ # This can be overwritten to customize the default generated string representation if desired.
+ # If you need to read back a key from a dom_id in order to query for the underlying database record,
+ # you should write a helper like 'person_record_from_dom_id' that will extract the key either based
+ # on the default implementation (which just joins all key attributes with '_') or on your own
+ # overwritten version of the method. By default, this implementation passes the key string through a
+ # method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
+ # make sure yourself that your dom ids are valid, in case you overwrite this method.
+ def record_key_for_dom_id(record)
+ key = convert_to_model(record).to_key
+ key ? key.join('_') : key
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/renderer/abstract_renderer.rb b/actionpack/lib/action_view/renderer/abstract_renderer.rb
index e3d8e9d508..6fb8cbb46c 100644
--- a/actionpack/lib/action_view/renderer/abstract_renderer.rb
+++ b/actionpack/lib/action_view/renderer/abstract_renderer.rb
@@ -22,5 +22,11 @@ module ActionView
def instrument(name, options={})
ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
end
+
+ def prepend_formats(formats)
+ formats = Array(formats)
+ return if formats.empty? || @lookup_context.html_fallback_for_js
+ @lookup_context.formats = formats | @lookup_context.formats
+ end
end
end
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
index 9100545718..edefeac184 100644
--- a/actionpack/lib/action_view/renderer/partial_renderer.rb
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActionView
# = Action View Partials
@@ -320,6 +319,8 @@ module ActionView
@block = block
@details = extract_details(options)
+ prepend_formats(options[:formats])
+
if String === partial
@object = options[:object]
@path = partial
@@ -335,17 +336,16 @@ module ActionView
end
end
+ if as = options[:as]
+ raise_invalid_identifier(as) unless as.to_s =~ /\A[a-z_]\w*\z/
+ as = as.to_sym
+ end
+
if @path
- @variable, @variable_counter = retrieve_variable(@path)
+ @variable, @variable_counter = retrieve_variable(@path, as)
@template_keys = retrieve_template_keys
else
- paths.map! { |path| retrieve_variable(path).unshift(path) }
- end
-
- if String === partial && @variable.to_s !~ /^[a-z_][a-zA-Z_0-9]*$/
- raise ArgumentError.new("The partial name (#{partial}) is not a valid Ruby identifier; " +
- "make sure your partial name starts with a lowercase letter or underscore, " +
- "and is followed by any combination of letters, numbers and underscores.")
+ paths.map! { |path| retrieve_variable(path, as).unshift(path) }
end
self
@@ -454,10 +454,22 @@ module ActionView
keys
end
- def retrieve_variable(path)
- variable = @options.fetch(:as) { path[%r'_?(\w+)(\.\w+)*$', 1] }.try(:to_sym)
+ def retrieve_variable(path, as)
+ variable = as || begin
+ base = path[-1] == "/" ? "" : File.basename(path)
+ raise_invalid_identifier(path) unless base =~ /\A_?([a-z]\w*)(\.\w+)*\z/
+ $1.to_sym
+ end
variable_counter = :"#{variable}_counter" if @collection
[variable, variable_counter]
end
+
+ IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores."
+
+ def raise_invalid_identifier(path)
+ raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path))
+ end
end
end
diff --git a/actionpack/lib/action_view/renderer/streaming_template_renderer.rb b/actionpack/lib/action_view/renderer/streaming_template_renderer.rb
index f46aabd2be..9cf6eb0c65 100644
--- a/actionpack/lib/action_view/renderer/streaming_template_renderer.rb
+++ b/actionpack/lib/action_view/renderer/streaming_template_renderer.rb
@@ -30,7 +30,7 @@ module ActionView
# This is the same logging logic as in ShowExceptions middleware.
# TODO Once "exceptron" is in, refactor this piece to simply re-use exceptron.
def log_error(exception) #:nodoc:
- logger = ActionController::Base.logger
+ logger = ActionView::Base.logger
return unless logger
message = "\n#{exception.class} (#{exception.message}):\n"
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
index 3c1b11396a..156ad4e547 100644
--- a/actionpack/lib/action_view/renderer/template_renderer.rb
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -8,9 +8,10 @@ module ActionView
template = determine_template(options)
context = @lookup_context
+ prepend_formats(template.formats)
+
unless context.rendered_format
- context.formats = template.formats unless template.formats.empty?
- context.rendered_format = context.formats.first
+ context.rendered_format = template.formats.first || formats.last
end
render_template(template, options[:layout], options[:locals])
diff --git a/actionpack/lib/action_view/routing_url_for.rb b/actionpack/lib/action_view/routing_url_for.rb
new file mode 100644
index 0000000000..13fb6406e1
--- /dev/null
+++ b/actionpack/lib/action_view/routing_url_for.rb
@@ -0,0 +1,107 @@
+module ActionView
+ module RoutingUrlFor
+
+ # Returns the URL for the set of +options+ provided. This takes the
+ # same options as +url_for+ in Action Controller (see the
+ # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
+ # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
+ # instead of the fully qualified URL like "http://example.com/controller/action".
+ #
+ # ==== Options
+ # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
+ # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
+ # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
+ # is currently not recommended since it breaks caching.
+ # * <tt>:host</tt> - Overrides the default (current) host if provided.
+ # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
+ # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
+ # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
+ #
+ # ==== Relying on named routes
+ #
+ # Passing a record (like an Active Record) instead of a hash as the options parameter will
+ # trigger the named route for that record. The lookup will happen on the name of the class. So passing a
+ # Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
+ # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
+ #
+ # ==== Implicit Controller Namespacing
+ #
+ # Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one.
+ #
+ # ==== Examples
+ # <%= url_for(:action => 'index') %>
+ # # => /blog/
+ #
+ # <%= url_for(:action => 'find', :controller => 'books') %>
+ # # => /books/find
+ #
+ # <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %>
+ # # => https://www.example.com/members/login/
+ #
+ # <%= url_for(:action => 'play', :anchor => 'player') %>
+ # # => /messages/play/#player
+ #
+ # <%= url_for(:action => 'jump', :anchor => 'tax&ship') %>
+ # # => /testing/jump/#tax&ship
+ #
+ # <%= url_for(Workshop.new) %>
+ # # relies on Workshop answering a persisted? call (and in this case returning false)
+ # # => /workshops
+ #
+ # <%= url_for(@workshop) %>
+ # # calls @workshop.to_param which by default returns the id
+ # # => /workshops/5
+ #
+ # # to_param can be re-defined in a model to provide different URL names:
+ # # => /workshops/1-workshop-name
+ #
+ # <%= url_for("http://www.example.com") %>
+ # # => http://www.example.com
+ #
+ # <%= url_for(:back) %>
+ # # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
+ # # => http://www.example.com
+ #
+ # <%= url_for(:back) %>
+ # # if request.env["HTTP_REFERER"] is not set or is blank
+ # # => javascript:history.back()
+ #
+ # <%= url_for(:action => 'index', :controller => 'users') %>
+ # # Assuming an "admin" namespace
+ # # => /admin/users
+ #
+ # <%= url_for(:action => 'index', :controller => '/users') %>
+ # # Specify absolute path with beginning slash
+ # # => /users
+ def url_for(options = nil)
+ case options
+ when String
+ options
+ when nil, Hash
+ options ||= {}
+ options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys)
+ super
+ when :back
+ _back_url
+ else
+ polymorphic_path(options)
+ end
+ end
+
+ def url_options #:nodoc:
+ return super unless controller.respond_to?(:url_options)
+ controller.url_options
+ end
+
+ def _routes_context #:nodoc:
+ controller
+ end
+ protected :_routes_context
+
+ def optimize_routes_generation? #:nodoc:
+ controller.respond_to?(:optimize_routes_generation?) ?
+ controller.optimize_routes_generation? : super
+ end
+ protected :optimize_routes_generation?
+ end
+end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index cd79468502..379cdc8a25 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -1,6 +1,6 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/deprecation'
require 'thread'
module ActionView
@@ -93,6 +93,7 @@ module ActionView
autoload :Error
autoload :Handlers
autoload :Text
+ autoload :Types
end
extend Template::Handlers
@@ -122,7 +123,7 @@ module ActionView
@locals = details[:locals] || []
@virtual_path = details[:virtual_path]
@updated_at = details[:updated_at] || Time.now
- @formats = Array(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f }
+ @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f }
@compile_mutex = Mutex.new
end
@@ -148,9 +149,14 @@ module ActionView
end
def mime_type
+ ActiveSupport::Deprecation.warn 'Template#mime_type is deprecated and will be removed in Rails 4.1. Please use type method instead.'
@mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
end
+ def type
+ @type ||= Types[@formats.first] if @formats.first
+ end
+
# Receives a view object and return a template similar to self by using @virtual_path.
#
# This method is useful if you have a template object but it does not contain its source
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index d8258f7b11..e00056781d 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -8,6 +8,9 @@ module ActionView
class EncodingError < StandardError #:nodoc:
end
+ class MissingRequestError < StandardError #:nodoc:
+ end
+
class WrongEncodingError < EncodingError #:nodoc:
def initialize(string, encoding)
@string, @encoding = string, encoding
@@ -84,13 +87,13 @@ module ActionView
start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
- indent = ' ' * indentation
+ indent = end_on_line.to_s.size + indentation
line_counter = start_on_line
return unless source_code = source_code[start_on_line..end_on_line]
source_code.sum do |line|
line_counter += 1
- "#{indent}#{line_counter}: #{line}\n"
+ "%#{indent}s: %s\n" % [line_counter, line]
end
end
diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb
index 34397c3bcf..d90b0c6378 100644
--- a/actionpack/lib/action_view/template/handlers/builder.rb
+++ b/actionpack/lib/action_view/template/handlers/builder.rb
@@ -3,7 +3,7 @@ module ActionView
class Builder
# Default format used by Builder.
class_attribute :default_format
- self.default_format = Mime::XML
+ self.default_format = :xml
def call(template)
require_engine
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb
index 19b9112afd..aa8eac7846 100644
--- a/actionpack/lib/action_view/template/handlers/erb.rb
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -1,5 +1,4 @@
require 'action_dispatch/http/mime_type'
-require 'active_support/core_ext/class/attribute'
require 'erubis'
module ActionView
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index 2bb656fac9..25c6fd4aa8 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -235,7 +235,7 @@ module ActionView
extension = pieces.pop
ActiveSupport::Deprecation.warn "The file #{path} did not specify a template handler. The default is currently ERB, but will change to RAW in the future." unless extension
handler = Template.handler_for_extension(extension)
- format = pieces.last && Mime[pieces.last]
+ format = pieces.last && Template::Types[pieces.last]
[handler, format]
end
end
diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb
index 3af76dfcdb..859c7bc3ce 100644
--- a/actionpack/lib/action_view/template/text.rb
+++ b/actionpack/lib/action_view/template/text.rb
@@ -2,12 +2,12 @@ module ActionView #:nodoc:
# = Action View Text Template
class Template
class Text #:nodoc:
- attr_accessor :mime_type
+ attr_accessor :type
- def initialize(string, mime_type = nil)
- @string = string.to_s
- @mime_type = Mime[mime_type] || mime_type if mime_type
- @mime_type ||= Mime::TEXT
+ def initialize(string, type = nil)
+ @string = string.to_s
+ @type = Types[type] || type if type
+ @type ||= Types[:text]
end
def identifier
@@ -27,7 +27,7 @@ module ActionView #:nodoc:
end
def formats
- [@mime_type.to_sym]
+ [@type.to_sym]
end
end
end
diff --git a/actionpack/lib/action_view/template/types.rb b/actionpack/lib/action_view/template/types.rb
new file mode 100644
index 0000000000..7611c9e708
--- /dev/null
+++ b/actionpack/lib/action_view/template/types.rb
@@ -0,0 +1,58 @@
+require 'set'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/object/blank'
+
+module ActionView
+ class Template
+ class Types
+ class Type
+ cattr_accessor :types
+ self.types = Set.new
+
+ def self.register(*t)
+ types.merge(t.map { |type| type.to_s })
+ end
+
+ register :html, :text, :js, :css, :xml, :json
+
+ def self.[](type)
+ return type if type.is_a?(self)
+
+ if type.is_a?(Symbol) || types.member?(type.to_s)
+ new(type)
+ end
+ end
+
+ attr_reader :symbol
+
+ def initialize(symbol)
+ @symbol = symbol.to_sym
+ end
+
+ delegate :to_s, :to_sym, :to => :symbol
+ alias to_str to_s
+
+ def ref
+ to_sym || to_s
+ end
+
+ def ==(type)
+ return false if type.blank?
+ symbol.to_sym == type.to_sym
+ end
+ end
+
+ cattr_accessor :type_klass
+
+ def self.delegate_to(klass)
+ self.type_klass = klass
+ end
+
+ delegate_to Type
+
+ def self.[](type)
+ type_klass[type]
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index 53bde48e4d..434fc8cc14 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/remove_method'
require 'action_controller'
require 'action_controller/test_case'
@@ -40,10 +38,11 @@ module ActionView
include ActionView::Context
include ActionDispatch::Routing::PolymorphicRoutes
- include ActionController::RecordIdentifier
include AbstractController::Helpers
include ActionView::Helpers
+ include ActionView::RecordIdentifier
+ include ActionView::RoutingUrlFor
delegate :lookup_context, :to => :controller
attr_accessor :controller, :output_buffer, :rendered
diff --git a/actionpack/lib/action_view/vendor/html-scanner.rb b/actionpack/lib/action_view/vendor/html-scanner.rb
new file mode 100644
index 0000000000..879b31e60e
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner.rb
@@ -0,0 +1,20 @@
+$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner"
+
+module HTML
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :CDATA, 'html/node'
+ autoload :Document, 'html/document'
+ autoload :FullSanitizer, 'html/sanitizer'
+ autoload :LinkSanitizer, 'html/sanitizer'
+ autoload :Node, 'html/node'
+ autoload :Sanitizer, 'html/sanitizer'
+ autoload :Selector, 'html/selector'
+ autoload :Tag, 'html/node'
+ autoload :Text, 'html/node'
+ autoload :Tokenizer, 'html/tokenizer'
+ autoload :Version, 'html/version'
+ autoload :WhiteListSanitizer, 'html/sanitizer'
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb b/actionpack/lib/action_view/vendor/html-scanner/html/document.rb
index 386820300a..386820300a 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/document.rb
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb b/actionpack/lib/action_view/vendor/html-scanner/html/node.rb
index 4e1f016431..4e1f016431 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/node.rb
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb
index 6b269e7a31..6b4ececda2 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb
@@ -1,6 +1,5 @@
require 'set'
require 'cgi'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
module HTML
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb b/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb
index 1eadfc0390..1eadfc0390 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb b/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb
index 8ac8d34430..8ac8d34430 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb b/actionpack/lib/action_view/vendor/html-scanner/html/version.rb
index 6d645c3e14..6d645c3e14 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/version.rb
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb
index 0194ee943f..99064a8b87 100644
--- a/actionpack/test/abstract/translation_test.rb
+++ b/actionpack/test/abstract/translation_test.rb
@@ -23,4 +23,17 @@ class TranslationControllerTest < ActiveSupport::TestCase
def test_action_controller_base_responds_to_l
assert_respond_to @controller, :l
end
+
+ def test_lazy_lookup
+ expected = 'bar'
+ @controller.stubs(:action_name => :index)
+ I18n.stubs(:translate).with('action_controller.base.index.foo').returns(expected)
+ assert_equal expected, @controller.t('.foo')
+ end
+
+ def test_default_translation
+ key, expected = 'one.two' 'bar'
+ I18n.stubs(:translate).with(key).returns(expected)
+ assert_equal expected, @controller.t(key)
+ end
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 37deb9c98a..4f5b2895c9 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -85,39 +85,28 @@ module RenderERBUtils
end
end
-module SetupOnce
- extend ActiveSupport::Concern
-
- included do
- cattr_accessor :setup_once_block
- self.setup_once_block = nil
-
- setup :run_setup_once
- end
+SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
- module ClassMethods
- def setup_once(&block)
- self.setup_once_block = block
+module ActionDispatch
+ module SharedRoutes
+ def before_setup
+ @routes = SharedTestRoutes
+ super
end
end
- private
- def run_setup_once
- if self.setup_once_block
- self.setup_once_block.call
- self.setup_once_block = nil
- end
+ # Hold off drawing routes until all the possible controller classes
+ # have been loaded.
+ module DrawOnce
+ class << self
+ attr_accessor :drew
end
-end
+ self.drew = false
-SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
+ def before_setup
+ super
+ return if DrawOnce.drew
-module ActiveSupport
- class TestCase
- include SetupOnce
- # Hold off drawing routes until all the possible controller classes
- # have been loaded.
- setup_once do
SharedTestRoutes.draw do
get ':controller(/:action)'
end
@@ -125,10 +114,18 @@ module ActiveSupport
ActionDispatch::IntegrationTest.app.routes.draw do
get ':controller(/:action)'
end
+
+ DrawOnce.drew = true
end
end
end
+module ActiveSupport
+ class TestCase
+ include ActionDispatch::DrawOnce
+ end
+end
+
class RoutedRackApp
attr_reader :routes
@@ -159,9 +156,7 @@ class BasicController
end
class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
- setup do
- @routes = SharedTestRoutes
- end
+ include ActionDispatch::SharedRoutes
def self.build_app(routes = nil)
RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware|
@@ -171,7 +166,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
middleware.use "ActionDispatch::ParamsParser"
middleware.use "ActionDispatch::Cookies"
middleware.use "ActionDispatch::Flash"
- middleware.use "ActionDispatch::Head"
+ middleware.use "Rack::Head"
yield(middleware) if block_given?
end
end
@@ -290,10 +285,7 @@ module ActionController
class TestCase
include ActionDispatch::TestProcess
-
- setup do
- @routes = SharedTestRoutes
- end
+ include ActionDispatch::SharedRoutes
end
end
@@ -304,9 +296,7 @@ module ActionView
class TestCase
# Must repeat the setup because AV::TestCase is a duplication
# of AC::TestCase
- setup do
- @routes = SharedTestRoutes
- end
+ include ActionDispatch::SharedRoutes
end
end
@@ -356,6 +346,36 @@ end
module RoutingTestHelpers
def url_for(set, options, recall = nil)
- set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall))
+ set.send(:url_for, options.merge(:only_path => true, :_recall => recall))
+ end
+end
+
+class ResourcesController < ActionController::Base
+ def index() render :nothing => true end
+ alias_method :show, :index
+end
+
+class ThreadsController < ResourcesController; end
+class MessagesController < ResourcesController; end
+class CommentsController < ResourcesController; end
+class ReviewsController < ResourcesController; end
+class AuthorsController < ResourcesController; end
+class LogosController < ResourcesController; end
+
+class AccountsController < ResourcesController; end
+class AdminController < ResourcesController; end
+class ProductsController < ResourcesController; end
+class ImagesController < ResourcesController; end
+class PreferencesController < ResourcesController; end
+
+module Backoffice
+ class ProductsController < ResourcesController; end
+ class TagsController < ResourcesController; end
+ class ManufacturersController < ResourcesController; end
+ class ImagesController < ResourcesController; end
+
+ module Admin
+ class ProductsController < ResourcesController; end
+ class ImagesController < ResourcesController; end
end
end
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
deleted file mode 100644
index 275f25f597..0000000000
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ /dev/null
@@ -1,288 +0,0 @@
-require 'active_record_unit'
-
-class ActiveRecordStoreTest < ActionDispatch::IntegrationTest
- class TestController < ActionController::Base
- def no_session_access
- head :ok
- end
-
- def set_session_value
- raise "missing session!" unless session
- session[:foo] = params[:foo] || "bar"
- head :ok
- end
-
- def get_session_value
- render :text => "foo: #{session[:foo].inspect}"
- end
-
- def get_session_id
- render :text => "#{request.session_options[:id]}"
- end
-
- def call_reset_session
- session[:foo]
- reset_session
- reset_session if params[:twice]
- session[:foo] = "baz"
- head :ok
- end
-
- def renew
- env["rack.session.options"][:renew] = true
- session[:foo] = "baz"
- head :ok
- end
- end
-
- def setup
- ActiveRecord::SessionStore.session_class.create_table!
- end
-
- def teardown
- ActiveRecord::SessionStore.session_class.drop_table!
- end
-
- %w{ session sql_bypass }.each do |class_name|
- define_method("test_setting_and_getting_session_value_with_#{class_name}_store") do
- with_store class_name do
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: "bar"', response.body
-
- get '/set_session_value', :foo => "baz"
- assert_response :success
- assert cookies['_session_id']
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: "baz"', response.body
-
- get '/call_reset_session'
- assert_response :success
- assert_not_equal [], headers['Set-Cookie']
- end
- end
- end
-
- define_method("test_renewing_with_#{class_name}_store") do
- with_store class_name do
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
-
- get '/renew'
- assert_response :success
- assert_not_equal [], headers['Set-Cookie']
- end
- end
- end
- end
-
- def test_getting_nil_session_value
- with_test_route_set do
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: nil', response.body
- end
- end
-
- def test_calling_reset_session_twice_does_not_raise_errors
- with_test_route_set do
- get '/call_reset_session', :twice => "true"
- assert_response :success
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: "baz"', response.body
- end
- end
-
- def test_setting_session_value_after_session_reset
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
- session_id = cookies['_session_id']
-
- get '/call_reset_session'
- assert_response :success
- assert_not_equal [], headers['Set-Cookie']
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: "baz"', response.body
-
- get '/get_session_id'
- assert_response :success
- assert_not_equal session_id, response.body
- end
- end
-
- def test_getting_session_value_after_session_reset
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
- session_cookie = cookies.send(:hash_for)['_session_id']
-
- get '/call_reset_session'
- assert_response :success
- assert_not_equal [], headers['Set-Cookie']
-
- cookies << session_cookie # replace our new session_id with our old, pre-reset session_id
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: nil', response.body, "data for this session should have been obliterated from the database"
- end
- end
-
- def test_getting_from_nonexistent_session
- with_test_route_set do
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: nil', response.body
- assert_nil cookies['_session_id'], "should only create session on write, not read"
- end
- end
-
- def test_getting_session_id
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
- session_id = cookies['_session_id']
-
- get '/get_session_id'
- assert_response :success
- assert_equal session_id, response.body, "should be able to read session id without accessing the session hash"
- end
- end
-
- def test_doesnt_write_session_cookie_if_session_id_is_already_exists
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
-
- get '/get_session_value'
- assert_response :success
- assert_equal nil, headers['Set-Cookie'], "should not resend the cookie again if session_id cookie is already exists"
- end
- end
-
- def test_prevents_session_fixation
- with_test_route_set do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: "bar"', response.body
- session_id = cookies['_session_id']
- assert session_id
-
- reset!
-
- get '/get_session_value', :_session_id => session_id
- assert_response :success
- assert_equal 'foo: nil', response.body
- assert_not_equal session_id, cookies['_session_id']
- end
- end
-
- def test_allows_session_fixation
- with_test_route_set(:cookie_only => false) do
- get '/set_session_value'
- assert_response :success
- assert cookies['_session_id']
-
- get '/get_session_value'
- assert_response :success
- assert_equal 'foo: "bar"', response.body
- session_id = cookies['_session_id']
- assert session_id
-
- reset!
-
- get '/set_session_value', :_session_id => session_id, :foo => "baz"
- assert_response :success
- assert_equal session_id, cookies['_session_id']
-
- get '/get_session_value', :_session_id => session_id
- assert_response :success
- assert_equal 'foo: "baz"', response.body
- assert_equal session_id, cookies['_session_id']
- end
- end
-
- def test_incoming_invalid_session_id_via_cookie_should_be_ignored
- with_test_route_set do
- open_session do |sess|
- sess.cookies['_session_id'] = 'INVALID'
-
- sess.get '/set_session_value'
- new_session_id = sess.cookies['_session_id']
- assert_not_equal 'INVALID', new_session_id
-
- sess.get '/get_session_value'
- new_session_id_2 = sess.cookies['_session_id']
- assert_equal new_session_id, new_session_id_2
- end
- end
- end
-
- def test_incoming_invalid_session_id_via_parameter_should_be_ignored
- with_test_route_set(:cookie_only => false) do
- open_session do |sess|
- sess.get '/set_session_value', :_session_id => 'INVALID'
- new_session_id = sess.cookies['_session_id']
- assert_not_equal 'INVALID', new_session_id
-
- sess.get '/get_session_value'
- new_session_id_2 = sess.cookies['_session_id']
- assert_equal new_session_id, new_session_id_2
- end
- end
- end
-
- def test_session_store_with_all_domains
- with_test_route_set(:domain => :all) do
- get '/set_session_value'
- assert_response :success
- end
- end
-
- private
-
- def with_test_route_set(options = {})
- with_routing do |set|
- set.draw do
- get ':action', :to => 'active_record_store_test/test'
- end
-
- @app = self.class.build_app(set) do |middleware|
- middleware.use ActiveRecord::SessionStore, options.reverse_merge(:key => '_session_id')
- middleware.delete "ActionDispatch::ShowExceptions"
- end
-
- yield
- end
- end
-
- def with_store(class_name)
- session_class, ActiveRecord::SessionStore.session_class =
- ActiveRecord::SessionStore.session_class, "ActiveRecord::SessionStore::#{class_name.camelize}".constantize
- yield
- ensure
- ActiveRecord::SessionStore.session_class = session_class
- end
-end
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 9b0d4d0f4c..4ab5d92a2b 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -1,5 +1,5 @@
require 'abstract_unit'
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
require 'controller/fake_controllers'
class ActionPackAssertionsController < ActionController::Base
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index b9513ccff4..9b42e7631f 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'active_support/logger'
+require 'controller/fake_models'
require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
# Provide some controller to run the tests on.
@@ -63,6 +64,10 @@ end
class RecordIdentifierController < ActionController::Base
end
+class RecordIdentifierWithoutDeprecationController < ActionController::Base
+ include ActionView::RecordIdentifier
+end
+
class ControllerClassTests < ActiveSupport::TestCase
def test_controller_path
@@ -81,6 +86,42 @@ class ControllerClassTests < ActiveSupport::TestCase
assert_respond_to RecordIdentifierController.new, :dom_id
assert_respond_to RecordIdentifierController.new, :dom_class
end
+
+ def test_record_identifier_is_deprecated
+ record = Comment.new
+ record.save
+
+ dom_id = nil
+ assert_deprecated 'dom_id method will no longer' do
+ dom_id = RecordIdentifierController.new.dom_id(record)
+ end
+
+ assert_equal 'comment_1', dom_id
+
+ dom_class = nil
+ assert_deprecated 'dom_class method will no longer' do
+ dom_class = RecordIdentifierController.new.dom_class(record)
+ end
+ assert_equal 'comment', dom_class
+ end
+
+ def test_no_deprecation_when_action_view_record_identifier_is_included
+ record = Comment.new
+ record.save
+
+ dom_id = nil
+ assert_not_deprecated do
+ dom_id = RecordIdentifierWithoutDeprecationController.new.dom_id(record)
+ end
+
+ assert_equal 'comment_1', dom_id
+
+ dom_class = nil
+ assert_not_deprecated do
+ dom_class = RecordIdentifierWithoutDeprecationController.new.dom_class(record)
+ end
+ assert_equal 'comment', dom_class
+ end
end
class ControllerInstanceTests < ActiveSupport::TestCase
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index d5afef9086..2c3511f6a0 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -349,15 +349,18 @@ class ActionCachingMockController
end
class ActionCacheTest < ActionController::TestCase
+ tests ActionCachingTestController
+
def setup
super
- reset!
+ @request.host = 'hostname.com'
FileUtils.mkdir_p(FILE_STORE_PATH)
@path_class = ActionController::Caching::Actions::ActionCachePath
@mock_controller = ActionCachingMockController.new
end
def teardown
+ super
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
end
@@ -367,7 +370,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test')
- reset!
get :index
assert_response :success
@@ -380,7 +382,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert !fragment_exist?('hostname.com/action_caching_test/destroy')
- reset!
get :destroy
assert_response :success
@@ -395,7 +396,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/with_layout')
- reset!
get :with_layout
assert_response :success
@@ -410,7 +410,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/layout_false')
- reset!
get :layout_false
assert_response :success
@@ -425,7 +424,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/with_layout_proc_param')
- reset!
get :with_layout_proc_param, :layout => false
assert_response :success
@@ -440,7 +438,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/with_layout_proc_param')
- reset!
get :with_layout_proc_param, :layout => true
assert_response :success
@@ -477,7 +474,6 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert fragment_exist?('test.host/custom/show')
- reset!
get :show
assert_response :success
@@ -488,7 +484,6 @@ class ActionCacheTest < ActionController::TestCase
get :edit
assert_response :success
assert fragment_exist?('test.host/edit')
- reset!
get :edit, :id => 1
assert_response :success
@@ -499,22 +494,18 @@ class ActionCacheTest < ActionController::TestCase
get :index
assert_response :success
cached_time = content_to_cache
- reset!
get :index
assert_response :success
assert_equal cached_time, @response.body
- reset!
get :expire
assert_response :success
- reset!
get :index
assert_response :success
new_cached_time = content_to_cache
assert_not_equal cached_time, @response.body
- reset!
get :index
assert_response :success
@@ -524,12 +515,10 @@ class ActionCacheTest < ActionController::TestCase
def test_cache_expiration_isnt_affected_by_request_format
get :index
cached_time = content_to_cache
- reset!
@request.request_uri = "/action_caching_test/expire.xml"
get :expire, :format => :xml
assert_response :success
- reset!
get :index
assert_response :success
@@ -539,12 +528,10 @@ class ActionCacheTest < ActionController::TestCase
def test_cache_expiration_with_url_string
get :index
cached_time = content_to_cache
- reset!
@request.request_uri = "/action_caching_test/expire_with_url_string"
get :expire_with_url_string
assert_response :success
- reset!
get :index
assert_response :success
@@ -557,23 +544,17 @@ class ActionCacheTest < ActionController::TestCase
assert_response :success
jamis_cache = content_to_cache
- reset!
-
@request.host = 'david.hostname.com'
get :index
assert_response :success
david_cache = content_to_cache
assert_not_equal jamis_cache, @response.body
- reset!
-
@request.host = 'jamis.hostname.com'
get :index
assert_response :success
assert_equal jamis_cache, @response.body
- reset!
-
@request.host = 'david.hostname.com'
get :index
assert_response :success
@@ -583,8 +564,6 @@ class ActionCacheTest < ActionController::TestCase
def test_redirect_is_not_cached
get :redirected
assert_response :redirect
- reset!
-
get :redirected
assert_response :redirect
end
@@ -592,8 +571,6 @@ class ActionCacheTest < ActionController::TestCase
def test_forbidden_is_not_cached
get :forbidden
assert_response :forbidden
- reset!
-
get :forbidden
assert_response :forbidden
end
@@ -609,17 +586,14 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/index.xml')
- reset!
get :index, :format => 'xml'
assert_response :success
assert_equal cached_time, @response.body
assert_equal 'application/xml', @response.content_type
- reset!
get :expire_xml
assert_response :success
- reset!
get :index, :format => 'xml'
assert_response :success
@@ -724,14 +698,6 @@ class ActionCacheTest < ActionController::TestCase
assigns(:cache_this)
end
- def reset!
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = ActionCachingTestController.new
- @controller.singleton_class.send(:include, @routes.url_helpers)
- @request.host = 'hostname.com'
- end
-
def fragment_exist?(path)
@controller.fragment_exist?(path)
end
@@ -888,14 +854,17 @@ Ciao
CACHED
assert_equal expected_body, @response.body
- assert_equal "This bit's fragment cached", @store.read('views/test.host/functional_caching/fragment_cached')
+ assert_equal "This bit's fragment cached",
+ @store.read("views/test.host/functional_caching/fragment_cached/#{template_digest("functional_caching/fragment_cached", "html")}")
end
def test_fragment_caching_in_partials
get :html_fragment_cached_with_partial
assert_response :success
assert_match(/Old fragment caching in a partial/, @response.body)
- assert_match("Old fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial'))
+
+ assert_match("Old fragment caching in a partial",
+ @store.read("views/test.host/functional_caching/html_fragment_cached_with_partial/#{template_digest("functional_caching/_partial", "html")}"))
end
def test_render_inline_before_fragment_caching
@@ -903,7 +872,8 @@ CACHED
assert_response :success
assert_match(/Some inline content/, @response.body)
assert_match(/Some cached content/, @response.body)
- assert_match("Some cached content", @store.read('views/test.host/functional_caching/inline_fragment_cached'))
+ assert_match("Some cached content",
+ @store.read("views/test.host/functional_caching/inline_fragment_cached/#{template_digest("functional_caching/inline_fragment_cached", "html")}"))
end
def test_html_formatted_fragment_caching
@@ -913,7 +883,8 @@ CACHED
assert_equal expected_body, @response.body
- assert_equal "<p>ERB</p>", @store.read('views/test.host/functional_caching/formatted_fragment_cached')
+ assert_equal "<p>ERB</p>",
+ @store.read("views/test.host/functional_caching/formatted_fragment_cached/#{template_digest("functional_caching/formatted_fragment_cached", "html")}")
end
def test_xml_formatted_fragment_caching
@@ -923,8 +894,14 @@ CACHED
assert_equal expected_body, @response.body
- assert_equal " <p>Builder</p>\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached')
+ assert_equal " <p>Builder</p>\n",
+ @store.read("views/test.host/functional_caching/formatted_fragment_cached/#{template_digest("functional_caching/formatted_fragment_cached", "xml")}")
end
+
+ private
+ def template_digest(name, format)
+ ActionView::Digestor.digest(name, format, @controller.lookup_context)
+ end
end
class CacheHelperOutputBufferTest < ActionController::TestCase
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index b9cb93f0f4..afc00a3c9d 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -505,6 +505,10 @@ class FilterTest < ActionController::TestCase
def show
render :text => 'hello world'
end
+
+ def error
+ raise StandardError.new
+ end
end
class ImplicitActionsController < ActionController::Base
@@ -534,6 +538,13 @@ class FilterTest < ActionController::TestCase
assert_equal 'hello world', response.body
end
+ def test_sweeper_should_clean_up_if_exception_is_raised
+ assert_raise StandardError do
+ test_process(SweeperTestController, 'error')
+ end
+ assert_nil AppSweeper.instance.controller
+ end
+
def test_before_method_of_sweeper_should_always_return_true
sweeper = ActionController::Caching::Sweeper.send(:new)
assert sweeper.before(TestController.new)
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index f91aa246f4..8340aab4d2 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -220,7 +220,6 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
class TestController < ActionController::Base
-
add_flash_types :bar
def set_flash
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 828ea5b0fb..b11ad633bd 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -139,11 +139,12 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
test "authentication request with request-uri that doesn't match credentials digest-uri" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
- @request.env['ORIGINAL_FULLPATH'] = "/http_digest_authentication_test/dummy_digest/altered/uri"
+ @request.env['PATH_INFO'] = "/proxied/uri"
get :display
- assert_response :unauthorized
- assert_equal "Authentication Failed", @response.body
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with absolute request uri (as in webrick)" do
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index 3054c1684c..ad4e743be8 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -79,6 +79,14 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
end
end
+ test "authentication request with badly formatted header" do
+ @request.env['HTTP_AUTHORIZATION'] = "Token foobar"
+ get :index
+
+ assert_response :unauthorized
+ assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication header was not properly parsed"
+ end
+
test "authentication request without credential" do
get :display
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index f18bf33969..cf561d913a 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
class SessionTest < ActiveSupport::TestCase
StubApp = lambda { |env|
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index c73b36f05e..94a8d2f180 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -200,7 +200,7 @@ class SetsNonExistentLayoutFile < LayoutTest
layout "nofile"
end
-class LayoutExceptionRaised < ActionController::TestCase
+class LayoutExceptionRaisedTest < ActionController::TestCase
def test_exception_raised_when_layout_file_not_found
@controller = SetsNonExistentLayoutFile.new
assert_raise(ActionView::MissingTemplate) { get :hello }
diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb
new file mode 100644
index 0000000000..20e433d1ec
--- /dev/null
+++ b/actionpack/test/controller/live_stream_test.rb
@@ -0,0 +1,121 @@
+require 'abstract_unit'
+require 'active_support/concurrency/latch'
+
+module ActionController
+ class LiveStreamTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ include ActionController::Live
+
+ attr_accessor :latch, :tc
+
+ def self.controller_path
+ 'test'
+ end
+
+ def render_text
+ render :text => 'zomg'
+ end
+
+ def default_header
+ response.stream.write "<html><body>hi</body></html>"
+ response.stream.close
+ end
+
+ def basic_stream
+ response.headers['Content-Type'] = 'text/event-stream'
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ end
+ response.stream.close
+ end
+
+ def blocking_stream
+ response.headers['Content-Type'] = 'text/event-stream'
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ latch.await
+ end
+ response.stream.close
+ end
+
+ def thread_locals
+ tc.assert_equal 'aaron', Thread.current[:setting]
+ tc.refute_equal Thread.current.object_id, Thread.current[:originating_thread]
+
+ response.headers['Content-Type'] = 'text/event-stream'
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ end
+ response.stream.close
+ end
+ end
+
+ tests TestController
+
+ class TestResponse < Live::Response
+ def recycle!
+ initialize
+ end
+ end
+
+ def build_response
+ TestResponse.new
+ end
+
+ def test_set_response!
+ @controller.set_response!(@request)
+ assert_kind_of(Live::Response, @controller.response)
+ assert_equal @request, @controller.response.request
+ end
+
+ def test_write_to_stream
+ @controller = TestController.new
+ get :basic_stream
+ assert_equal "helloworld", @response.body
+ assert_equal 'text/event-stream', @response.headers['Content-Type']
+ end
+
+ def test_async_stream
+ @controller.latch = ActiveSupport::Concurrency::Latch.new
+ parts = ['hello', 'world']
+
+ @controller.request = @request
+ @controller.response = @response
+
+ t = Thread.new(@response) { |resp|
+ resp.stream.each do |part|
+ assert_equal parts.shift, part
+ ol = @controller.latch
+ @controller.latch = ActiveSupport::Concurrency::Latch.new
+ ol.release
+ end
+ }
+
+ @controller.process :blocking_stream
+
+ assert t.join
+ end
+
+ def test_thread_locals_get_copied
+ @controller.tc = self
+ Thread.current[:originating_thread] = Thread.current.object_id
+ Thread.current[:setting] = 'aaron'
+
+ get :thread_locals
+ end
+
+ def test_live_stream_default_header
+ @controller.request = @request
+ @controller.response = @response
+ @controller.process :default_header
+ _, headers, _ = @response.prepare!
+ assert headers['Content-Type']
+ end
+
+ def test_render_text
+ get :render_text
+ assert_equal 'zomg', response.body
+ assert response.stream.closed?, 'stream should be closed'
+ end
+ end
+end
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index c8e036b116..b21d35c846 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
require 'controller/fake_models'
require 'active_support/core_ext/hash/conversions'
-require 'active_support/core_ext/object/inclusion'
class StarStarMimeController < ActionController::Base
layout nil
@@ -152,10 +151,11 @@ class RespondToController < ActionController::Base
protected
def set_layout
- if action_name.in?(["all_types_with_layout", "iphone_with_html_response_type"])
- "respond_to/layouts/standard"
- elsif action_name == "iphone_with_html_response_type_without_layout"
- "respond_to/layouts/missing"
+ case action_name
+ when "all_types_with_layout", "iphone_with_html_response_type"
+ "respond_to/layouts/standard"
+ when "iphone_with_html_response_type_without_layout"
+ "respond_to/layouts/missing"
end
end
end
@@ -851,7 +851,7 @@ class RespondWithControllerTest < ActionController::TestCase
put :using_resource
assert_equal "application/xml", @response.content_type
assert_equal 204, @response.status
- assert_equal " ", @response.body
+ assert_equal "", @response.body
end
def test_using_resource_for_put_with_json_yields_no_content_on_success
@@ -860,7 +860,7 @@ class RespondWithControllerTest < ActionController::TestCase
put :using_resource
assert_equal "application/json", @response.content_type
assert_equal 204, @response.status
- assert_equal " ", @response.body
+ assert_equal "", @response.body
end
def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure
@@ -902,7 +902,7 @@ class RespondWithControllerTest < ActionController::TestCase
delete :using_resource
assert_equal "application/xml", @response.content_type
assert_equal 204, @response.status
- assert_equal " ", @response.body
+ assert_equal "", @response.body
end
def test_using_resource_for_delete_with_json_yields_no_content_on_success
@@ -912,7 +912,7 @@ class RespondWithControllerTest < ActionController::TestCase
delete :using_resource
assert_equal "application/json", @response.content_type
assert_equal 204, @response.status
- assert_equal " ", @response.body
+ assert_equal "", @response.body
end
def test_using_resource_for_delete_with_html_redirects_on_failure
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 5bcd79ebec..7396c850ad 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -110,6 +110,36 @@ module BareMetalTest
assert_nil headers['Content-Type']
assert_nil headers['Content-Length']
end
+
+ test "head :no_content (204) does not return any content" do
+ content = HeadController.action(:no_content).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :reset_content (205) does not return any content" do
+ content = HeadController.action(:reset_content).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :not_modified (304) does not return any content" do
+ content = HeadController.action(:not_modified).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :continue (100) does not return any content" do
+ content = HeadController.action(:continue).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :switching_protocols (101) does not return any content" do
+ content = HeadController.action(:switching_protocols).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :processing (102) does not return any content" do
+ content = HeadController.action(:processing).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
end
class BareControllerTest < ActionController::TestCase
diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb
index aa44e0b282..475bf9d3c9 100644
--- a/actionpack/test/controller/new_base/render_action_test.rb
+++ b/actionpack/test/controller/new_base/render_action_test.rb
@@ -86,8 +86,6 @@ module RenderAction
def setup
end
- describe "Both <controller_path>.html.erb and application.html.erb are missing"
-
test "rendering with layout => true" do
assert_raise(ArgumentError) do
get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false
@@ -154,8 +152,6 @@ module RenderActionWithApplicationLayout
end
class LayoutTest < Rack::TestCase
- describe "Only application.html.erb is present and <controller_path>.html.erb is missing"
-
test "rendering implicit application.html.erb as layout" do
get "/render_action_with_application_layout/basic/hello_world"
@@ -232,8 +228,6 @@ module RenderActionWithControllerLayout
end
class ControllerLayoutTest < Rack::TestCase
- describe "Only <controller_path>.html.erb is present and application.html.erb is missing"
-
test "render hello_world and implicitly use <controller_path>.html.erb as a layout." do
get "/render_action_with_controller_layout/basic/hello_world"
@@ -290,8 +284,6 @@ module RenderActionWithBothLayouts
end
class ControllerLayoutTest < Rack::TestCase
- describe "Both <controller_path>.html.erb and application.html.erb are present"
-
test "rendering implicitly use <controller_path>.html.erb over application.html.erb as a layout" do
get "/render_action_with_both_layouts/basic/hello_world"
diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb
index bfca8c5c24..f4bdd3e1d4 100644
--- a/actionpack/test/controller/new_base/render_streaming_test.rb
+++ b/actionpack/test/controller/new_base/render_streaming_test.rb
@@ -85,7 +85,7 @@ module RenderStreaming
test "rendering with template exception logs the exception" do
io = StringIO.new
- _old, ActionController::Base.logger = ActionController::Base.logger, ActiveSupport::Logger.new(io)
+ _old, ActionView::Base.logger = ActionView::Base.logger, ActiveSupport::Logger.new(io)
begin
get "/render_streaming/basic/template_exception"
diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb
index 00c7df2af8..d0be4f66d1 100644
--- a/actionpack/test/controller/new_base/render_template_test.rb
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -126,7 +126,7 @@ module RenderTemplate
test "rendering a template with error properly excerts the code" do
get :with_error
assert_status 500
- assert_match "undefined local variable or method `idontexist'", response.body
+ assert_match "undefined local variable or method `idontexist", response.body
end
end
@@ -160,8 +160,6 @@ module RenderTemplate
end
class TestWithLayout < Rack::TestCase
- describe "Rendering with :template using implicit or explicit layout"
-
test "rendering with implicit layout" do
with_routing do |set|
set.draw { get ':controller', :action => :index }
diff --git a/actionpack/test/controller/new_base/render_text_test.rb b/actionpack/test/controller/new_base/render_text_test.rb
index f8d02e8b6c..d6c3926a4d 100644
--- a/actionpack/test/controller/new_base/render_text_test.rb
+++ b/actionpack/test/controller/new_base/render_text_test.rb
@@ -63,8 +63,6 @@ module RenderText
end
class RenderTextTest < Rack::TestCase
- describe "Rendering text using render :text"
-
test "rendering text from an action with default options renders the text with the layout" do
with_routing do |set|
set.draw { get ':controller', :action => 'index' }
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 6bebe7e1ed..fd8f87e377 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -22,6 +22,18 @@ module Quiz
end
end
+class TestControllerWithExtraEtags < ActionController::Base
+ etag { nil }
+ etag { 'ab' }
+ etag { :cde }
+ etag { [:f] }
+ etag { nil }
+
+ def fresh
+ render text: "stale" if stale?(etag: '123')
+ end
+end
+
class TestController < ActionController::Base
protect_from_forgery
@@ -186,7 +198,7 @@ class TestController < ActionController::Base
# :ported:
def render_text_hello_world_with_layout
- @variable_for_layout = ", I'm here!"
+ @variable_for_layout = ", I am here!"
render :text => "hello world", :layout => true
end
@@ -844,7 +856,7 @@ class RenderTest < ActionController::TestCase
# :ported:
def test_do_with_render_text_and_layout
get :render_text_hello_world_with_layout
- assert_equal "<html>hello world, I'm here!</html>", @response.body
+ assert_equal "<html>hello world, I am here!</html>", @response.body
end
# :ported:
@@ -1626,6 +1638,26 @@ class LastModifiedRenderTest < ActionController::TestCase
end
end
+class EtagRenderTest < ActionController::TestCase
+ tests TestControllerWithExtraEtags
+
+ def setup
+ super
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_multiple_etags
+ @request.if_none_match = %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key([ "123", 'ab', :cde, [:f] ]))}")
+ get :fresh
+ assert_response :not_modified
+
+ @request.if_none_match = %("nomatch")
+ get :fresh
+ assert_response :success
+ end
+end
+
+
class MetalRenderTest < ActionController::TestCase
tests MetalTestController
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index de1bff17eb..305659b219 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -1,36 +1,6 @@
require 'abstract_unit'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/object/with_options'
-require 'active_support/core_ext/object/inclusion'
-
-class ResourcesController < ActionController::Base
- def index() render :nothing => true end
- alias_method :show, :index
-end
-
-class ThreadsController < ResourcesController; end
-class MessagesController < ResourcesController; end
-class CommentsController < ResourcesController; end
-class AuthorsController < ResourcesController; end
-class LogosController < ResourcesController; end
-
-class AccountsController < ResourcesController; end
-class AdminController < ResourcesController; end
-class ProductsController < ResourcesController; end
-class ImagesController < ResourcesController; end
-class PreferencesController < ResourcesController; end
-
-module Backoffice
- class ProductsController < ResourcesController; end
- class TagsController < ResourcesController; end
- class ManufacturersController < ResourcesController; end
- class ImagesController < ResourcesController; end
-
- module Admin
- class ProductsController < ResourcesController; end
- class ImagesController < ResourcesController; end
- end
-end
class ResourcesTest < ActionController::TestCase
def test_default_restful_routes
@@ -1308,7 +1278,7 @@ class ResourcesTest < ActionController::TestCase
def assert_resource_methods(expected, resource, action_method, method)
assert_equal expected.length, resource.send("#{action_method}_methods")[method].size, "#{resource.send("#{action_method}_methods")[method].inspect}"
expected.each do |action|
- assert action.in?(resource.send("#{action_method}_methods")[method])
+ assert resource.send("#{action_method}_methods")[method].include?(action)
"#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}"
end
end
@@ -1345,9 +1315,9 @@ class ResourcesTest < ActionController::TestCase
options = options.merge(:action => action.to_s)
path_options = { :path => path, :method => method }
- if action.in?(Array(allowed))
+ if Array(allowed).include?(action)
assert_recognizes options, path_options
- elsif action.in?(Array(not_allowed))
+ elsif Array(not_allowed).include?(action)
assert_not_recognizes options, path_options
end
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 6cc1370105..f0430e516f 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -197,7 +197,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
def test_regexp_precidence
- @rs.draw do
+ rs.draw do
get '/whois/:domain', :constraints => {
:domain => /\w+\.[\w\.]+/ },
:to => lambda { |env| [200, {}, %w{regexp}] }
@@ -216,7 +216,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
}
- @rs.draw do
+ rs.draw do
get '/', :constraints => subdomain.new,
:to => lambda { |env| [200, {}, %w{default}] }
get '/', :constraints => { :subdomain => 'clients' },
@@ -228,7 +228,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
def test_lambda_constraints
- @rs.draw do
+ rs.draw do
get '/', :constraints => lambda { |req|
req.subdomain.present? and req.subdomain != "clients" },
:to => lambda { |env| [200, {}, %w{default}] }
@@ -266,22 +266,22 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
def test_draw_with_block_arity_one_raises
assert_raise(RuntimeError) do
- @rs.draw { |map| map.match '/:controller(/:action(/:id))' }
+ rs.draw { |map| map.match '/:controller(/:action(/:id))' }
end
end
def test_specific_controller_action_failure
- @rs.draw do
+ rs.draw do
mount lambda {} => "/foo"
end
- assert_raises(ActionController::RoutingError) do
- url_for(@rs, :controller => "omg", :action => "lol")
+ assert_raises(ActionController::UrlGenerationError) do
+ url_for(rs, :controller => "omg", :action => "lol")
end
end
def test_default_setup
- @rs.draw { get '/:controller(/:action(/:id))' }
+ rs.draw { get '/:controller(/:action(/:id))' }
assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
@@ -298,8 +298,8 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
def test_ignores_leading_slash
- @rs.clear!
- @rs.draw { get '/:controller(/:action(/:id))'}
+ rs.clear!
+ rs.draw { get '/:controller(/:action(/:id))'}
test_default_setup
end
@@ -470,7 +470,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
def test_changing_controller
- @rs.draw { get ':controller/:action/:id' }
+ rs.draw { get ':controller/:action/:id' }
assert_equal '/admin/stuff/show/10',
url_for(rs, {:controller => 'stuff', :action => 'show', :id => 10},
@@ -514,7 +514,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
rs.draw do
get 'post/:id' => 'post#show', :constraints => { :id => /\d+/ }, :as => 'post'
end
- assert_raise(ActionController::RoutingError) do
+ assert_raise(ActionController::UrlGenerationError) do
url_for(rs, { :controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post" })
end
end
@@ -583,7 +583,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
def test_action_expiry
- @rs.draw { get ':controller(/:action(/:id))' }
+ rs.draw { get ':controller(/:action(/:id))' }
assert_equal '/content', url_for(rs, { :controller => 'content' }, { :controller => 'content', :action => 'show' })
end
@@ -594,7 +594,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
assert_equal '/post/10', url_for(rs, { :controller => 'post', :action => 'show', :id => 10 })
- assert_raise ActionController::RoutingError do
+ assert_raise(ActionController::UrlGenerationError) do
url_for(rs, { :controller => 'post', :action => 'show' })
end
end
@@ -760,7 +760,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
get 'foos/:id' => 'foos#show', :as => 'foo_with_requirement', :constraints => { :id => /\d+/ }
end
- assert_raise(ActionController::RoutingError) do
+ assert_raise(ActionController::UrlGenerationError) do
setup_for_named_route.send(:foo_with_requirement_url, "I am Against the constraints")
end
end
@@ -1051,7 +1051,7 @@ class RouteSetTest < ActiveSupport::TestCase
set.draw do
get "/people" => "missing#index"
end
-
+
assert_raise(ActionController::RoutingError) {
set.recognize_path("/people", :method => :get)
}
@@ -1459,7 +1459,7 @@ class RouteSetTest < ActiveSupport::TestCase
url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'david' })
assert_equal "/page/david", url
- assert_raise ActionController::RoutingError do
+ assert_raise(ActionController::UrlGenerationError) do
url_for(set, { :controller => 'pages', :action => 'show', :name => 'davidjamis' })
end
url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'JAMIS' })
diff --git a/actionpack/test/controller/selector_test.rb b/actionpack/test/controller/selector_test.rb
index 5e302da212..1e80c8601c 100644
--- a/actionpack/test/controller/selector_test.rb
+++ b/actionpack/test/controller/selector_test.rb
@@ -5,7 +5,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-require 'action_controller/vendor/html-scanner'
+require 'action_view/vendor/html-scanner'
class SelectorTest < ActiveSupport::TestCase
#
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index 6fc3556e31..97ede35317 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -51,14 +51,14 @@ class SendFileTest < ActionController::TestCase
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
- assert_respond_to response.body_parts, :each
- assert_respond_to response.body_parts, :to_path
+ assert_respond_to response.stream, :each
+ assert_respond_to response.stream, :to_path
require 'stringio'
output = StringIO.new
output.binmode
output.string.force_encoding(file_data.encoding)
- assert_nothing_raised { response.body_parts.each { |part| output << part.to_s } }
+ response.body_parts.each { |part| output << part.to_s }
assert_equal file_data, output.string
end
diff --git a/actionpack/test/controller/streaming_test.rb b/actionpack/test/controller/streaming_test.rb
new file mode 100644
index 0000000000..6ee6444065
--- /dev/null
+++ b/actionpack/test/controller/streaming_test.rb
@@ -0,0 +1,26 @@
+require 'abstract_unit'
+
+module ActionController
+ class StreamingResponseTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def self.controller_path
+ 'test'
+ end
+
+ def basic_stream
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ response.stream.write "\n"
+ end
+ response.stream.close
+ end
+ end
+
+ tests TestController
+
+ def test_write_to_stream
+ get :basic_stream
+ assert_equal "hello\nworld\n", @response.body
+ end
+ end
+end
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index b2cb5f80d5..d3fc7128e9 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -3,7 +3,7 @@ require 'abstract_unit'
module AbstractController
module Testing
- class UrlForTests < ActionController::TestCase
+ class UrlForTest < ActionController::TestCase
class W
include ActionDispatch::Routing::RouteSet.new.tap { |r| r.draw { get ':controller(/:action(/:id(.:format)))' } }.url_helpers
end
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index cc3706aeee..d9a1ae7d4f 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-class UrlRewriterTests < ActionController::TestCase
+class UrlRewriterTests < ActiveSupport::TestCase
class Rewriter
def initialize(request)
@options = {
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 2467654a70..347b3b3b5a 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -190,7 +190,7 @@ class CookiesTest < ActionController::TestCase
def test_setting_the_same_value_to_permanent_cookie
request.cookies[:user_name] = 'Jamie'
get :set_permanent_cookie
- assert response.cookies, 'user_name' => 'Jamie'
+ assert_equal response.cookies, 'user_name' => 'Jamie'
end
def test_setting_with_escapable_characters
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
index 6ff651ad52..d236b14e02 100644
--- a/actionpack/test/dispatch/debug_exceptions_test.rb
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -37,6 +37,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new)
when "/bad_request"
raise ActionController::BadRequest
+ when "/missing_keys"
+ raise ActionController::UrlGenerationError, "No route matches"
else
raise "puke!"
end
@@ -113,6 +115,15 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
assert_match(/AbstractController::ActionNotFound/, body)
end
+ test "named urls missing keys raise 500 level error" do
+ @app = DevelopmentApp
+
+ get "/missing_keys", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 500
+
+ assert_match(/ActionController::UrlGenerationError/, body)
+ end
+
test "show the controller name in the diagnostics template when controller name is present" do
@app = DevelopmentApp
get("/runtime_error", {}, {
diff --git a/actionpack/test/dispatch/live_response_test.rb b/actionpack/test/dispatch/live_response_test.rb
new file mode 100644
index 0000000000..e16f23914b
--- /dev/null
+++ b/actionpack/test/dispatch/live_response_test.rb
@@ -0,0 +1,83 @@
+require 'abstract_unit'
+require 'active_support/concurrency/latch'
+
+module ActionController
+ module Live
+ class ResponseTest < ActiveSupport::TestCase
+ def setup
+ @response = Live::Response.new
+ end
+
+ def test_header_merge
+ header = @response.header.merge('Foo' => 'Bar')
+ assert_kind_of(ActionController::Live::Response::Header, header)
+ refute_equal header, @response.header
+ end
+
+ def test_initialize_with_default_headers
+ r = Class.new(Live::Response) do
+ def self.default_headers
+ { 'omg' => 'g' }
+ end
+ end
+
+ header = r.new.header
+ assert_kind_of(ActionController::Live::Response::Header, header)
+ end
+
+ def test_parallel
+ latch = ActiveSupport::Concurrency::Latch.new
+
+ t = Thread.new {
+ @response.stream.write 'foo'
+ latch.await
+ @response.stream.close
+ }
+
+ @response.each do |part|
+ assert_equal 'foo', part
+ latch.release
+ end
+ assert t.join
+ end
+
+ def test_setting_body_populates_buffer
+ @response.body = 'omg'
+ @response.close
+ assert_equal ['omg'], @response.body_parts
+ end
+
+ def test_cache_control_is_set
+ @response.stream.write 'omg'
+ assert_equal 'no-cache', @response.headers['Cache-Control']
+ end
+
+ def test_content_length_is_removed
+ @response.headers['Content-Length'] = "1234"
+ @response.stream.write 'omg'
+ assert_nil @response.headers['Content-Length']
+ end
+
+ def test_headers_cannot_be_written_after_write
+ @response.stream.write 'omg'
+
+ assert @response.headers.frozen?
+ e = assert_raises(ActionDispatch::IllegalStateError) do
+ @response.headers['Content-Length'] = "zomg"
+ end
+
+ assert_equal 'header already sent', e.message
+ end
+
+ def test_headers_cannot_be_written_after_close
+ @response.stream.close
+
+ assert @response.headers.frozen?
+ e = assert_raises(ActionDispatch::IllegalStateError) do
+ @response.headers['Content-Length'] = "zomg"
+ end
+ assert_equal 'header already sent', e.message
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb
index 8070bdec8a..58457b0c28 100644
--- a/actionpack/test/dispatch/mapper_test.rb
+++ b/actionpack/test/dispatch/mapper_test.rb
@@ -98,6 +98,15 @@ module ActionDispatch
mapper.get '/*path', :to => 'pages#show', :format => true
assert_equal '/*path.:format', fakeset.conditions.first[:path_info]
end
+
+ def test_raising_helpful_error_on_invalid_arguments
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ app = lambda { |env| [200, {}, [""]] }
+ assert_raises ArgumentError do
+ mapper.mount app
+ end
+ end
end
end
end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index ed012093a7..3e83f3d4fa 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -92,7 +92,7 @@ class MimeTypeTest < ActiveSupport::TestCase
# (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1)
test "parse other broken acceptlines" do
accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*"
- expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL ]
+ expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL]
assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
end
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
index 536e35ab2e..3b008fdff0 100644
--- a/actionpack/test/dispatch/mount_test.rb
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -22,6 +22,7 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
mount SprocketsApp => "/shorthand"
mount FakeEngine, :at => "/fakeengine"
+ mount FakeEngine, :at => "/getfake", :via => :get
scope "/its_a" do
mount SprocketsApp, :at => "/sprocket"
@@ -52,6 +53,14 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
assert_equal "/shorthand -- /omg", response.body
end
+ def test_mounting_works_with_via
+ get "/getfake"
+ assert_equal "OK", response.body
+
+ post "/getfake"
+ assert_response :not_found
+ end
+
def test_with_fake_engine_does_not_call_invalid_method
get "/fakeengine"
assert_equal "OK", response.body
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
index ab2f7612ce..6d75c5ec7a 100644
--- a/actionpack/test/dispatch/prefix_generation_test.rb
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -166,18 +166,6 @@ module TestGenerationPrefix
assert_equal "/generate", last_response.body
end
- test "[ENGINE] generating application's url includes default_url_options[:script_name]" do
- RailsApplication.routes.default_url_options = {:script_name => "/something"}
- get "/pure-awesomeness/blog/url_to_application"
- assert_equal "/something/generate", last_response.body
- end
-
- test "[ENGINE] generating application's url should give higher priority to default_url_options[:script_name]" do
- RailsApplication.routes.default_url_options = {:script_name => "/something"}
- get "/pure-awesomeness/blog/url_to_application", {}, 'SCRIPT_NAME' => '/foo'
- assert_equal "/something/generate", last_response.body
- end
-
test "[ENGINE] generating engine's url with polymorphic path" do
get "/pure-awesomeness/blog/polymorphic_path_for_engine"
assert_equal "/pure-awesomeness/blog/posts/1", last_response.body
@@ -200,12 +188,6 @@ module TestGenerationPrefix
assert_equal "/something/awesome/blog/posts/1", last_response.body
end
- test "[APP] generating engine's route should give higher priority to default_url_options[:script_name]" do
- RailsApplication.routes.default_url_options = {:script_name => "/something"}
- get "/generate", {}, 'SCRIPT_NAME' => "/foo"
- assert_equal "/something/awesome/blog/posts/1", last_response.body
- end
-
test "[APP] generating engine's url with polymorphic path" do
get "/polymorphic_path_for_engine"
assert_equal "/awesome/blog/posts/1", last_response.body
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 54fc1b208d..a434e49dbd 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -461,14 +461,6 @@ class RequestTest < ActiveSupport::TestCase
end
end
- test "head masquerading as get" do
- request = stub_request 'REQUEST_METHOD' => 'GET', "rack.methodoverride.original_method" => "HEAD"
- assert_equal "HEAD", request.method
- assert_equal "GET", request.request_method
- assert request.get?
- assert request.head?
- end
-
test "post masquerading as patch" do
request = stub_request 'REQUEST_METHOD' => 'PATCH', "rack.methodoverride.original_method" => "POST"
assert_equal "POST", request.method
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 82d1200f8e..4d699bd739 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -5,6 +5,35 @@ class ResponseTest < ActiveSupport::TestCase
@response = ActionDispatch::Response.new
end
+ def test_can_wait_until_commit
+ t = Thread.new {
+ @response.await_commit
+ }
+ @response.commit!
+ assert @response.committed?
+ assert t.join(0.5)
+ end
+
+ def test_stream_close
+ @response.stream.close
+ assert @response.stream.closed?
+ end
+
+ def test_stream_write
+ @response.stream.write "foo"
+ @response.stream.close
+ assert_equal "foo", @response.body
+ end
+
+ def test_write_after_close
+ @response.stream.close
+
+ e = assert_raises(IOError) do
+ @response.stream.write "omg"
+ end
+ assert_equal "closed stream", e.message
+ end
+
def test_response_body_encoding
body = ["hello".encode('utf-8')]
response = ActionDispatch::Response.new 200, {}, body
@@ -147,6 +176,35 @@ class ResponseTest < ActiveSupport::TestCase
ActionDispatch::Response.default_charset = original
end
end
+
+ test "read x_frame_options, x_content_type_options and x_xss_protection" do
+ ActionDispatch::Response.default_headers = {
+ 'X-Frame-Options' => 'DENY',
+ 'X-Content-Type-Options' => 'nosniff',
+ 'X-XSS-Protection' => '1;'
+ }
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('DENY', resp.headers['X-Frame-Options'])
+ assert_equal('nosniff', resp.headers['X-Content-Type-Options'])
+ assert_equal('1;', resp.headers['X-XSS-Protection'])
+ end
+
+ test "read custom default_header" do
+ ActionDispatch::Response.default_headers = {
+ 'X-XX-XXXX' => 'Here is my phone number'
+ }
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('Here is my phone number', resp.headers['X-XX-XXXX'])
+ end
+
end
class ResponseIntegrationTest < ActionDispatch::IntegrationTest
diff --git a/actionpack/test/dispatch/routing/concerns_test.rb b/actionpack/test/dispatch/routing/concerns_test.rb
new file mode 100644
index 0000000000..9f37701656
--- /dev/null
+++ b/actionpack/test/dispatch/routing/concerns_test.rb
@@ -0,0 +1,119 @@
+require 'abstract_unit'
+
+class RoutingConcernsTest < ActionDispatch::IntegrationTest
+ class Reviewable
+ def self.call(mapper, options = {})
+ mapper.resources :reviews, options
+ end
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ concern :commentable do |options|
+ resources :comments, options
+ end
+
+ concern :image_attachable do
+ resources :images, only: :index
+ end
+
+ concern :reviewable, Reviewable
+
+ resources :posts, concerns: [:commentable, :image_attachable, :reviewable] do
+ resource :video, concerns: :commentable do
+ concerns :reviewable, as: :video_reviews
+ end
+ end
+
+ resource :picture, concerns: :commentable do
+ resources :posts, concerns: :commentable
+ end
+
+ scope "/videos" do
+ concerns :commentable, except: :destroy
+ end
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ def test_accessing_concern_from_resources
+ get "/posts/1/comments"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/comments", post_comments_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_resource
+ get "/picture/comments"
+ assert_equal "200", @response.code
+ assert_equal "/picture/comments", picture_comments_path
+ end
+
+ def test_accessing_concern_from_nested_resource
+ get "/posts/1/video/comments"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/video/comments", post_video_comments_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_nested_resources
+ get "/picture/posts/1/comments"
+ assert_equal "200", @response.code
+ assert_equal "/picture/posts/1/comments", picture_post_comments_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_resources_with_more_than_one_concern
+ get "/posts/1/images"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/images", post_images_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_resources_using_only_option
+ get "/posts/1/image/1"
+ assert_equal "404", @response.code
+ end
+
+ def test_accessing_callable_concern_
+ get "/posts/1/reviews/1"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/reviews/1", post_review_path(post_id: 1, id: 1)
+ end
+
+ def test_callable_concerns_accept_options
+ get "/posts/1/video/reviews/1"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/video/reviews/1", post_video_video_review_path(post_id: 1, id: 1)
+ end
+
+ def test_accessing_concern_from_a_scope
+ get "/videos/comments"
+ assert_equal "200", @response.code
+ end
+
+ def test_concerns_accept_options
+ delete "/videos/comments/1"
+ assert_equal "404", @response.code
+ end
+
+ def test_with_an_invalid_concern_name
+ e = assert_raise ArgumentError do
+ ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ resources :posts, concerns: :foo
+ end
+ end
+ end
+
+ assert_equal "No concern named foo was found!", e.message
+ end
+
+ def test_concerns_executes_block_in_context_of_current_mapper
+ mapper = ActionDispatch::Routing::Mapper.new(ActionDispatch::Routing::RouteSet.new)
+ mapper.concern :test_concern do
+ resources :things
+ return self
+ end
+
+ assert_equal mapper, mapper.concerns(:test_concern)
+ end
+end
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
new file mode 100644
index 0000000000..97fc4f3e4b
--- /dev/null
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -0,0 +1,170 @@
+require 'minitest/autorun'
+require 'action_controller'
+require 'rails/engine'
+require 'action_dispatch/routing/inspector'
+
+module ActionDispatch
+ module Routing
+ class RoutesInspectorTest < ActiveSupport::TestCase
+ def setup
+ @set = ActionDispatch::Routing::RouteSet.new
+ @inspector = ActionDispatch::Routing::RoutesInspector.new
+ app = ActiveSupport::OrderedOptions.new
+ app.config = ActiveSupport::OrderedOptions.new
+ app.config.assets = ActiveSupport::OrderedOptions.new
+ app.config.assets.prefix = '/sprockets'
+ Rails.stubs(:application).returns(app)
+ Rails.stubs(:env).returns("development")
+ end
+
+ def draw(&block)
+ @set.draw(&block)
+ @inspector.format(@set.routes)
+ end
+
+ def test_displaying_routes_for_engines
+ engine = Class.new(Rails::Engine) do
+ def self.to_s
+ "Blog::Engine"
+ end
+ end
+ engine.routes.draw do
+ get '/cart', :to => 'cart#show'
+ end
+
+ output = draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ mount engine => "/blog", :as => "blog"
+ end
+
+ expected = [
+ "custom_assets GET /custom/assets(.:format) custom_assets#show",
+ " blog /blog Blog::Engine",
+ "\nRoutes for Blog::Engine:",
+ "cart GET /cart(.:format) cart#show"
+ ]
+ assert_equal expected, output
+ end
+
+ def test_cart_inspect
+ output = draw do
+ get '/cart', :to => 'cart#show'
+ end
+ assert_equal ["cart GET /cart(.:format) cart#show"], output
+ end
+
+ def test_inspect_shows_custom_assets
+ output = draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ end
+ assert_equal ["custom_assets GET /custom/assets(.:format) custom_assets#show"], output
+ end
+
+ def test_inspect_routes_shows_resources_route
+ output = draw do
+ resources :articles
+ end
+ expected = [
+ " articles GET /articles(.:format) articles#index",
+ " POST /articles(.:format) articles#create",
+ " new_article GET /articles/new(.:format) articles#new",
+ "edit_article GET /articles/:id/edit(.:format) articles#edit",
+ " article GET /articles/:id(.:format) articles#show",
+ " PATCH /articles/:id(.:format) articles#update",
+ " PUT /articles/:id(.:format) articles#update",
+ " DELETE /articles/:id(.:format) articles#destroy" ]
+ assert_equal expected, output
+ end
+
+ def test_inspect_routes_shows_root_route
+ output = draw do
+ root :to => 'pages#main'
+ end
+ assert_equal ["root GET / pages#main"], output
+ end
+
+ def test_inspect_routes_shows_dynamic_action_route
+ output = draw do
+ get 'api/:action' => 'api'
+ end
+ assert_equal [" GET /api/:action(.:format) api#:action"], output
+ end
+
+ def test_inspect_routes_shows_controller_and_action_only_route
+ output = draw do
+ get ':controller/:action'
+ end
+ assert_equal [" GET /:controller/:action(.:format) :controller#:action"], output
+ end
+
+ def test_inspect_routes_shows_controller_and_action_route_with_constraints
+ output = draw do
+ get ':controller(/:action(/:id))', :id => /\d+/
+ end
+ assert_equal [" GET /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"], output
+ end
+
+ def test_rake_routes_shows_route_with_defaults
+ output = draw do
+ get 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
+ end
+ assert_equal [%Q[ GET /photos/:id(.:format) photos#show {:format=>"jpg"}]], output
+ end
+
+ def test_rake_routes_shows_route_with_constraints
+ output = draw do
+ get 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
+ end
+ assert_equal [" GET /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"], output
+ end
+
+ class RackApp
+ def self.call(env)
+ end
+ end
+
+ def test_rake_routes_shows_route_with_rack_app
+ output = draw do
+ get 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
+ end
+ assert_equal [" GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output
+ end
+
+ def test_rake_routes_shows_route_with_rack_app_nested_with_dynamic_constraints
+ constraint = Class.new do
+ def to_s
+ "( my custom constraint )"
+ end
+ end
+
+ output = draw do
+ scope :constraint => constraint.new do
+ mount RackApp => '/foo'
+ end
+ end
+
+ assert_equal [" /foo #{RackApp.name} {:constraint=>( my custom constraint )}"], output
+ end
+
+ def test_rake_routes_dont_show_app_mounted_in_assets_prefix
+ output = draw do
+ get '/sprockets' => RackApp
+ end
+ assert_no_match(/RackApp/, output.first)
+ assert_no_match(/\/sprockets/, output.first)
+ end
+
+ def test_redirect
+ output = draw do
+ get "/foo" => redirect("/foo/bar"), :constraints => { :subdomain => "admin" }
+ get "/bar" => redirect(path: "/foo/bar", status: 307)
+ get "/foobar" => redirect{ "/foo/bar" }
+ end
+
+ assert_equal " foo GET /foo(.:format) redirect(301, /foo/bar) {:subdomain=>\"admin\"}", output[0]
+ assert_equal " bar GET /bar(.:format) redirect(307, path: /foo/bar)", output[1]
+ assert_equal "foobar GET /foobar(.:format) redirect(301)", output[2]
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index fed26d89f8..856248e2ac 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -2,7 +2,6 @@
require 'erb'
require 'abstract_unit'
require 'controller/fake_controllers'
-require 'active_support/core_ext/object/inclusion'
class TestRoutingMapper < ActionDispatch::IntegrationTest
SprocketsApp = lambda { |env|
@@ -482,11 +481,17 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get :preview, :on => :member
end
- resources :profiles, :param => :username do
+ resources :profiles, :param => :username, :username => /[a-z]+/ do
get :details, :on => :member
resources :messages
end
+ resources :orders do
+ constraints :download => /[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/ do
+ resources :downloads, :param => :download, :shallow => true
+ end
+ end
+
scope :as => "routes" do
get "/c/:id", :as => :collision, :to => "collision#show"
get "/collision", :to => "collision#show"
@@ -506,7 +511,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
resources :todos, :id => /\d+/
end
- scope '/countries/:country', :constraints => lambda { |params, req| params[:country].in?(["all", "France"]) } do
+ scope '/countries/:country', :constraints => lambda { |params, req| %w(all France).include?(params[:country]) } do
get '/', :to => 'countries#index'
get '/cities', :to => 'countries#cities'
end
@@ -1794,7 +1799,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/movies/00001'
assert_equal 'Not Found', @response.body
- assert_raises(ActionController::RoutingError){ movie_path(:id => '00001') }
+ assert_raises(ActionController::UrlGenerationError){ movie_path(:id => '00001') }
get '/movies/0001/reviews'
assert_equal 'reviews#index', @response.body
@@ -1802,7 +1807,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/movies/00001/reviews'
assert_equal 'Not Found', @response.body
- assert_raises(ActionController::RoutingError){ movie_reviews_path(:movie_id => '00001') }
+ assert_raises(ActionController::UrlGenerationError){ movie_reviews_path(:movie_id => '00001') }
get '/movies/0001/reviews/0001'
assert_equal 'reviews#show', @response.body
@@ -1810,7 +1815,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/movies/00001/reviews/0001'
assert_equal 'Not Found', @response.body
- assert_raises(ActionController::RoutingError){ movie_path(:movie_id => '00001', :id => '00001') }
+ assert_raises(ActionController::UrlGenerationError){ movie_path(:movie_id => '00001', :id => '00001') }
get '/movies/0001/trailer'
assert_equal 'trailers#show', @response.body
@@ -1818,7 +1823,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/movies/00001/trailer'
assert_equal 'Not Found', @response.body
- assert_raises(ActionController::RoutingError){ movie_trailer_path(:movie_id => '00001') }
+ assert_raises(ActionController::UrlGenerationError){ movie_trailer_path(:movie_id => '00001') }
end
def test_only_should_be_read_from_scope
@@ -2137,7 +2142,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/lists/2/todos/1'
assert_equal 'Not Found', @response.body
- assert_raises(ActionController::RoutingError){ list_todo_path(:list_id => '2', :id => '1') }
+ assert_raises(ActionController::UrlGenerationError){ list_todo_path(:list_id => '2', :id => '1') }
end
def test_named_routes_collision_is_avoided_unless_explicitly_given_as
@@ -2243,6 +2248,23 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal '34', @request.params[:id]
end
+ def test_custom_param_constraint
+ get '/profiles/bob1'
+ assert_equal 404, @response.status
+
+ get '/profiles/bob1/details'
+ assert_equal 404, @response.status
+
+ get '/profiles/bob1/messages/34'
+ assert_equal 404, @response.status
+ end
+
+ def test_shallow_custom_param
+ get '/downloads/0c0c0b68-d24b-11e1-a861-001ff3fffe6f.zip'
+ assert_equal 'downloads#show', @response.body
+ assert_equal '0c0c0b68-d24b-11e1-a861-001ff3fffe6f', @request.params[:download]
+ end
+
private
def with_https
old_https = https?
@@ -2603,7 +2625,7 @@ class TestNamedRouteUrlHelpers < ActionDispatch::IntegrationTest
get "/categories/1"
assert_response :success
- assert_raises(ActionController::RoutingError) { product_path(nil) }
+ assert_raises(ActionController::UrlGenerationError) { product_path(nil) }
end
end
@@ -2679,3 +2701,30 @@ class TestInvalidUrls < ActionDispatch::IntegrationTest
end
end
end
+
+class TestOptionalRootSegments < ActionDispatch::IntegrationTest
+ stub_controllers do |routes|
+ Routes = routes
+ Routes.draw do
+ get '/(page/:page)', :to => 'pages#index', :as => :root
+ end
+ end
+
+ def app
+ Routes
+ end
+
+ include Routes.url_helpers
+
+ def test_optional_root_segments
+ get '/'
+ assert_equal 'pages#index', @response.body
+ assert_equal '/', root_path
+
+ get '/page/1'
+ assert_equal 'pages#index', @response.body
+ assert_equal '1', @request.params[:page]
+ assert_equal '/page/1', root_path('1')
+ assert_equal '/page/1', root_path(:page => '1')
+ end
+end
diff --git a/actionpack/test/fixtures/digestor/comments/_comment.html.erb b/actionpack/test/fixtures/digestor/comments/_comment.html.erb
new file mode 100644
index 0000000000..f172e749da
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/comments/_comment.html.erb
@@ -0,0 +1 @@
+Great story, bro!
diff --git a/actionpack/test/fixtures/digestor/comments/_comments.html.erb b/actionpack/test/fixtures/digestor/comments/_comments.html.erb
new file mode 100644
index 0000000000..c28646a283
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/comments/_comments.html.erb
@@ -0,0 +1 @@
+<%= render partial: "comments/comment", collection: commentable.comments %>
diff --git a/actionpack/test/fixtures/digestor/events/_event.html.erb b/actionpack/test/fixtures/digestor/events/_event.html.erb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/events/_event.html.erb
diff --git a/actionpack/test/fixtures/digestor/messages/_form.html.erb b/actionpack/test/fixtures/digestor/messages/_form.html.erb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/_form.html.erb
diff --git a/actionpack/test/fixtures/digestor/messages/_header.html.erb b/actionpack/test/fixtures/digestor/messages/_header.html.erb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/_header.html.erb
diff --git a/actionpack/test/fixtures/digestor/messages/_message.html.erb b/actionpack/test/fixtures/digestor/messages/_message.html.erb
new file mode 100644
index 0000000000..406a0fb848
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/_message.html.erb
@@ -0,0 +1 @@
+THIS BE WHERE THEM MESSAGE GO, YO! \ No newline at end of file
diff --git a/actionpack/test/fixtures/digestor/messages/actions/_move.html.erb b/actionpack/test/fixtures/digestor/messages/actions/_move.html.erb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/actions/_move.html.erb
diff --git a/actionpack/test/fixtures/digestor/messages/edit.html.erb b/actionpack/test/fixtures/digestor/messages/edit.html.erb
new file mode 100644
index 0000000000..a9e0a88e32
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/edit.html.erb
@@ -0,0 +1,5 @@
+<%= render "header" %>
+<%= render partial: "form" %>
+<%= render @message %>
+<%= render ( @message.events ) %>
+<%= render :partial => "comments/comment", :collection => @message.comments %>
diff --git a/actionpack/test/fixtures/digestor/messages/index.html.erb b/actionpack/test/fixtures/digestor/messages/index.html.erb
new file mode 100644
index 0000000000..1937b652e4
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/index.html.erb
@@ -0,0 +1,2 @@
+<%= render @messages %>
+<%= render @events %>
diff --git a/actionpack/test/fixtures/digestor/messages/show.html.erb b/actionpack/test/fixtures/digestor/messages/show.html.erb
new file mode 100644
index 0000000000..9f73345a9f
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/show.html.erb
@@ -0,0 +1,9 @@
+<%# Template Dependency: messages/message %>
+<%= render "header" %>
+<%= render "comments/comments" %>
+
+<%= render "messages/actions/move" %>
+
+<%= render @message.history.events %>
+
+<%# render "something_missing" %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/project.rb b/actionpack/test/fixtures/project.rb
index 2b53d39ed5..c124a9e605 100644
--- a/actionpack/test/fixtures/project.rb
+++ b/actionpack/test/fixtures/project.rb
@@ -1,3 +1,3 @@
class Project < ActiveRecord::Base
- has_and_belongs_to_many :developers, :uniq => true
+ has_and_belongs_to_many :developers, -> { uniq }
end
diff --git a/actionpack/test/fixtures/reply.rb b/actionpack/test/fixtures/reply.rb
index 0d3b0a7c98..047522c55b 100644
--- a/actionpack/test/fixtures/reply.rb
+++ b/actionpack/test/fixtures/reply.rb
@@ -1,6 +1,6 @@
class Reply < ActiveRecord::Base
- scope :base, -> { scoped }
- belongs_to :topic, :include => [:replies]
+ scope :base, -> { all }
+ belongs_to :topic, -> { includes(:replies) }
belongs_to :developer
validates_presence_of :content
diff --git a/actionpack/test/fixtures/test/_changing_priority.html.erb b/actionpack/test/fixtures/test/_changing_priority.html.erb
new file mode 100644
index 0000000000..3225efc49a
--- /dev/null
+++ b/actionpack/test/fixtures/test/_changing_priority.html.erb
@@ -0,0 +1 @@
+HTML \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_changing_priority.json.erb b/actionpack/test/fixtures/test/_changing_priority.json.erb
new file mode 100644
index 0000000000..7fa41dce66
--- /dev/null
+++ b/actionpack/test/fixtures/test/_changing_priority.json.erb
@@ -0,0 +1 @@
+JSON \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_first_json_partial.json.erb b/actionpack/test/fixtures/test/_first_json_partial.json.erb
new file mode 100644
index 0000000000..790ee896db
--- /dev/null
+++ b/actionpack/test/fixtures/test/_first_json_partial.json.erb
@@ -0,0 +1 @@
+<%= render :partial => "test/second_json_partial" %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_json_change_priority.json.erb b/actionpack/test/fixtures/test/_json_change_priority.json.erb
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/actionpack/test/fixtures/test/_json_change_priority.json.erb
diff --git a/actionpack/test/fixtures/test/_raise_indentation.html.erb b/actionpack/test/fixtures/test/_raise_indentation.html.erb
new file mode 100644
index 0000000000..f9a93728fe
--- /dev/null
+++ b/actionpack/test/fixtures/test/_raise_indentation.html.erb
@@ -0,0 +1,13 @@
+<p>First paragraph</p>
+<p>Second paragraph</p>
+<p>Third paragraph</p>
+<p>Fourth paragraph</p>
+<p>Fifth paragraph</p>
+<p>Sixth paragraph</p>
+<p>Seventh paragraph</p>
+<p>Eight paragraph</p>
+<p>Ninth paragraph</p>
+<p>Tenth paragraph</p>
+<%= raise "error here!" %>
+<p>Eleventh paragraph</p>
+<p>Twelfth paragraph</p> \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_second_json_partial.json.erb b/actionpack/test/fixtures/test/_second_json_partial.json.erb
new file mode 100644
index 0000000000..5ebb7f1afd
--- /dev/null
+++ b/actionpack/test/fixtures/test/_second_json_partial.json.erb
@@ -0,0 +1 @@
+Third level \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/change_priorty.html.erb b/actionpack/test/fixtures/test/change_priorty.html.erb
new file mode 100644
index 0000000000..5618977d05
--- /dev/null
+++ b/actionpack/test/fixtures/test/change_priorty.html.erb
@@ -0,0 +1,2 @@
+<%= render :partial => "test/json_change_priority", formats: :json %>
+HTML Template, but <%= render :partial => "test/changing_priority" %> partial \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/html_template.html.erb b/actionpack/test/fixtures/test/html_template.html.erb
new file mode 100644
index 0000000000..1bbc2b7f09
--- /dev/null
+++ b/actionpack/test/fixtures/test/html_template.html.erb
@@ -0,0 +1 @@
+<%= render :partial => "test/first_json_partial", formats: :json %> \ No newline at end of file
diff --git a/actionpack/test/template/active_model_helper_test.rb b/actionpack/test/template/active_model_helper_test.rb
index 24511df444..86bccdfade 100644
--- a/actionpack/test/template/active_model_helper_test.rb
+++ b/actionpack/test/template/active_model_helper_test.rb
@@ -41,6 +41,19 @@ class ActiveModelHelperTest < ActionView::TestCase
)
end
+ def test_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><select name="post[author_name]" id="post_author_name"><option value="a">a</option>\n<option value="b">b</option></select></div>),
+ select("post", "author_name", [:a, :b])
+ )
+ end
+
+ def test_select_with_errors_and_blank_option
+ expected_dom = %(<div class="field_with_errors"><select name="post[author_name]" id="post_author_name"><option value="">Choose one...</option>\n<option value="a">a</option>\n<option value="b">b</option></select></div>)
+ assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], :include_blank => 'Choose one...'))
+ assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], :prompt => 'Choose one...'))
+ end
+
def test_date_select_with_errors
assert_dom_equal(
%(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n</div>),
@@ -82,4 +95,5 @@ class ActiveModelHelperTest < ActionView::TestCase
ensure
ActionView::Base.field_error_proc = old_proc if old_proc
end
+
end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index bcc55189b9..25d85c47c7 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -65,7 +65,6 @@ class AssetTagHelperTest < ActionView::TestCase
%(auto_discovery_link_tag) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:rss)) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:atom)) => %(<link href="http://www.example.com" rel="alternate" title="ATOM" type="application/atom+xml" />),
- %(auto_discovery_link_tag(:xml)) => %(<link href="http://www.example.com" rel="alternate" title="XML" type="application/xml" />),
%(auto_discovery_link_tag(:rss, :action => "feed")) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:rss, "http://localhost/feed")) => %(<link href="http://localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:rss, "//localhost/feed")) => %(<link href="//localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
@@ -299,6 +298,16 @@ class AssetTagHelperTest < ActionView::TestCase
%(audio_tag(["audio.mp3", "audio.ogg"], :autobuffer => true, :controls => true)) => %(<audio autobuffer="autobuffer" controls="controls"><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>)
}
+ def test_autodiscovery_link_tag_deprecated_types
+ result = nil
+ assert_deprecated do
+ result = auto_discovery_link_tag(:xml)
+ end
+
+ expected = %(<link href="http://www.example.com" rel="alternate" title="XML" type="application/xml" />)
+ assert_equal expected, result
+ end
+
def test_auto_discovery_link_tag
AutoDiscoveryToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
end
@@ -417,6 +426,15 @@ class AssetTagHelperTest < ActionView::TestCase
assert_raise(ArgumentError) { javascript_include_tag(:defaults) }
end
+ def test_all_javascript_expansion_not_include_application_js_if_not_exists
+ FileUtils.mv(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'application.js'),
+ File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'application.bak'))
+ assert_no_match(/application\.js/, javascript_include_tag(:all))
+ ensure
+ FileUtils.mv(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'application.bak'),
+ File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'application.js'))
+ end
+
def test_stylesheet_path
ENV["RAILS_ASSET_ID"] = ""
StylePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
diff --git a/actionpack/test/template/capture_helper_test.rb b/actionpack/test/template/capture_helper_test.rb
index 17469f8c3e..234ac3252d 100644
--- a/actionpack/test/template/capture_helper_test.rb
+++ b/actionpack/test/template/capture_helper_test.rb
@@ -56,7 +56,7 @@ class CaptureHelperTest < ActionView::TestCase
def test_content_for_with_multiple_calls_and_flush
assert ! content_for?(:title)
content_for :title, 'foo'
- content_for :title, 'bar', true
+ content_for :title, 'bar', flush: true
assert_equal 'bar', content_for(:title)
end
@@ -75,7 +75,7 @@ class CaptureHelperTest < ActionView::TestCase
content_for :title do
'foo'
end
- content_for :title, true do
+ content_for :title, flush: true do
'bar'
end
assert_equal 'bar', content_for(:title)
@@ -86,7 +86,7 @@ class CaptureHelperTest < ActionView::TestCase
content_for :title do
'foo'
end
- content_for :title, nil, true do
+ content_for :title, nil, flush: true do
'bar'
end
assert_equal 'bar', content_for(:title)
@@ -97,7 +97,7 @@ class CaptureHelperTest < ActionView::TestCase
content_for :title do
'foo'
end
- content_for :title, false do
+ content_for :title, flush: false do
'bar'
end
assert_equal 'foobar', content_for(:title)
@@ -117,11 +117,11 @@ class CaptureHelperTest < ActionView::TestCase
def test_content_for_with_whitespace_block_and_flush
assert ! content_for?(:title)
content_for :title, 'foo'
- content_for :title, true do
+ content_for :title, flush: true do
output_buffer << " \n "
nil
end
- content_for :title, 'bar', true
+ content_for :title, 'bar', flush: true
assert_equal 'bar', content_for(:title)
end
@@ -131,9 +131,9 @@ class CaptureHelperTest < ActionView::TestCase
assert_equal nil, content_for(:title) { output_buffer << 'bar'; nil }
assert_equal nil, content_for(:title) { output_buffer << " \n "; nil }
assert_equal 'foobar', content_for(:title)
- assert_equal nil, content_for(:title, 'foo', true)
- assert_equal nil, content_for(:title, true) { output_buffer << 'bar'; nil }
- assert_equal nil, content_for(:title, true) { output_buffer << " \n "; nil }
+ assert_equal nil, content_for(:title, 'foo', flush: true)
+ assert_equal nil, content_for(:title, flush: true) { output_buffer << 'bar'; nil }
+ assert_equal nil, content_for(:title, flush: true) { output_buffer << " \n "; nil }
assert_equal 'bar', content_for(:title)
end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index ff85a675a2..a4da7cd4b0 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1243,6 +1243,35 @@ class DateHelperTest < ActionView::TestCase
:prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year', :hour => 'Choose hour', :minute => 'Choose minute'})
end
+ def test_select_datetime_with_custom_hours
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="">Choose year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
+ expected << "</select>\n"
+
+ expected << " &mdash; "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="">Choose hour</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n)
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :start_hour => 1, :end_hour => 9, :prefix => "date[first]",
+ :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year', :hour => 'Choose hour', :minute => 'Choose minute'})
+ end
+
def test_select_datetime_with_hidden
expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n)
expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n)
@@ -2629,6 +2658,30 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true)
end
+ def test_datetime_select_disabled_and_discard_minute
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" disabled="disabled" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" disabled="disabled" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " &mdash; "
+
+ expected << %{<select id="post_updated_at_4i" disabled="disabled" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<input type="hidden" id="post_updated_at_5i" disabled="disabled" name="post[updated_at(5i)]" value="16" />\n}
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true, :disabled => true)
+ end
+
def test_datetime_select_invalid_order
@post = Post.new
@post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
diff --git a/actionpack/test/template/digestor_test.rb b/actionpack/test/template/digestor_test.rb
new file mode 100644
index 0000000000..9c84f3107f
--- /dev/null
+++ b/actionpack/test/template/digestor_test.rb
@@ -0,0 +1,157 @@
+require 'abstract_unit'
+require 'fileutils'
+
+class FixtureTemplate
+ attr_reader :source
+
+ def initialize(template_path)
+ @source = File.read(template_path)
+ rescue Errno::ENOENT
+ raise ActionView::MissingTemplate.new([], "", [], true, [])
+ end
+end
+
+class FixtureFinder
+ FIXTURES_DIR = "#{File.dirname(__FILE__)}/../fixtures/digestor"
+ TMP_DIR = "#{File.dirname(__FILE__)}/../tmp"
+
+ def find(logical_name, keys, partial, options)
+ FixtureTemplate.new("#{TMP_DIR}/digestor/#{partial ? logical_name.gsub(%r|/([^/]+)$|, '/_\1') : logical_name}.#{options[:formats].first}.erb")
+ end
+end
+
+class TemplateDigestorTest < ActionView::TestCase
+ def setup
+ FileUtils.cp_r FixtureFinder::FIXTURES_DIR, FixtureFinder::TMP_DIR
+ end
+
+ def teardown
+ FileUtils.rm_r File.join(FixtureFinder::TMP_DIR, "digestor")
+ ActionView::Digestor.cache.clear
+ end
+
+ def test_top_level_change_reflected
+ assert_digest_difference("messages/show") do
+ change_template("messages/show")
+ end
+ end
+
+ def test_explicit_dependency
+ assert_digest_difference("messages/show") do
+ change_template("messages/_message")
+ end
+ end
+
+ def test_second_level_dependency
+ assert_digest_difference("messages/show") do
+ change_template("comments/_comments")
+ end
+ end
+
+ def test_second_level_dependency_within_same_directory
+ assert_digest_difference("messages/show") do
+ change_template("messages/_header")
+ end
+ end
+
+ def test_third_level_dependency
+ assert_digest_difference("messages/show") do
+ change_template("comments/_comment")
+ end
+ end
+
+ def test_logging_of_missing_template
+ assert_logged "Couldn't find template for digesting: messages/something_missing.html" do
+ digest("messages/show")
+ end
+ end
+
+ def test_nested_template_directory
+ assert_digest_difference("messages/show") do
+ change_template("messages/actions/_move")
+ end
+ end
+
+ def test_dont_generate_a_digest_for_missing_templates
+ assert_equal '', digest("nothing/there")
+ end
+
+ def test_collection_dependency
+ assert_digest_difference("messages/index") do
+ change_template("messages/_message")
+ end
+
+ assert_digest_difference("messages/index") do
+ change_template("events/_event")
+ end
+ end
+
+ def test_collection_derived_from_record_dependency
+ assert_digest_difference("messages/show") do
+ change_template("events/_event")
+ end
+ end
+
+ def test_extra_whitespace_in_render_partial
+ assert_digest_difference("messages/edit") do
+ change_template("messages/_form")
+ end
+ end
+
+ def test_extra_whitespace_in_render_named_partial
+ assert_digest_difference("messages/edit") do
+ change_template("messages/_header")
+ end
+ end
+
+ def test_extra_whitespace_in_render_record
+ assert_digest_difference("messages/edit") do
+ change_template("messages/_message")
+ end
+ end
+
+ def test_extra_whitespace_in_render_with_parenthesis
+ assert_digest_difference("messages/edit") do
+ change_template("events/_event")
+ end
+ end
+
+ def test_old_style_hash_in_render_invocation
+ assert_digest_difference("messages/edit") do
+ change_template("comments/_comment")
+ end
+ end
+
+ private
+ def assert_logged(message)
+ log = StringIO.new
+ ActionView::Digestor.logger = Logger.new(log)
+
+ yield
+
+ log.rewind
+ assert_match message, log.read
+
+ ActionView::Digestor.logger = nil
+ end
+
+ def assert_digest_difference(template_name)
+ previous_digest = digest(template_name)
+ ActionView::Digestor.cache.clear
+
+ yield
+
+ assert previous_digest != digest(template_name), "digest didn't change"
+ ActionView::Digestor.cache.clear
+ end
+
+ def digest(template_name)
+ ActionView::Digestor.digest(template_name, :html, FixtureFinder.new)
+ end
+
+ def change_template(template_name)
+ File.open("#{FixtureFinder::TMP_DIR}/digestor/#{template_name}.html.erb", "w") do |f|
+ f.write "\nTHIS WAS CHANGED!"
+ end
+ end
+end
diff --git a/actionpack/test/template/erb/helper.rb b/actionpack/test/template/erb/helper.rb
index 799f9e4036..a1973068d5 100644
--- a/actionpack/test/template/erb/helper.rb
+++ b/actionpack/test/template/erb/helper.rb
@@ -1,5 +1,6 @@
module ERBTest
class ViewContext
+ include ActionView::Helpers::UrlHelper
include SharedTestRoutes.url_helpers
include ActionView::Helpers::TagHelper
include ActionView::Helpers::JavaScriptHelper
@@ -20,4 +21,4 @@ module ERBTest
"<%= #{str} do %>#{rest}<% end %>"
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/erb/tag_helper_test.rb b/actionpack/test/template/erb/tag_helper_test.rb
index 1724d6432d..84e328d8be 100644
--- a/actionpack/test/template/erb/tag_helper_test.rb
+++ b/actionpack/test/template/erb/tag_helper_test.rb
@@ -3,9 +3,6 @@ require "template/erb/helper"
module ERBTest
class TagHelperTest < BlockTestCase
-
- extend ActiveSupport::Testing::Declarative
-
test "percent equals works for content_tag and does not require parenthesis on method call" do
assert_equal "<div>Hello world</div>", render_content("content_tag :div", "Hello world")
end
diff --git a/actionpack/test/template/erb_util_test.rb b/actionpack/test/template/erb_util_test.rb
index ca2710e9b3..f1cb920963 100644
--- a/actionpack/test/template/erb_util_test.rb
+++ b/actionpack/test/template/erb_util_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'active_support/core_ext/object/inclusion'
class ErbUtilTest < ActiveSupport::TestCase
include ERB::Util
@@ -8,11 +7,11 @@ class ErbUtilTest < ActiveSupport::TestCase
define_method "test_html_escape_#{expected.gsub(/\W/, '')}" do
assert_equal expected, html_escape(given)
end
+ end
- unless given == '"'
- define_method "test_json_escape_#{expected.gsub(/\W/, '')}" do
- assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given)
- end
+ ERB::Util::JSON_ESCAPE.each do |given, expected|
+ define_method "test_json_escape_#{expected.gsub(/\W/, '')}" do
+ assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given)
end
end
@@ -40,13 +39,13 @@ class ErbUtilTest < ActiveSupport::TestCase
def test_rest_in_ascii
(0..127).to_a.map {|int| int.chr }.each do |chr|
- next if chr.in?('&"<>')
+ next if %('"&<>).include?(chr)
assert_equal chr, html_escape(chr)
end
end
def test_html_escape_once
- assert_equal '1 &lt; 2 &amp; 3', html_escape_once('1 < 2 &amp; 3')
+ assert_equal '1 &lt;&gt;&amp;&quot;&#x27; 2 &amp; 3', html_escape_once('1 <>&"\' 2 &amp; 3')
end
def test_html_escape_once_returns_unsafe_strings_when_passed_unsafe_strings
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 7da293ce23..246c4bfada 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
require 'controller/fake_models'
-require 'active_support/core_ext/object/inclusion'
class FormHelperTest < ActionView::TestCase
include RenderERBUtils
@@ -82,8 +81,6 @@ class FormHelperTest < ActionView::TestCase
@post.tags = []
@post.tags << Tag.new
- @blog_post = Blog::Post.new("And his name will be forty and four.", 44)
-
@car = Car.new("#000FFF")
end
@@ -1046,6 +1043,20 @@ class FormHelperTest < ActionView::TestCase
end
end
+ def test_form_for_requires_arguments
+ error = assert_raises(ArgumentError) do
+ form_for(nil, :html => { :id => 'create-post' }) do
+ end
+ end
+ assert_equal "First argument in form cannot contain nil or be empty", error.message
+
+ error = assert_raises(ArgumentError) do
+ form_for([nil, nil], :html => { :id => 'create-post' }) do
+ end
+ end
+ assert_equal "First argument in form cannot contain nil or be empty", error.message
+ end
+
def test_form_for
form_for(@post, :html => { :id => 'create-post' }) do |f|
concat f.label(:title) { "The Title" }
@@ -1155,7 +1166,9 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_with_model_using_relative_model_naming
- form_for(@blog_post) do |f|
+ blog_post = Blog::Post.new("And his name will be forty and four.", 44)
+
+ form_for(blog_post) do |f|
concat f.text_field :title
concat f.submit('Edit post')
end
@@ -2638,6 +2651,12 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_form_for_with_data_attributes
+ form_for(@post, data: { behavior: "stuff" }, remote: true) {}
+ assert_match %r|data-behavior="stuff"|, output_buffer
+ assert_match %r|data-remote="true"|, output_buffer
+ end
+
def test_fields_for_returns_block_result
output = fields_for(Post.new) { |f| "fields" }
assert_equal "fields", output
@@ -2660,7 +2679,7 @@ class FormHelperTest < ActionView::TestCase
def hidden_fields(method = nil)
txt = %{<div style="margin:0;padding:0;display:inline">}
txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
- if method && !method.to_s.in?(['get', 'post'])
+ if method && !%w(get post).include?(method.to_s)
txt << %{<input name="_method" type="hidden" value="#{method}" />}
end
txt << %{</div>}
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 2322fb0406..f908de865e 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
require 'tzinfo'
-require 'active_support/core_ext/object/inclusion'
class Map < Hash
def category
@@ -83,7 +82,7 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_collection_options_with_proc_for_disabled
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
- options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda{|p| p.author_name.in?(["Babe", "Cabe"]) })
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda {|p| %w(Babe Cabe).include?(p.author_name)})
)
end
@@ -1125,11 +1124,25 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_options_for_select_with_element_attributes
assert_dom_equal(
- "<option value=\"&lt;Denmark&gt;\" class=\"bold\">&lt;Denmark&gt;</option>\n<option value=\"USA\" onclick=\"alert('Hello World');\">USA</option>\n<option value=\"Sweden\">Sweden</option>\n<option value=\"Germany\">Germany</option>",
+ "<option value=\"&lt;Denmark&gt;\" class=\"bold\">&lt;Denmark&gt;</option>\n<option value=\"USA\" onclick=\"alert(&#x27;Hello World&#x27;);\">USA</option>\n<option value=\"Sweden\">Sweden</option>\n<option value=\"Germany\">Germany</option>",
options_for_select([ [ "<Denmark>", { :class => 'bold' } ], [ "USA", { :onclick => "alert('Hello World');" } ], [ "Sweden" ], "Germany" ])
)
end
+ def test_options_for_select_with_data_element
+ assert_dom_equal(
+ "<option value=\"&lt;Denmark&gt;\" data-test=\"bold\">&lt;Denmark&gt;</option>",
+ options_for_select([ [ "<Denmark>", { :data => { :test => 'bold' } } ] ])
+ )
+ end
+
+ def test_options_for_select_with_data_element_with_special_characters
+ assert_dom_equal(
+ "<option value=\"&lt;Denmark&gt;\" data-test=\"&lt;bold&gt;\">&lt;Denmark&gt;</option>",
+ options_for_select([ [ "<Denmark>", { :data => { :test => '<bold>' } } ] ])
+ )
+ end
+
def test_options_for_select_with_element_attributes_and_selection
assert_dom_equal(
"<option value=\"&lt;Denmark&gt;\">&lt;Denmark&gt;</option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
@@ -1144,13 +1157,21 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
- def test_option_html_attributes_from_without_hash
- assert_equal(
- {},
- option_html_attributes([ 'foo', 'bar' ])
+ def test_options_for_select_with_special_characters
+ assert_dom_equal(
+ "<option value=\"&lt;Denmark&gt;\" onclick=\"alert(&quot;&lt;code&gt;&quot;)\">&lt;Denmark&gt;</option>",
+ options_for_select([ [ "<Denmark>", { :onclick => %(alert("<code>")) } ] ])
)
end
+ def test_option_html_attributes_with_no_array_element
+ assert_equal({}, option_html_attributes('foo'))
+ end
+
+ def test_option_html_attributes_without_hash
+ assert_equal({}, option_html_attributes([ 'foo', 'bar' ]))
+ end
+
def test_option_html_attributes_with_single_element_hash
assert_equal(
{:class => 'fancy'},
@@ -1172,11 +1193,13 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
- def test_option_html_attributes_with_special_characters
- assert_equal(
- {:onclick => "alert(&quot;&lt;code&gt;&quot;)"},
- option_html_attributes([ 'foo', 'bar', { :onclick => %(alert("<code>")) } ])
- )
+ def test_option_html_attributes_with_multiple_hashes_does_not_modify_them
+ options1 = { class: 'fancy' }
+ options2 = { onclick: "alert('Hello World');" }
+ option_html_attributes([ 'foo', 'bar', options1, options2 ])
+
+ assert_equal({ class: 'fancy' }, options1)
+ assert_equal({ onclick: "alert('Hello World');" }, options2)
end
def test_grouped_collection_select
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 5d19e3274d..3c66a29754 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'active_support/core_ext/object/inclusion'
class FormTagHelperTest < ActionView::TestCase
include RenderERBUtils
@@ -16,7 +15,7 @@ class FormTagHelperTest < ActionView::TestCase
txt = %{<div style="margin:0;padding:0;display:inline">}
txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
- if method && !method.to_s.in?(['get','post'])
+ if method && !%w(get post).include?(method.to_s)
txt << %{<input name="_method" type="hidden" value="#{method}" />}
end
txt << %{</div>}
@@ -214,12 +213,30 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_select_tag_escapes_prompt
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "<script>alert(1337)</script>"
+ expected = %(<select id="places" name="places"><option value="">&lt;script&gt;alert(1337)&lt;/script&gt;</option><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
def test_select_tag_with_prompt_and_include_blank
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string", :include_blank => true
expected = %(<select name="places" id="places"><option value="">string</option><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>)
assert_dom_equal expected, actual
end
+ def test_select_tag_with_nil_option_tags_and_include_blank
+ actual = select_tag "places", nil, :include_blank => true
+ expected = %(<select id="places" name="places"><option value=""></option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_with_nil_option_tags_and_prompt
+ actual = select_tag "places", nil, :prompt => "string"
+ expected = %(<select id="places" name="places"><option value="">string</option></select>)
+ assert_dom_equal expected, actual
+ end
+
def test_text_area_tag_size_string
actual = text_area_tag "body", "hello world", "size" => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>)
@@ -374,18 +391,34 @@ class FormTagHelperTest < ActionView::TestCase
def test_submit_tag
assert_dom_equal(
- %(<input name='commit' data-disable-with="Saving..." onclick="alert('hello!')" type="submit" value="Save" />),
- submit_tag("Save", 'data-disable-with' => "Saving...", :onclick => "alert('hello!')")
+ %(<input name='commit' data-disable-with="Saving..." onclick="alert(&#x27;hello!&#x27;)" type="submit" value="Save" />),
+ submit_tag("Save", :onclick => "alert('hello!')", :data => { :disable_with => "Saving..." })
+ )
+ end
+
+ def test_submit_tag_with_no_onclick_options
+ assert_dom_equal(
+ %(<input name='commit' data-disable-with="Saving..." type="submit" value="Save" />),
+ submit_tag("Save", :data => { :disable_with => "Saving..." })
)
end
def test_submit_tag_with_confirmation
assert_dom_equal(
%(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />),
- submit_tag("Save", :confirm => "Are you sure?")
+ submit_tag("Save", :data => { :confirm => "Are you sure?" })
)
end
+ def test_submit_tag_with_deprecated_confirmation
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ %(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />),
+ submit_tag("Save", :confirm => "Are you sure?")
+ )
+ end
+ end
+
def test_button_tag
assert_dom_equal(
%(<button name="button" type="submit">Button</button>),
@@ -437,13 +470,39 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output)
end
+ def test_button_tag_with_confirmation
+ assert_dom_equal(
+ %(<button name="button" type="submit" data-confirm="Are you sure?">Save</button>),
+ button_tag("Save", :type => "submit", :data => { :confirm => "Are you sure?" })
+ )
+ end
+
+ def test_button_tag_with_deprecated_confirmation
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ %(<button name="button" type="submit" data-confirm="Are you sure?">Save</button>),
+ button_tag("Save", :type => "submit", :confirm => "Are you sure?")
+ )
+ end
+ end
+
def test_image_submit_tag_with_confirmation
assert_dom_equal(
%(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
- image_submit_tag("save.gif", :confirm => "Are you sure?")
+ image_submit_tag("save.gif", :data => { :confirm => "Are you sure?" })
)
end
+ def test_image_submit_tag_with_deprecated_confirmation
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ %(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
+ image_submit_tag("save.gif", :confirm => "Are you sure?")
+ )
+ end
+ end
+
+
def test_color_field_tag
expected = %{<input id="car" name="car" type="color" />}
assert_dom_equal(expected, color_field_tag("car"))
diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb
index fe7607ee26..4a9a382afa 100644
--- a/actionpack/test/template/javascript_helper_test.rb
+++ b/actionpack/test/template/javascript_helper_test.rb
@@ -42,6 +42,48 @@ class JavaScriptHelperTest < ActionView::TestCase
assert_instance_of ActiveSupport::SafeBuffer, escape_javascript(ActiveSupport::SafeBuffer.new(given))
end
+ def test_button_to_function
+ assert_deprecated "button_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead." do
+ assert_dom_equal %(<input type="button" onclick="alert(&#x27;Hello world!&#x27;);" value="Greeting" />),
+ button_to_function("Greeting", "alert('Hello world!')")
+ end
+ end
+
+ def test_button_to_function_with_onclick
+ assert_deprecated "button_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead." do
+ assert_dom_equal "<input onclick=\"alert(&#x27;Goodbye World :(&#x27;); alert(&#x27;Hello world!&#x27;);\" type=\"button\" value=\"Greeting\" />",
+ button_to_function("Greeting", "alert('Hello world!')", :onclick => "alert('Goodbye World :(')")
+ end
+ end
+
+ def test_button_to_function_without_function
+ assert_deprecated "button_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead." do
+ assert_dom_equal "<input onclick=\";\" type=\"button\" value=\"Greeting\" />",
+ button_to_function("Greeting")
+ end
+ end
+
+ def test_link_to_function
+ assert_deprecated "link_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead." do
+ assert_dom_equal %(<a href="#" onclick="alert(&#x27;Hello world!&#x27;); return false;">Greeting</a>),
+ link_to_function("Greeting", "alert('Hello world!')")
+ end
+ end
+
+ def test_link_to_function_with_existing_onclick
+ assert_deprecated "link_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead." do
+ assert_dom_equal %(<a href="#" onclick="confirm(&#x27;Sanity!&#x27;); alert(&#x27;Hello world!&#x27;); return false;">Greeting</a>),
+ link_to_function("Greeting", "alert('Hello world!')", :onclick => "confirm('Sanity!')")
+ end
+ end
+
+ def test_function_with_href
+ assert_deprecated "link_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead." do
+ assert_dom_equal %(<a href="http://example.com/" onclick="alert(&#x27;Hello world!&#x27;); return false;">Greeting</a>),
+ link_to_function("Greeting", "alert('Hello world!')", :href => 'http://example.com/')
+ end
+ end
+
def test_javascript_tag
self.output_buffer = 'foo'
diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb
index 1713ce935c..7f4c84929f 100644
--- a/actionpack/test/template/log_subscriber_test.rb
+++ b/actionpack/test/template/log_subscriber_test.rb
@@ -8,9 +8,10 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
def setup
super
- @controller = Object.new
- @controller.stubs(:_prefixes).returns(%w(test))
- @view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller)
+ view_paths = ActionController::Base.view_paths
+ lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"])
+ renderer = ActionView::Renderer.new(lookup_context)
+ @view = ActionView::Base.new(renderer, {})
Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH))
ActionView::LogSubscriber.attach_to :action_view
end
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
index ef9c5ce10c..073bd14783 100644
--- a/actionpack/test/template/lookup_context_test.rb
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -11,6 +11,17 @@ class LookupContextTest < ActiveSupport::TestCase
I18n.locale = :en
end
+ test "allows to override default_formats with ActionView::Base.default_formats" do
+ begin
+ formats = ActionView::Base.default_formats
+ ActionView::Base.default_formats = [:foo, :bar]
+
+ assert_equal [:foo, :bar], ActionView::LookupContext.new([]).default_formats
+ ensure
+ ActionView::Base.default_formats = formats
+ end
+ end
+
test "process view paths on initialization" do
assert_kind_of ActionView::PathSet, @lookup_context.view_paths
end
diff --git a/actionpack/test/controller/record_identifier_test.rb b/actionpack/test/template/record_identifier_test.rb
index eb38b81e85..22038110a5 100644
--- a/actionpack/test/controller/record_identifier_test.rb
+++ b/actionpack/test/template/record_identifier_test.rb
@@ -2,7 +2,7 @@ require 'abstract_unit'
require 'controller/fake_models'
class RecordIdentifierTest < ActiveSupport::TestCase
- include ActionController::RecordIdentifier
+ include ActionView::RecordIdentifier
def setup
@klass = Comment
@@ -37,4 +37,13 @@ class RecordIdentifierTest < ActiveSupport::TestCase
def test_dom_class_with_prefix
assert_equal "custom_prefix_#{@singular}", dom_class(@record, :custom_prefix)
end
+
+ def test_dom_id_as_singleton_method
+ @record.save
+ assert_equal "#{@singular}_1", ActionView::RecordIdentifier.dom_id(@record)
+ end
+
+ def test_dom_class_as_singleton_method
+ assert_equal @singular, ActionView::RecordIdentifier.dom_class(@record)
+ end
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 88ed8664c2..b26354e7cc 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -54,6 +54,16 @@ module RenderTestCases
assert_equal "Hello world", @view.render(:template => "test/one", :formats => [:html])
end
+ def test_render_partial_implicitly_use_format_of_the_rendered_partial
+ @view.lookup_context.formats = [:html]
+ assert_equal "Third level", @view.render(:template => "test/html_template")
+ end
+
+ def test_render_partial_use_last_prepended_format_for_partials_with_the_same_names
+ @view.lookup_context.formats = [:html]
+ assert_equal "\nHTML Template, but JSON partial", @view.render(:template => "test/change_priorty")
+ end
+
def test_render_template_with_a_missing_partial_of_another_format
@view.lookup_context.formats = [:html]
assert_raise ActionView::Template::Error, "Missing partial /missing with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder]}" do
@@ -177,6 +187,13 @@ module RenderTestCases
assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.", e.message
end
+ def test_render_partial_with_hyphen
+ e = assert_raises(ArgumentError) { @view.render(:partial => "test/a-in") }
+ assert_equal "The partial name (test/a-in) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores.", e.message
+ end
+
def test_render_partial_with_errors
e = assert_raises(ActionView::Template::Error) { @view.render(:partial => "test/raise") }
assert_match %r!method.*doesnt_exist!, e.message
@@ -186,6 +203,15 @@ module RenderTestCases
assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
end
+ def test_render_error_indentation
+ e = assert_raises(ActionView::Template::Error) { @view.render(:partial => "test/raise_indentation") }
+ error_lines = e.annoted_source_code.split("\n")
+ assert_match %r!error\shere!, e.message
+ assert_equal "11", e.line_number
+ assert_equal " 9: <p>Ninth paragraph</p>", error_lines.second
+ assert_equal " 10: <p>Tenth paragraph</p>", error_lines.third
+ end
+
def test_render_sub_template_with_errors
e = assert_raises(ActionView::Template::Error) { @view.render(:template => "test/sub_template_raise") }
assert_match %r!method.*doesnt_exist!, e.message
diff --git a/actionpack/test/template/sanitize_helper_test.rb b/actionpack/test/template/sanitize_helper_test.rb
index 4182af590e..7626cdf386 100644
--- a/actionpack/test/template/sanitize_helper_test.rb
+++ b/actionpack/test/template/sanitize_helper_test.rb
@@ -40,9 +40,9 @@ class SanitizeHelperTest < ActionView::TestCase
[nil, '', ' '].each do |blank|
stripped = strip_tags(blank)
assert_equal blank, stripped
- assert stripped.html_safe? unless blank.nil?
end
- assert strip_tags("<script>").html_safe?
+ assert_equal "", strip_tags("<script>")
+ assert_equal "something &lt;img onerror=alert(1337)", ERB::Util.html_escape(strip_tags("something <img onerror=alert(1337)"))
end
def test_sanitize_is_marked_safe
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index 322bea3fb0..86ba5f3b4d 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -59,6 +59,13 @@ class TestERBTemplate < ActiveSupport::TestCase
@context = Context.new
end
+ def test_mime_type_is_deprecated
+ template = new_template
+ assert_deprecated 'Template#mime_type is deprecated and will be removed' do
+ template.mime_type
+ end
+ end
+
def test_basic_template
@template = new_template
assert_equal "Hello", render
@@ -84,7 +91,7 @@ class TestERBTemplate < ActiveSupport::TestCase
def test_locals
@template = new_template("<%= my_local %>")
@template.locals = [:my_local]
- assert_equal "I'm a local", render(:my_local => "I'm a local")
+ assert_equal "I am a local", render(:my_local => "I am a local")
end
def test_restores_buffer
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index a3ab091c6c..c0f694b2bf 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -107,8 +107,8 @@ class TextHelperTest < ActionView::TestCase
end
def test_truncate_with_link_options
- assert_equal "Here's a long test and I...<a href=\"#\">Continue</a>",
- truncate("Here's a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' }
+ assert_equal "Here is a long test and ...<a href=\"#\">Continue</a>",
+ truncate("Here is a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' }
end
def test_truncate_should_be_html_safe
@@ -149,8 +149,8 @@ class TextHelperTest < ActionView::TestCase
end
def test_truncate_with_block_should_escape_the_block
- assert_equal "Here's a long test and I...&lt;script&gt;alert('foo');&lt;/script&gt;",
- truncate("Here's a long test and I need a continue to read link", :length => 27) { "<script>alert('foo');</script>" }
+ assert_equal "Here is a long test and ...&lt;script&gt;alert(&#x27;foo&#x27;);&lt;/script&gt;",
+ truncate("Here is a long test and I need a continue to read link", :length => 27) { "<script>alert('foo');</script>" }
end
def test_highlight_should_be_html_safe
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index 62608a727f..9c4271f19b 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -20,9 +20,9 @@ class UrlHelperTest < ActiveSupport::TestCase
get "/article/:id" => "foo#article", :as => :article
end
+ include ActionView::Helpers::UrlHelper
include routes.url_helpers
- include ActionView::Helpers::UrlHelper
include ActionView::Helpers::JavaScriptHelper
include ActionDispatch::Assertions::DomAssertions
include ActionView::Context
@@ -90,17 +90,35 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_button_to_with_javascript_confirm
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
- button_to("Hello", "http://www.example.com", :confirm => "Are you sure?")
+ button_to("Hello", "http://www.example.com", :data => { :confirm => "Are you sure?" })
)
end
+ def test_button_to_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :confirm => "Are you sure?")
+ )
+ end
+ end
+
def test_button_to_with_javascript_disable_with
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input data-disable-with=\"Greeting...\" type=\"submit\" value=\"Hello\" /></div></form>",
- button_to("Hello", "http://www.example.com", 'data-disable-with' => "Greeting...")
+ button_to("Hello", "http://www.example.com", :data => { :disable_with => "Greeting..." })
)
end
+ def test_button_to_with_javascript_deprecated_disable_with
+ assert_deprecated ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input data-disable-with=\"Greeting...\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :disable_with => "Greeting...")
+ )
+ end
+ end
+
def test_button_to_with_remote_and_form_options
assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"custom-class\" data-remote=\"true\" data-type=\"json\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :remote => true, :form => { :class => "custom-class", "data-type" => "json" } )
end
@@ -108,10 +126,35 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_button_to_with_remote_and_javascript_confirm
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
- button_to("Hello", "http://www.example.com", :remote => true, :confirm => "Are you sure?")
+ button_to("Hello", "http://www.example.com", :remote => true, :data => { :confirm => "Are you sure?" })
+ )
+ end
+
+ def test_button_to_with_remote_and_javascript_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :remote => true, :confirm => "Are you sure?")
+ )
+ end
+ end
+
+ def test_button_to_with_remote_and_javascript_disable_with
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-disable-with=\"Greeting...\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :remote => true, :data => { :disable_with => "Greeting..." })
)
end
+ def test_button_to_with_remote_and_javascript_deprecated_disable_with
+ assert_deprecated ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-disable-with=\"Greeting...\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :remote => true, :disable_with => "Greeting...")
+ )
+ end
+ end
+
def test_button_to_with_remote_false
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>",
@@ -201,25 +244,46 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_link_tag_with_custom_onclick
link = link_to("Hello", "http://www.example.com", :onclick => "alert('yay!')")
- expected = %{<a href="http://www.example.com" onclick="alert('yay!')">Hello</a>}
+ expected = %{<a href="http://www.example.com" onclick="alert(&#x27;yay!&#x27;)">Hello</a>}
assert_dom_equal expected, link
end
def test_link_tag_with_javascript_confirm
assert_dom_equal(
"<a href=\"http://www.example.com\" data-confirm=\"Are you sure?\">Hello</a>",
- link_to("Hello", "http://www.example.com", :confirm => "Are you sure?")
+ link_to("Hello", "http://www.example.com", :data => { :confirm => "Are you sure?" })
)
assert_dom_equal(
- "<a href=\"http://www.example.com\" data-confirm=\"You can't possibly be sure, can you?\">Hello</a>",
- link_to("Hello", "http://www.example.com", :confirm => "You can't possibly be sure, can you?")
+ "<a href=\"http://www.example.com\" data-confirm=\"You cant possibly be sure, can you?\">Hello</a>",
+ link_to("Hello", "http://www.example.com", :data => { :confirm => "You cant possibly be sure, can you?" })
)
assert_dom_equal(
- "<a href=\"http://www.example.com\" data-confirm=\"You can't possibly be sure,\n can you?\">Hello</a>",
- link_to("Hello", "http://www.example.com", :confirm => "You can't possibly be sure,\n can you?")
+ "<a href=\"http://www.example.com\" data-confirm=\"You cant possibly be sure,\n can you?\">Hello</a>",
+ link_to("Hello", "http://www.example.com", :data => { :confirm => "You cant possibly be sure,\n can you?" })
)
end
+ def test_link_tag_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<a href=\"http://www.example.com\" data-confirm=\"Are you sure?\">Hello</a>",
+ link_to("Hello", "http://www.example.com", :confirm => "Are you sure?")
+ )
+ end
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<a href=\"http://www.example.com\" data-confirm=\"You cant possibly be sure, can you?\">Hello</a>",
+ link_to("Hello", "http://www.example.com", :confirm => "You cant possibly be sure, can you?")
+ )
+ end
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<a href=\"http://www.example.com\" data-confirm=\"You cant possibly be sure,\n can you?\">Hello</a>",
+ link_to("Hello", "http://www.example.com", :confirm => "You cant possibly be sure,\n can you?")
+ )
+ end
+ end
+
def test_link_to_with_remote
assert_dom_equal(
"<a href=\"http://www.example.com\" data-remote=\"true\">Hello</a>",
@@ -265,18 +329,37 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_link_tag_using_post_javascript_and_confirm
assert_dom_equal(
"<a href=\"http://www.example.com\" data-method=\"post\" rel=\"nofollow\" data-confirm=\"Are you serious?\">Hello</a>",
- link_to("Hello", "http://www.example.com", :method => :post, :confirm => "Are you serious?")
+ link_to("Hello", "http://www.example.com", :method => :post, :data => { :confirm => "Are you serious?" })
)
end
+ def test_link_tag_using_post_javascript_and_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<a href=\"http://www.example.com\" data-method=\"post\" rel=\"nofollow\" data-confirm=\"Are you serious?\">Hello</a>",
+ link_to("Hello", "http://www.example.com", :method => :post, :confirm => "Are you serious?")
+ )
+ end
+ end
+
def test_link_tag_using_delete_javascript_and_href_and_confirm
assert_dom_equal(
"<a href='\#' rel=\"nofollow\" data-confirm=\"Are you serious?\" data-method=\"delete\">Destroy</a>",
- link_to("Destroy", "http://www.example.com", :method => :delete, :href => '#', :confirm => "Are you serious?"),
+ link_to("Destroy", "http://www.example.com", :method => :delete, :href => '#', :data => { :confirm => "Are you serious?" }),
"When specifying url, form should be generated with it, but not this.href"
)
end
+ def test_link_tag_using_delete_javascript_and_href_and_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead" do
+ assert_dom_equal(
+ "<a href='\#' rel=\"nofollow\" data-confirm=\"Are you serious?\" data-method=\"delete\">Destroy</a>",
+ link_to("Destroy", "http://www.example.com", :method => :delete, :href => '#', :confirm => "Are you serious?"),
+ "When specifying url, form should be generated with it, but not this.href"
+ )
+ end
+ end
+
def test_link_tag_with_block
assert_dom_equal '<a href="/"><span>Example site</span></a>',
link_to('/') { content_tag(:span, 'Example site') }
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 847ae7f237..9d0ff5ba99 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,5 +1,22 @@
## Rails 4.0.0 (unreleased) ##
+* Changed inclusion and exclusion validators to accept a symbol for `:in` option.
+
+ This allows to use dynamic inclusion/exclusion values using methods, besides the current lambda/proc support.
+
+ *Gabriel Sobrinho*
+
+* `AM::Validation#validates` ability to pass custom exception to `:strict` option.
+
+ *Bogdan Gusiev*
+
+* Changed `ActiveModel::Serializers::Xml::Serializer#add_associations` to by default
+ propagate `:skip_types, :dasherize, :camelize` keys to included associations.
+ It can be overriden on each association by explicitly specifying the option on one
+ or more associations
+
+ *Anthony Alberto*
+
* Changed `AM::Serializers::JSON.include_root_in_json' default value to false.
Now, AM Serializers and AR objects have the same default behaviour. Fixes #6578.
@@ -39,194 +56,4 @@
* When `^` or `$` are used in the regular expression provided to `validates_format_of` and the :multiline option is not set to true, an exception will be raised. This is to prevent security vulnerabilities when using `validates_format_of`. The problem is described in detail in the Rails security guide.
-## Rails 3.2.6 (Jun 12, 2012) ##
-
-* No changes.
-
-## Rails 3.2.5 (Jun 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.4 (May 31, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.3 (March 30, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.2 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.1 (January 26, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.0 (January 20, 2012) ##
-
-* Deprecated `define_attr_method` in `ActiveModel::AttributeMethods`, because this only existed to
- support methods like `set_table_name` in Active Record, which are themselves being deprecated.
-
- *Jon Leighton*
-
-* Add ActiveModel::Errors#added? to check if a specific error has been added *Martin Svalin*
-
-* Add ability to define strict validation(with :strict => true option) that always raises exception when fails *Bogdan Gusiev*
-
-* Deprecate "Model.model_name.partial_path" in favor of "model.to_partial_path" *Grant Hutchins, Peter Jaros*
-
-* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior *Bogdan Gusiev*
-
-
-## Rails 3.1.3 (November 20, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.2 (November 18, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.1 (October 7, 2011) ##
-
-* Remove hard dependency on bcrypt-ruby to avoid make ActiveModel dependent on a binary library.
- You must add the gem explicitly to your Gemfile if you want use ActiveModel::SecurePassword:
-
- gem 'bcrypt-ruby', '~> 3.0.0'
-
- See GH #2687. *Guillermo Iguaran*
-
-
-## Rails 3.1.0 (August 30, 2011) ##
-
-* Alternate I18n namespace lookup is no longer supported.
- Instead of "activerecord.models.admins.post", do "activerecord.models.admins/post" instead *José Valim*
-
-* attr_accessible and friends now accepts :as as option to specify a role *Josh Kalderimis*
-
-* Add support for proc or lambda as an option for InclusionValidator,
- ExclusionValidator, and FormatValidator *Prem Sichanugrist*
-
- You can now supply Proc, lambda, or anything that respond to #call in those
- validations, and it will be called with current record as an argument.
- That given proc or lambda must returns an object which respond to #include? for
- InclusionValidator and ExclusionValidator, and returns a regular expression
- object for FormatValidator.
-
-* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting *DHH*
-
-* ActiveModel::AttributeMethods allows attributes to be defined on demand *Alexander Uvarov*
-
-* Add support for selectively enabling/disabling observers *Myron Marston*
-
-
-## Rails 3.0.12 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.0.11 (November 18, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.10 (August 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.9 (June 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.8 (June 7, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.7 (April 18, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.6 (April 5, 2011) ##
-
-* Fix when database column name has some symbolic characters (e.g. Oracle CASE# VARCHAR2(20)) #5818 #6850 *Robert Pankowecki, Santiago Pastorino*
-
-* Fix length validation for fixnums #6556 *Andriy Tyurnikov*
-
-* Fix i18n key collision with namespaced models #6448 *yves.senn*
-
-
-## Rails 3.0.5 (February 26, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.4 (February 8, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.3 (November 16, 2010) ##
-
-* No changes.
-
-
-## Rails 3.0.2 (November 15, 2010) ##
-
-* No changes
-
-
-## Rails 3.0.1 (October 15, 2010) ##
-
-* No Changes, just a version bump.
-
-
-## Rails 3.0.0 (August 29, 2010) ##
-
-* Added ActiveModel::MassAssignmentSecurity *Eric Chapweske, Josh Kalderimis*
-
-* JSON supports a custom root option: to_json(:root => 'custom') #4515 *Jatinder Singh*
-
-* #new_record? and #destroyed? were removed from ActiveModel::Lint. Use
- persisted? instead. A model is persisted if it's not a new_record? and it was
- not destroyed? *MG*
-
-* Added validations reflection in ActiveModel::Validations *JV*
-
- Model.validators
- Model.validators_on(:field)
-
-* #to_key was added to ActiveModel::Lint so we can generate DOM IDs for
- AMo objects with composite keys *MG*
-
-* ActiveModel::Observer#add_observer!
-
- It has a custom hook to define after_find that should really be in a
- ActiveRecord::Observer subclass:
-
- def add_observer!(klass)
- klass.add_observer(self)
- klass.class_eval 'def after_find() end' unless klass.respond_to?(:after_find)
- end
-
-* Change the ActiveModel::Base.include_root_in_json default to true for Rails 3 *DHH*
-
-* Add validates_format_of :without => /regexp/ option. #430 *Elliot Winkler, Peer Allan*
-
- Example :
-
- validates_format_of :subdomain, :without => /www|admin|mail/
-
-* Introduce validates_with to encapsulate attribute validations in a class. #2630 *Jeff Dean*
-
-* Extracted from Active Record and Active Resource.
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activemodel/CHANGELOG.md) for previous changes.
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index f6bacf5ec0..d1cc19ec6b 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -22,6 +22,7 @@
#++
require 'active_support'
+require 'active_support/rails'
require 'active_model/version'
module ActiveModel
@@ -33,7 +34,6 @@ module ActiveModel
autoload :Conversion
autoload :Dirty
autoload :EachValidator, 'active_model/validator'
- autoload :Errors
autoload :Lint
autoload :MassAssignmentSecurity
autoload :Model
@@ -48,11 +48,22 @@ module ActiveModel
autoload :Validations
autoload :Validator
+ eager_autoload do
+ autoload :Errors
+ end
+
module Serializers
extend ActiveSupport::Autoload
- autoload :JSON
- autoload :Xml
+ eager_autoload do
+ autoload :JSON
+ autoload :Xml
+ end
+ end
+
+ def eager_load!
+ super
+ ActiveModel::Serializer.eager_load!
end
end
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index eb06250060..ef04f1fa49 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -1,8 +1,14 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/deprecation'
module ActiveModel
# Raised when an attribute is not defined.
+ #
+ # class User < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # user = User.first
+ # user.pets.select(:id).first.user_id
+ # # => ActiveModel::MissingAttributeError: missing attribute: user_id
class MissingAttributeError < NoMethodError
end
# == Active Model Attribute Methods
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
index e669113001..e442455a53 100644
--- a/activemodel/lib/active_model/callbacks.rb
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -38,6 +38,17 @@ module ActiveModel
# # Your code here
# end
#
+ # When defining an around callback remember to yield to the block, otherwise
+ # it won't be executed:
+ #
+ # around_create :log_status
+ #
+ # def log_status
+ # puts 'going to call the block...'
+ # yield
+ # puts 'block successfully called.'
+ # end
+ #
# You can choose not to have all three callbacks by passing a hash to the
# +define_model_callbacks+ method.
#
diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb
index 89d87a8b6f..48c53f0789 100644
--- a/activemodel/lib/active_model/conversion.rb
+++ b/activemodel/lib/active_model/conversion.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
require 'active_support/inflector'
module ActiveModel
@@ -45,18 +44,30 @@ module ActiveModel
# Returns an Enumerable of all key attributes if any is set, regardless if
# the object is persisted or not. If there no key attributes, returns +nil+.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.create
+ # person.to_key # => [1]
def to_key
key = respond_to?(:id) && id
key ? [key] : nil
end
- # Returns a string representing the object's key suitable for use in URLs,
- # or +nil+ if <tt>persisted?</tt> is false.
+ # Returns a +string+ representing the object's key suitable for use in URLs,
+ # or +nil+ if <tt>persisted?</tt> is +false+.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.create
+ # person.to_param # => "1"
def to_param
persisted? ? to_key.join('-') : nil
end
- # Returns a string identifying the path associated with the object.
+ # Returns a +string+ identifying the path associated with the object.
# ActionPack uses this to find a suitable partial to represent the object.
#
# class Person
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index 9bd5f903cd..c0b268fa4d 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -1,7 +1,6 @@
require 'active_model/attribute_methods'
require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/object/duplicable'
-require 'active_support/core_ext/object/blank'
module ActiveModel
# == Active Model Dirty
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 4ed3462e7e..b3b9ba8e56 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -2,7 +2,6 @@
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/string/inflections'
-require 'active_support/core_ext/object/blank'
module ActiveModel
# == Active Model Errors
@@ -284,15 +283,19 @@ module ActiveModel
#
# If the <tt>:strict</tt> option is set to true will raise
# ActiveModel::StrictValidationFailed instead of adding the error.
+ # <tt>:strict</tt> option can also be set to any other exception.
#
# person.errors.add(:name, nil, strict: true)
# # => ActiveModel::StrictValidationFailed: name is invalid
+ # person.errors.add(:name, nil, strict: NameIsInvalid)
+ # # => NameIsInvalid: name is invalid
#
# person.errors.messages # => {}
def add(attribute, message = nil, options = {})
message = normalize_message(attribute, message, options)
- if options[:strict]
- raise ActiveModel::StrictValidationFailed, full_message(attribute, message)
+ if exception = options[:strict]
+ exception = ActiveModel::StrictValidationFailed if exception == true
+ raise exception, full_message(attribute, message)
end
self[attribute] << message
@@ -437,6 +440,19 @@ module ActiveModel
# Raised when a validation cannot be corrected by end users and are considered
# exceptional.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ #
+ # validates_presence_of :name, strict: true
+ # end
+ #
+ # person = Person.new
+ # person.name = nil
+ # person.valid?
+ # # => ActiveModel::StrictValidationFailed: Name can't be blank
class StrictValidationFailed < StandardError
end
end
diff --git a/activemodel/lib/active_model/mass_assignment_security.rb b/activemodel/lib/active_model/mass_assignment_security.rb
index 8f2c0bf00a..f9841abcb0 100644
--- a/activemodel/lib/active_model/mass_assignment_security.rb
+++ b/activemodel/lib/active_model/mass_assignment_security.rb
@@ -1,10 +1,50 @@
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/string/inflections'
require 'active_model/mass_assignment_security/permission_set'
require 'active_model/mass_assignment_security/sanitizer'
module ActiveModel
- # = Active Model Mass-Assignment Security
+ # == Active Model Mass-Assignment Security
+ #
+ # Mass assignment security provides an interface for protecting attributes
+ # from end-user assignment. For more complex permissions, mass assignment
+ # security may be handled outside the model by extending a non-ActiveRecord
+ # class, such as a controller, with this behavior.
+ #
+ # For example, a logged in user may need to assign additional attributes
+ # depending on their role:
+ #
+ # class AccountsController < ApplicationController
+ # include ActiveModel::MassAssignmentSecurity
+ #
+ # attr_accessible :first_name, :last_name
+ # attr_accessible :first_name, :last_name, :plan_id, as: :admin
+ #
+ # def update
+ # ...
+ # @account.update_attributes(account_params)
+ # ...
+ # end
+ #
+ # protected
+ #
+ # def account_params
+ # role = admin ? :admin : :default
+ # sanitize_for_mass_assignment(params[:account], role)
+ # end
+ #
+ # end
+ #
+ # === Configuration options
+ #
+ # * <tt>mass_assignment_sanitizer</tt> - Defines sanitize method. Possible
+ # values are:
+ # * <tt>:logger</tt> (default) - writes filtered attributes to logger
+ # * <tt>:strict</tt> - raise <tt>ActiveModel::MassAssignmentSecurity::Error</tt>
+ # on any protected attribute update.
+ #
+ # You can specify your own sanitizer object eg. <tt>MySanitizer.new</tt>.
+ # See <tt>ActiveModel::MassAssignmentSecurity::LoggerSanitizer</tt> for
+ # example implementation.
module MassAssignmentSecurity
extend ActiveSupport::Concern
@@ -17,55 +57,17 @@ module ActiveModel
self.mass_assignment_sanitizer = :logger
end
- # Mass assignment security provides an interface for protecting attributes
- # from end-user assignment. For more complex permissions, mass assignment security
- # may be handled outside the model by extending a non-ActiveRecord class,
- # such as a controller, with this behavior.
- #
- # For example, a logged in user may need to assign additional attributes depending
- # on their role:
- #
- # class AccountsController < ApplicationController
- # include ActiveModel::MassAssignmentSecurity
- #
- # attr_accessible :first_name, :last_name
- # attr_accessible :first_name, :last_name, :plan_id, :as => :admin
- #
- # def update
- # ...
- # @account.update_attributes(account_params)
- # ...
- # end
- #
- # protected
- #
- # def account_params
- # role = admin ? :admin : :default
- # sanitize_for_mass_assignment(params[:account], role)
- # end
- #
- # end
- #
- # = Configuration options
- #
- # * <tt>mass_assignment_sanitizer</tt> - Defines sanitize method. Possible values are:
- # * <tt>:logger</tt> (default) - writes filtered attributes to logger
- # * <tt>:strict</tt> - raise <tt>ActiveModel::MassAssignmentSecurity::Error</tt> on any protected attribute update
- #
- # You can specify your own sanitizer object eg. MySanitizer.new.
- # See <tt>ActiveModel::MassAssignmentSecurity::LoggerSanitizer</tt> for example implementation.
- #
- #
module ClassMethods
# Attributes named in this macro are protected from mass-assignment
# whenever attributes are sanitized before assignment. A role for the
- # attributes is optional, if no role is provided then :default is used.
- # A role can be defined by using the :as option with a symbol or an array of symbols as the value.
+ # attributes is optional, if no role is provided then <tt>:default</tt>
+ # is used. A role can be defined by using the <tt>:as</tt> option with a
+ # symbol or an array of symbols as the value.
#
# Mass-assignment to these attributes will simply be ignored, to assign
# to them you can use direct writer methods. This is meant to protect
# sensitive attributes from being overwritten by malicious users
- # tampering with URLs or forms. Example:
+ # tampering with URLs or forms.
#
# class Customer
# include ActiveModel::MassAssignmentSecurity
@@ -74,7 +76,7 @@ module ActiveModel
#
# attr_protected :logins_count
# # Suppose that admin can not change email for customer
- # attr_protected :logins_count, :email, :as => :admin
+ # attr_protected :logins_count, :email, as: :admin
#
# def assign_attributes(values, options = {})
# sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
@@ -83,23 +85,23 @@ module ActiveModel
# end
# end
#
- # When using the :default role:
+ # When using the <tt>:default</tt> role:
#
# customer = Customer.new
- # customer.assign_attributes({ "name" => "David", "email" => "a@b.com", :logins_count => 5 }, :as => :default)
- # customer.name # => "David"
- # customer.email # => "a@b.com"
- # customer.logins_count # => nil
+ # customer.assign_attributes({ name: 'David', email: 'a@b.com', logins_count: 5 }, as: :default)
+ # customer.name # => "David"
+ # customer.email # => "a@b.com"
+ # customer.logins_count # => nil
#
- # And using the :admin role:
+ # And using the <tt>:admin</tt> role:
#
# customer = Customer.new
- # customer.assign_attributes({ "name" => "David", "email" => "a@b.com", :logins_count => 5}, :as => :admin)
- # customer.name # => "David"
- # customer.email # => nil
- # customer.logins_count # => nil
+ # customer.assign_attributes({ name: 'David', email: 'a@b.com', logins_count: 5}, as: :admin)
+ # customer.name # => "David"
+ # customer.email # => nil
+ # customer.logins_count # => nil
#
- # customer.email = "c@d.com"
+ # customer.email = 'c@d.com'
# customer.email # => "c@d.com"
#
# To start from an all-closed default and enable attributes as needed,
@@ -125,8 +127,9 @@ module ActiveModel
# mass-assignment.
#
# Like +attr_protected+, a role for the attributes is optional,
- # if no role is provided then :default is used. A role can be defined by
- # using the :as option with a symbol or an array of symbols as the value.
+ # if no role is provided then <tt>:default</tt> is used. A role can be
+ # defined by using the <tt>:as</tt> option with a symbol or an array of
+ # symbols as the value.
#
# This is the opposite of the +attr_protected+ macro: Mass-assignment
# will only set attributes in this list, to assign to the rest of
@@ -141,8 +144,10 @@ module ActiveModel
#
# attr_accessor :name, :credit_rating
#
- # attr_accessible :name
- # attr_accessible :name, :credit_rating, :as => :admin
+ # # Both admin and default user can change name of a customer
+ # attr_accessible :name, as: [:admin, :default]
+ # # Only admin can change credit rating of a customer
+ # attr_accessible :credit_rating, as: :admin
#
# def assign_attributes(values, options = {})
# sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
@@ -151,20 +156,20 @@ module ActiveModel
# end
# end
#
- # When using the :default role:
+ # When using the <tt>:default</tt> role:
#
# customer = Customer.new
- # customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :default)
+ # customer.assign_attributes({ name: 'David', credit_rating: 'Excellent', last_login: 1.day.ago }, as: :default)
# customer.name # => "David"
# customer.credit_rating # => nil
#
- # customer.credit_rating = "Average"
+ # customer.credit_rating = 'Average'
# customer.credit_rating # => "Average"
#
- # And using the :admin role:
+ # And using the <tt>:admin</tt> role:
#
# customer = Customer.new
- # customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :admin)
+ # customer.assign_attributes({ name: 'David', credit_rating: 'Excellent', last_login: 1.day.ago }, as: :admin)
# customer.name # => "David"
# customer.credit_rating # => "Excellent"
#
@@ -184,23 +189,131 @@ module ActiveModel
self._active_authorizer = self._accessible_attributes
end
+ # Returns an instance of <tt>ActiveModel::MassAssignmentSecurity::BlackList</tt>
+ # with the attributes protected by #attr_protected method. If no +role+
+ # is provided, then <tt>:default</tt> is used.
+ #
+ # class Customer
+ # include ActiveModel::MassAssignmentSecurity
+ #
+ # attr_accessor :name, :email, :logins_count
+ #
+ # attr_protected :logins_count
+ # attr_protected :logins_count, :email, as: :admin
+ # end
+ #
+ # Customer.protected_attributes
+ # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {"logins_count"}>
+ #
+ # Customer.protected_attributes(:default)
+ # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {"logins_count"}>
+ #
+ # Customer.protected_attributes(:admin)
+ # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {"logins_count", "email"}>
def protected_attributes(role = :default)
protected_attributes_configs[role]
end
+ # Returns an instance of <tt>ActiveModel::MassAssignmentSecurity::WhiteList</tt>
+ # with the attributes protected by #attr_accessible method. If no +role+
+ # is provided, then <tt>:default</tt> is used.
+ #
+ # class Customer
+ # include ActiveModel::MassAssignmentSecurity
+ #
+ # attr_accessor :name, :credit_rating
+ #
+ # attr_accessible :name, as: [:admin, :default]
+ # attr_accessible :credit_rating, as: :admin
+ # end
+ #
+ # Customer.accessible_attributes
+ # # => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name"}>
+ #
+ # Customer.accessible_attributes(:default)
+ # # => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name"}>
+ #
+ # Customer.accessible_attributes(:admin)
+ # # => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name", "credit_rating"}>
def accessible_attributes(role = :default)
accessible_attributes_configs[role]
end
+ # Returns a hash with the protected attributes (by #attr_accessible or
+ # #attr_protected) per role.
+ #
+ # class Customer
+ # include ActiveModel::MassAssignmentSecurity
+ #
+ # attr_accessor :name, :credit_rating
+ #
+ # attr_accessible :name, as: [:admin, :default]
+ # attr_accessible :credit_rating, as: :admin
+ # end
+ #
+ # Customer.active_authorizers
+ # # => {
+ # # :admin=> #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name", "credit_rating"}>,
+ # # :default=>#<ActiveModel::MassAssignmentSecurity::WhiteList: {"name"}>
+ # #  }
def active_authorizers
self._active_authorizer ||= protected_attributes_configs
end
alias active_authorizer active_authorizers
+ # Returns an empty array by default. You can still override this to define
+ # the default attributes protected by #attr_protected method.
+ #
+ # class Customer
+ # include ActiveModel::MassAssignmentSecurity
+ #
+ # def self.attributes_protected_by_default
+ # [:name]
+ # end
+ # end
+ #
+ # Customer.protected_attributes
+ # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {:name}>
def attributes_protected_by_default
[]
end
+ # Defines sanitize method.
+ #
+ # class Customer
+ # include ActiveModel::MassAssignmentSecurity
+ #
+ # attr_accessor :name
+ #
+ # attr_protected :name
+ #
+ # def assign_attributes(values)
+ # sanitize_for_mass_assignment(values).each do |k, v|
+ # send("#{k}=", v)
+ # end
+ # end
+ # end
+ #
+ # # See ActiveModel::MassAssignmentSecurity::StrictSanitizer for more information.
+ # Customer.mass_assignment_sanitizer = :strict
+ #
+ # customer = Customer.new
+ # customer.assign_attributes(name: 'David')
+ # # => ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes for Customer: name
+ #
+ # Also, you can specify your own sanitizer object.
+ #
+ # class CustomSanitizer < ActiveModel::MassAssignmentSecurity::Sanitizer
+ # def process_removed_attributes(klass, attrs)
+ # raise StandardError
+ # end
+ # end
+ #
+ # Customer.mass_assignment_sanitizer = CustomSanitizer.new
+ #
+ # customer = Customer.new
+ # customer.assign_attributes(name: 'David')
+ # # => StandardError: StandardError
def mass_assignment_sanitizer=(value)
self._mass_assignment_sanitizer = if value.is_a?(Symbol)
const_get(:"#{value.to_s.camelize}Sanitizer").new(self)
@@ -226,11 +339,11 @@ module ActiveModel
protected
- def sanitize_for_mass_assignment(attributes, role = nil)
+ def sanitize_for_mass_assignment(attributes, role = nil) #:nodoc:
_mass_assignment_sanitizer.sanitize(self.class, attributes, mass_assignment_authorizer(role))
end
- def mass_assignment_authorizer(role)
+ def mass_assignment_authorizer(role) #:nodoc:
self.class.active_authorizer[role || :default]
end
end
diff --git a/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb b/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
index 44ce5a489d..dafb7cdff3 100644
--- a/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
+++ b/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
@@ -1,6 +1,6 @@
module ActiveModel
module MassAssignmentSecurity
- class Sanitizer
+ class Sanitizer #:nodoc:
# Returns all attributes not denied by the authorizer.
def sanitize(klass, attributes, authorizer)
rejected = []
@@ -18,7 +18,7 @@ module ActiveModel
end
end
- class LoggerSanitizer < Sanitizer
+ class LoggerSanitizer < Sanitizer #:nodoc:
def initialize(target)
@target = target
super()
@@ -50,7 +50,7 @@ module ActiveModel
end
end
- class StrictSanitizer < Sanitizer
+ class StrictSanitizer < Sanitizer #:nodoc:
def initialize(target = nil)
super()
end
@@ -65,7 +65,7 @@ module ActiveModel
end
end
- class Error < StandardError
+ class Error < StandardError #:nodoc:
def initialize(klass, attrs)
super("Can't mass-assign protected attributes for #{klass.name}: #{attrs.join(', ')}")
end
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index ea4f9341c6..c0d93e5d53 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -1,8 +1,6 @@
require 'active_support/inflector'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/introspection'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/object/blank'
module ActiveModel
class Name
@@ -220,6 +218,14 @@ module ActiveModel
# Returns an ActiveModel::Name object for module. It can be
# used to retrieve all kinds of naming-related information
# (See ActiveModel::Name for more information).
+ #
+ # class Person < ActiveModel::Model
+ # end
+ #
+ # Person.model_name # => Person
+ # Person.model_name.class # => ActiveModel::Name
+ # Person.model_name.singular # => "person"
+ # Person.model_name.plural # => "people"
def model_name
@_model_name ||= begin
namespace = self.parents.detect do |n|
@@ -256,11 +262,11 @@ module ActiveModel
# Returns string to use while generating route names. It differs for
# namespaced models regarding whether it's inside isolated engine.
#
- # For isolated engine:
- # ActiveModel::Naming.route_key(Blog::Post) #=> post
+ # # For isolated engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> post
#
- # For shared engine:
- # ActiveModel::Naming.route_key(Blog::Post) #=> blog_post
+ # # For shared engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> blog_post
def self.singular_route_key(record_or_class)
model_name_from_record_or_class(record_or_class).singular_route_key
end
@@ -268,11 +274,11 @@ module ActiveModel
# Returns string to use while generating route names. It differs for
# namespaced models regarding whether it's inside isolated engine.
#
- # For isolated engine:
- # ActiveModel::Naming.route_key(Blog::Post) #=> posts
+ # # For isolated engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> posts
#
- # For shared engine:
- # ActiveModel::Naming.route_key(Blog::Post) #=> blog_posts
+ # # For shared engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> blog_posts
#
# The route key also considers if the noun is uncountable and, in
# such cases, automatically appends _index.
@@ -283,23 +289,24 @@ module ActiveModel
# Returns string to use for params names. It differs for
# namespaced models regarding whether it's inside isolated engine.
#
- # For isolated engine:
- # ActiveModel::Naming.param_key(Blog::Post) #=> post
+ # # For isolated engine:
+ # ActiveModel::Naming.param_key(Blog::Post) #=> post
#
- # For shared engine:
- # ActiveModel::Naming.param_key(Blog::Post) #=> blog_post
+ # # For shared engine:
+ # ActiveModel::Naming.param_key(Blog::Post) #=> blog_post
def self.param_key(record_or_class)
model_name_from_record_or_class(record_or_class).param_key
end
- private
- def self.model_name_from_record_or_class(record_or_class)
- (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
- end
-
- def self.convert_to_model(object)
- object.respond_to?(:to_model) ? object.to_model : object
+ def self.model_name_from_record_or_class(record_or_class) #:nodoc:
+ if record_or_class.respond_to?(:model_name)
+ record_or_class.model_name
+ elsif record_or_class.respond_to?(:to_model)
+ record_or_class.to_model.class.model_name
+ else
+ record_or_class.class.model_name
end
+ end
+ private_class_method :model_name_from_record_or_class
end
-
end
diff --git a/activemodel/lib/active_model/observer_array.rb b/activemodel/lib/active_model/observer_array.rb
index 8de6918d18..77bc0f71e3 100644
--- a/activemodel/lib/active_model/observer_array.rb
+++ b/activemodel/lib/active_model/observer_array.rb
@@ -5,20 +5,21 @@ module ActiveModel
# a particular model class.
class ObserverArray < Array
attr_reader :model_class
- def initialize(model_class, *args)
+ def initialize(model_class, *args) #:nodoc:
@model_class = model_class
super(*args)
end
- # Returns true if the given observer is disabled for the model class.
- def disabled_for?(observer)
+ # Returns +true+ if the given observer is disabled for the model class,
+ # +false+ otherwise.
+ def disabled_for?(observer) #:nodoc:
disabled_observers.include?(observer.class)
end
# Disables one or more observers. This supports multiple forms:
#
# ORM.observers.disable :all
- # # => disables all observers for all models subclassed from
+ # # => disables all observers for all models subclassed from
# # an ORM base class that includes ActiveModel::Observing
# # e.g. ActiveRecord::Base
#
@@ -43,7 +44,7 @@ module ActiveModel
# Enables one or more observers. This supports multiple forms:
#
# ORM.observers.enable :all
- # # => enables all observers for all models subclassed from
+ # # => enables all observers for all models subclassed from
# # an ORM base class that includes ActiveModel::Observing
# # e.g. ActiveRecord::Base
#
@@ -71,11 +72,11 @@ module ActiveModel
protected
- def disabled_observers
+ def disabled_observers #:nodoc:
@disabled_observers ||= Set.new
end
- def observer_class_for(observer)
+ def observer_class_for(observer) #:nodoc:
return observer if observer.is_a?(Class)
if observer.respond_to?(:to_sym) # string/symbol
@@ -86,25 +87,25 @@ module ActiveModel
end
end
- def start_transaction
+ def start_transaction #:nodoc:
disabled_observer_stack.push(disabled_observers.dup)
each_subclass_array do |array|
array.start_transaction
end
end
- def disabled_observer_stack
+ def disabled_observer_stack #:nodoc:
@disabled_observer_stack ||= []
end
- def end_transaction
+ def end_transaction #:nodoc:
@disabled_observers = disabled_observer_stack.pop
each_subclass_array do |array|
array.end_transaction
end
end
- def transaction
+ def transaction #:nodoc:
start_transaction
begin
@@ -114,13 +115,13 @@ module ActiveModel
end
end
- def each_subclass_array
+ def each_subclass_array #:nodoc:
model_class.descendants.each do |subclass|
yield subclass.observers
end
end
- def set_enablement(enabled, observers)
+ def set_enablement(enabled, observers) #:nodoc:
if block_given?
transaction do
set_enablement(enabled, observers)
diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb
index ca206ee9aa..9db7639ea3 100644
--- a/activemodel/lib/active_model/observing.rb
+++ b/activemodel/lib/active_model/observing.rb
@@ -4,11 +4,11 @@ require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/enumerable'
-require 'active_support/deprecation'
require 'active_support/core_ext/object/try'
require 'active_support/descendants_tracker'
module ActiveModel
+ # == Active Model Observers Activation
module Observing
extend ActiveSupport::Concern
@@ -17,9 +17,7 @@ module ActiveModel
end
module ClassMethods
- # == Active Model Observers Activation
- #
- # Activates the observers assigned. Examples:
+ # Activates the observers assigned.
#
# class ORM
# include ActiveModel::Observing
@@ -35,34 +33,95 @@ module ActiveModel
# ORM.observers = Cacher, GarbageCollector
#
# Note: Setting this does not instantiate the observers yet.
- # +instantiate_observers+ is called during startup, and before
+ # <tt>instantiate_observers</tt> is called during startup, and before
# each development request.
def observers=(*values)
observers.replace(values.flatten)
end
- # Gets an array of observers observing this model.
- # The array also provides +enable+ and +disable+ methods
- # that allow you to selectively enable and disable observers.
- # (see <tt>ActiveModel::ObserverArray.enable</tt> and
- # <tt>ActiveModel::ObserverArray.disable</tt> for more on this)
+ # Gets an array of observers observing this model. The array also provides
+ # +enable+ and +disable+ methods that allow you to selectively enable and
+ # disable observers (see ActiveModel::ObserverArray.enable and
+ # ActiveModel::ObserverArray.disable for more on this).
+ #
+ # class ORM
+ # include ActiveModel::Observing
+ # end
+ #
+ # ORM.observers = :cacher, :garbage_collector
+ # ORM.observers # => [:cacher, :garbage_collector]
+ # ORM.observers.class # => ActiveModel::ObserverArray
def observers
@observers ||= ObserverArray.new(self)
end
- # Gets the current observer instances.
+ # Returns the current observer instances.
+ #
+ # class Foo
+ # include ActiveModel::Observing
+ #
+ # attr_accessor :status
+ # end
+ #
+ # class FooObserver < ActiveModel::Observer
+ # def on_spec(record, *args)
+ # record.status = true
+ # end
+ # end
+ #
+ # Foo.observers = FooObserver
+ # Foo.instantiate_observers
+ #
+ # Foo.observer_instances # => [#<FooObserver:0x007fc212c40820>]
def observer_instances
@observer_instances ||= []
end
# Instantiate the global observers.
+ #
+ # class Foo
+ # include ActiveModel::Observing
+ #
+ # attr_accessor :status
+ # end
+ #
+ # class FooObserver < ActiveModel::Observer
+ # def on_spec(record, *args)
+ # record.status = true
+ # end
+ # end
+ #
+ # Foo.observers = FooObserver
+ #
+ # foo = Foo.new
+ # foo.status = false
+ # foo.notify_observers(:on_spec)
+ # foo.status # => false
+ #
+ # Foo.instantiate_observers # => [FooObserver]
+ #
+ # foo = Foo.new
+ # foo.status = false
+ # foo.notify_observers(:on_spec)
+ # foo.status # => true
def instantiate_observers
observers.each { |o| instantiate_observer(o) }
end
- # Add a new observer to the pool.
- # The new observer needs to respond to 'update', otherwise it
- # raises an +ArgumentError+ exception.
+ # Add a new observer to the pool. The new observer needs to respond to
+ # <tt>update</tt>, otherwise it raises an +ArgumentError+ exception.
+ #
+ # class Foo
+ # include ActiveModel::Observing
+ # end
+ #
+ # class FooObserver < ActiveModel::Observer
+ # end
+ #
+ # Foo.add_observer(FooObserver.instance)
+ #
+ # Foo.observers_instance
+ # # => [#<FooObserver:0x007fccf55d9390>]
def add_observer(observer)
unless observer.respond_to? :update
raise ArgumentError, "observer needs to respond to 'update'"
@@ -70,16 +129,47 @@ module ActiveModel
observer_instances << observer
end
- # Notify list of observers of a change.
+ # Fires notifications to model's observers.
+ #
+ # def save
+ # notify_observers(:before_save)
+ # ...
+ # notify_observers(:after_save)
+ # end
+ #
+ # Custom notifications can be sent in a similar fashion:
+ #
+ # notify_observers(:custom_notification, :foo)
+ #
+ # This will call <tt>custom_notification</tt>, passing as arguments
+ # the current object and <tt>:foo</tt>.
def notify_observers(*args)
observer_instances.each { |observer| observer.update(*args) }
end
- # Total number of observers.
+ # Returns the total number of instantiated observers.
+ #
+ # class Foo
+ # include ActiveModel::Observing
+ #
+ # attr_accessor :status
+ # end
+ #
+ # class FooObserver < ActiveModel::Observer
+ # def on_spec(record, *args)
+ # record.status = true
+ # end
+ # end
+ #
+ # Foo.observers = FooObserver
+ # Foo.observers_count # => 0
+ # Foo.instantiate_observers
+ # Foo.observers_count # => 1
def observers_count
observer_instances.size
end
+ # <tt>count_observers</tt> is deprecated. Use #observers_count.
def count_observers
msg = "count_observers is deprecated in favor of observers_count"
ActiveSupport::Deprecation.warn(msg)
@@ -104,27 +194,36 @@ module ActiveModel
end
# Notify observers when the observed class is subclassed.
- def inherited(subclass)
+ def inherited(subclass) #:nodoc:
super
notify_observers :observed_class_inherited, subclass
end
end
- # Fires notifications to model's observers
+ # Notify a change to the list of observers.
+ #
+ # class Foo
+ # include ActiveModel::Observing
#
- # def save
- # notify_observers(:before_save)
- # ...
- # notify_observers(:after_save)
+ # attr_accessor :status
# end
#
- # Custom notifications can be sent in a similar fashion:
+ # class FooObserver < ActiveModel::Observer
+ # def on_spec(record, *args)
+ # record.status = true
+ # end
+ # end
#
- # notify_observers(:custom_notification, :foo)
+ # Foo.observers = FooObserver
+ # Foo.instantiate_observers # => [FooObserver]
#
- # This will call +custom_notification+, passing as arguments
- # the current object and :foo.
+ # foo = Foo.new
+ # foo.status = false
+ # foo.notify_observers(:on_spec)
+ # foo.status # => true
#
+ # See ActiveModel::Observing::ClassMethods.notify_observers for more
+ # information.
def notify_observers(method, *extra_args)
self.class.notify_observers(method, self, *extra_args)
end
@@ -136,15 +235,15 @@ module ActiveModel
# behavior outside the original class. This is a great way to reduce the
# clutter that normally comes when the model class is burdened with
# functionality that doesn't pertain to the core responsibility of the
- # class. Example:
+ # class.
#
# class CommentObserver < ActiveModel::Observer
# def after_save(comment)
- # Notifications.comment("admin@do.com", "New comment was posted", comment).deliver
+ # Notifications.comment('admin@do.com', 'New comment was posted', comment).deliver
# end
# end
#
- # This Observer sends an email when a Comment#save is finished.
+ # This Observer sends an email when a <tt>Comment#save</tt> is finished.
#
# class ContactObserver < ActiveModel::Observer
# def after_create(contact)
@@ -161,44 +260,50 @@ module ActiveModel
# == Observing a class that can't be inferred
#
# Observers will by default be mapped to the class with which they share a
- # name. So CommentObserver will be tied to observing Comment, ProductManagerObserver
- # to ProductManager, and so on. If you want to name your observer differently than
- # the class you're interested in observing, you can use the <tt>Observer.observe</tt>
- # class method which takes either the concrete class (Product) or a symbol for that
- # class (:product):
+ # name. So <tt>CommentObserver</tt> will be tied to observing <tt>Comment</tt>,
+ # <tt>ProductManagerObserver</tt> to <tt>ProductManager</tt>, and so on. If
+ # you want to name your observer differently than the class you're interested
+ # in observing, you can use the <tt>Observer.observe</tt> class method which
+ # takes either the concrete class (<tt>Product</tt>) or a symbol for that
+ # class (<tt>:product</tt>):
#
# class AuditObserver < ActiveModel::Observer
# observe :account
#
# def after_update(account)
- # AuditTrail.new(account, "UPDATED")
+ # AuditTrail.new(account, 'UPDATED')
# end
# end
#
- # If the audit observer needs to watch more than one kind of object, this can be
- # specified with multiple arguments:
+ # If the audit observer needs to watch more than one kind of object, this can
+ # be specified with multiple arguments:
#
# class AuditObserver < ActiveModel::Observer
# observe :account, :balance
#
# def after_update(record)
- # AuditTrail.new(record, "UPDATED")
+ # AuditTrail.new(record, 'UPDATED')
# end
# end
#
- # The AuditObserver will now act on both updates to Account and Balance by treating
- # them both as records.
+ # The <tt>AuditObserver</tt> will now act on both updates to <tt>Account</tt>
+ # and <tt>Balance</tt> by treating them both as records.
#
- # If you're using an Observer in a Rails application with Active Record, be sure to
- # read about the necessary configuration in the documentation for
+ # If you're using an Observer in a Rails application with Active Record, be
+ # sure to read about the necessary configuration in the documentation for
# ActiveRecord::Observer.
- #
class Observer
include Singleton
extend ActiveSupport::DescendantsTracker
class << self
# Attaches the observer to the supplied model classes.
+ #
+ # class AuditObserver < ActiveModel::Observer
+ # observe :account, :balance
+ # end
+ #
+ # AuditObserver.observed_classes # => [Account, Balance]
def observe(*models)
models.flatten!
models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
@@ -207,6 +312,8 @@ module ActiveModel
# Returns an array of Classes to observe.
#
+ # AccountObserver.observed_classes # => [Account]
+ #
# You can override this instead of using the +observe+ helper.
#
# class AuditObserver < ActiveModel::Observer
@@ -218,8 +325,11 @@ module ActiveModel
Array(observed_class)
end
- # The class observed by default is inferred from the observer's class name:
- # assert_equal Person, PersonObserver.observed_class
+ # Returns the class observed by default. It's inferred from the observer's
+ # class name.
+ #
+ # PersonObserver.observed_class # => Person
+ # AccountObserver.observed_class # => Account
def observed_class
name[/(.*)Observer/, 1].try :constantize
end
@@ -227,7 +337,7 @@ module ActiveModel
# Start observing the declared classes and their subclasses.
# Called automatically by the instance method.
- def initialize
+ def initialize #:nodoc:
observed_classes.each { |klass| add_observer!(klass) }
end
@@ -238,7 +348,7 @@ module ActiveModel
# Send observed_method(object) if the method exists and
# the observer is enabled for the given object's class.
def update(observed_method, object, *extra_args, &block) #:nodoc:
- return if !respond_to?(observed_method) || disabled_for?(object)
+ return if !respond_to?(observed_method) || disabled_for?(object)
send(observed_method, object, *extra_args, &block)
end
@@ -255,7 +365,7 @@ module ActiveModel
end
# Returns true if notifications are disabled for this object.
- def disabled_for?(object)
+ def disabled_for?(object) #:nodoc:
klass = object.class
return false unless klass.respond_to?(:observers)
klass.observers.disabled_for?(self)
diff --git a/activemodel/lib/active_model/railtie.rb b/activemodel/lib/active_model/railtie.rb
index 63ffe5db63..f239758b35 100644
--- a/activemodel/lib/active_model/railtie.rb
+++ b/activemodel/lib/active_model/railtie.rb
@@ -1,2 +1,8 @@
require "active_model"
-require "rails" \ No newline at end of file
+require "rails"
+
+module ActiveModel
+ class Railtie < Rails::Railtie
+ config.eager_load_namespaces << ActiveModel
+ end
+end \ No newline at end of file
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
index 3eab745c89..d011402081 100644
--- a/activemodel/lib/active_model/secure_password.rb
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -6,12 +6,12 @@ module ActiveModel
# Adds methods to set and authenticate against a BCrypt password.
# This mechanism requires you to have a password_digest attribute.
#
- # Validations for presence of password on create, confirmation of password (using
- # a "password_confirmation" attribute) are automatically added.
- # If you wish to turn off validations, pass 'validations: false' as an argument.
- # You can add more validations by hand if need be.
+ # Validations for presence of password on create, confirmation of password
+ # (using a +password_confirmation+ attribute) are automatically added. If
+ # you wish to turn off validations, pass <tt>validations: false</tt> as an
+ # argument. You can add more validations by hand if need be.
#
- # You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use has_secure_password:
+ # You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use #has_secure_password:
#
# gem 'bcrypt-ruby', '~> 3.0.0'
#
@@ -22,35 +22,36 @@ module ActiveModel
# has_secure_password
# end
#
- # user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
+ # user = User.new(name: 'david', password: '', password_confirmation: 'nomatch')
# user.save # => false, password required
- # user.password = "mUc3m00RsqyRe"
+ # user.password = 'mUc3m00RsqyRe'
# user.save # => false, confirmation doesn't match
- # user.password_confirmation = "mUc3m00RsqyRe"
+ # user.password_confirmation = 'mUc3m00RsqyRe'
# user.save # => true
- # user.authenticate("notright") # => false
- # user.authenticate("mUc3m00RsqyRe") # => user
- # User.find_by_name("david").try(:authenticate, "notright") # => false
- # User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
+ # user.authenticate('notright') # => false
+ # user.authenticate('mUc3m00RsqyRe') # => user
+ # User.find_by_name('david').try(:authenticate, 'notright') # => false
+ # User.find_by_name('david').try(:authenticate, 'mUc3m00RsqyRe') # => user
def has_secure_password(options = {})
# Load bcrypt-ruby only when has_secure_password is used.
- # This is to avoid ActiveModel (and by extension the entire framework) being dependent on a binary library.
+ # This is to avoid ActiveModel (and by extension the entire framework)
+ # being dependent on a binary library.
gem 'bcrypt-ruby', '~> 3.0.0'
require 'bcrypt'
attr_reader :password
-
+
if options.fetch(:validations, true)
validates_confirmation_of :password
validates_presence_of :password, :on => :create
+
+ before_create { raise "Password digest missing on new record" if password_digest.blank? }
end
-
- before_create { raise "Password digest missing on new record" if password_digest.blank? }
include InstanceMethodsOnActivation
if respond_to?(:attributes_protected_by_default)
- def self.attributes_protected_by_default
+ def self.attributes_protected_by_default #:nodoc:
super + ['password_digest']
end
end
@@ -58,13 +59,32 @@ module ActiveModel
end
module InstanceMethodsOnActivation
- # Returns self if the password is correct, otherwise false.
+ # Returns +self+ if the password is correct, otherwise +false+.
+ #
+ # class User < ActiveRecord::Base
+ # has_secure_password validations: false
+ # end
+ #
+ # user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
+ # user.save
+ # user.authenticate('notright') # => false
+ #  user.authenticate('mUc3m00RsqyRe') # => user
def authenticate(unencrypted_password)
BCrypt::Password.new(password_digest) == unencrypted_password && self
end
- # Encrypts the password into the password_digest attribute, only if the
+ # Encrypts the password into the +password_digest+ attribute, only if the
# new password is not blank.
+ #
+ # class User < ActiveRecord::Base
+ # has_secure_password validations: false
+ # end
+ #
+ # user = User.new
+ # user.password = nil
+ # user.password_digest # => nil
+ # user.password = 'mUc3m00RsqyRe'
+ # user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
def password=(unencrypted_password)
unless unencrypted_password.blank?
@password = unencrypted_password
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index 6d8fd21814..8a63014ffb 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -25,17 +25,16 @@ module ActiveModel
# person.name = "Bob"
# person.serializable_hash # => {"name"=>"Bob"}
#
- # You need to declare an attributes hash which contains the attributes
- # you want to serialize. Attributes must be strings, not symbols.
- # When called, serializable hash will use
- # instance methods that match the name of the attributes hash's keys.
- # In order to override this behavior, take a look at the private
- # method +read_attribute_for_serialization+.
+ # You need to declare an attributes hash which contains the attributes you
+ # want to serialize. Attributes must be strings, not symbols. When called,
+ # serializable hash will use instance methods that match the name of the
+ # attributes hash's keys. In order to override this behavior, take a look at
+ # the private method +read_attribute_for_serialization+.
#
# Most of the time though, you will want to include the JSON or XML
# serializations. Both of these modules automatically include the
- # <tt>ActiveModel::Serialization</tt> module, so there is no need to explicitly
- # include it.
+ # <tt>ActiveModel::Serialization</tt> module, so there is no need to
+ # explicitly include it.
#
# A minimal implementation including XML and JSON would be:
#
@@ -64,13 +63,37 @@ module ActiveModel
# person.to_json # => "{\"name\":\"Bob\"}"
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
#
- # Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and <tt>:include</tt>.
- # The following are all valid examples:
+ # Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
+ # <tt>:include</tt>. The following are all valid examples:
#
- # person.serializable_hash(:only => 'name')
- # person.serializable_hash(:include => :address)
- # person.serializable_hash(:include => { :address => { :only => 'city' }})
+ # person.serializable_hash(only: 'name')
+ # person.serializable_hash(include: :address)
+ # person.serializable_hash(include: { address: { only: 'city' }})
module Serialization
+ # Returns a serialized hash of your object.
+ #
+ # class Person
+ # include ActiveModel::Serialization
+ #
+ # attr_accessor :name, :age
+ #
+ # def attributes
+ # {'name' => nil, 'age' => nil}
+ # end
+ #
+ # def capitalized_name
+ # name.capitalize
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'bob'
+ # person.age = 22
+ # person.serializable_hash # => {"name"=>"bob", "age"=>22}
+ # person.serializable_hash(only: :name) # => {"name"=>"bob"}
+ # person.serializable_hash(except: :name) # => {"age"=>22}
+ # person.serializable_hash(methods: :capitalized_name)
+ # # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
def serializable_hash(options = nil)
options ||= {}
@@ -115,7 +138,6 @@ module ActiveModel
# @data[key]
# end
# end
- #
alias :read_attribute_for_serialization :send
# Add associations specified via the <tt>:include</tt> option.
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index b4baf3a946..a4252b995d 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -1,5 +1,4 @@
require 'active_support/json'
-require 'active_support/core_ext/class/attribute'
module ActiveModel
# == Active Model JSON Serializer
@@ -19,8 +18,8 @@ module ActiveModel
# passed through +options+.
#
# The option <tt>include_root_in_json</tt> controls the top-level behavior
- # of +as_json+. If true +as_json+ will emit a single root node named after
- # the object's type. The default value for <tt>include_root_in_json</tt>
+ # of +as_json+. If +true+, +as_json+ will emit a single root node named
+ # after the object's type. The default value for <tt>include_root_in_json</tt>
# option is +false+.
#
# user = User.find(1)
@@ -87,8 +86,12 @@ module ActiveModel
# # { "comments" => [ { "body" => "Don't think too hard" } ],
# # "title" => "So I was thinking" } ] }
def as_json(options = nil)
- root = include_root_in_json
- root = options[:root] if options.try(:key?, :root)
+ root = if options && options.key?(:root)
+ options[:root]
+ else
+ include_root_in_json
+ end
+
if root
root = self.class.model_name.element if root == true
{ root => serializable_hash(options) }
@@ -97,6 +100,40 @@ module ActiveModel
end
end
+ # Sets the model +attributes+ from a JSON string. Returns +self+.
+ #
+ # class Person
+ # include ActiveModel::Serializers::JSON
+ #
+ # attr_accessor :name, :age, :awesome
+ #
+ # def attributes=(hash)
+ # hash.each do |key, value|
+ # instance_variable_set("@#{key}", value)
+ # end
+ # end
+ #
+ # def attributes
+ # instance_values
+ # end
+ # end
+ #
+ # json = { name: 'bob', age: 22, awesome:true }.to_json
+ # person = Person.new
+ # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
+ #
+ # The default value for +include_root+ is +false+. You can change it to
+ # +true+ if the given JSON string includes a single root node.
+ #
+ # json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
+ # person = Person.new
+ # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
def from_json(json, include_root=include_root_in_json)
hash = ActiveSupport::JSON.decode(json)
hash = hash.values.first if include_root
diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb
index 2b3e9ce134..cf742d0569 100644..100755
--- a/activemodel/lib/active_model/serializers/xml.rb
+++ b/activemodel/lib/active_model/serializers/xml.rb
@@ -110,11 +110,15 @@ module ActiveModel
end
end
- # TODO This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
+ # TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
def add_associations(association, records, opts)
merged_options = opts.merge(options.slice(:builder, :indent))
merged_options[:skip_instruct] = true
+ [:skip_types, :dasherize, :camelize].each do |key|
+ merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
+ end
+
if records.respond_to?(:to_ary)
records = records.to_ary
@@ -161,8 +165,8 @@ module ActiveModel
# Returns XML representing the model. Configuration can be
# passed through +options+.
#
- # Without any +options+, the returned XML string will include all the model's
- # attributes. For example:
+ # Without any +options+, the returned XML string will include all the
+ # model's attributes.
#
# user = User.find(1)
# user.to_xml
@@ -175,18 +179,42 @@ module ActiveModel
# <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
# </user>
#
- # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
- # included, and work similar to the +attributes+ method.
+ # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
+ # attributes included, and work similar to the +attributes+ method.
#
# To include the result of some method calls on the model use <tt>:methods</tt>.
#
# To include associations use <tt>:include</tt>.
#
- # For further documentation see activerecord/lib/active_record/serializers/xml_serializer.xml.
+ # For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
def to_xml(options = {}, &block)
Serializer.new(self, options).serialize(&block)
end
+ # Sets the model +attributes+ from a JSON string. Returns +self+.
+ #
+ # class Person
+ # include ActiveModel::Serializers::Xml
+ #
+ # attr_accessor :name, :age, :awesome
+ #
+ # def attributes=(hash)
+ # hash.each do |key, value|
+ # instance_variable_set("@#{key}", value)
+ # end
+ # end
+ #
+ # def attributes
+ # instance_values
+ # end
+ # end
+ #
+ # xml = { name: 'bob', age: 22, awesome:true }.to_xml
+ # person = Person.new
+ # person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
def from_xml(xml)
self.attributes = Hash.from_xml(xml).values.first
self
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 55ea6be796..4762f39044 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/except'
require 'active_model/errors'
@@ -33,11 +32,11 @@ module ActiveModel
# person.first_name = 'zoolander'
# person.valid? # => false
# person.invalid? # => true
- # person.errors # => #<Hash {:first_name=>["starts with z."]}>
+ # person.errors.messages # => {:first_name=>["starts with z."]}
#
- # Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+ method
- # to your instances initialized with a new <tt>ActiveModel::Errors</tt> object, so
- # there is no need for you to do this manually.
+ # Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+
+ # method to your instances initialized with a new <tt>ActiveModel::Errors</tt>
+ # object, so there is no need for you to do this manually.
module Validations
extend ActiveSupport::Concern
@@ -63,24 +62,25 @@ module ActiveModel
#
# attr_accessor :first_name, :last_name
#
- # validates_each :first_name, :last_name, :allow_blank => true do |record, attr, value|
+ # validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
# end
# end
#
# Options:
# * <tt>:on</tt> - Specifies the context where this validation is active
- # (e.g. <tt>:on => :create</tt> or <tt>:on => :custom_validation_context</tt>)
+ # (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt>)
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
- # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
- # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method,
- # proc or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or
- # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
def validates_each(*attr_names, &block)
validates_with BlockValidator, _merge_attributes(attr_names), &block
end
@@ -97,7 +97,7 @@ module ActiveModel
# validate :must_be_friends
#
# def must_be_friends
- # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
# end
# end
#
@@ -111,7 +111,7 @@ module ActiveModel
# end
#
# def must_be_friends
- # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
# end
# end
#
@@ -121,23 +121,24 @@ module ActiveModel
# include ActiveModel::Validations
#
# validate do
- # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
# end
# end
#
# Options:
# * <tt>:on</tt> - Specifies the context where this validation is active
- # (e.g. <tt>:on => :create</tt> or <tt>:on => :custom_validation_context</tt>)
+ # (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt>)
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
- # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
- # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method,
- # proc or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or
- # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
def validate(*args, &block)
options = args.extract_options!
if options.key?(:on)
@@ -171,39 +172,101 @@ module ActiveModel
end
# List all validators that are being used to validate a specific attribute.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name , :age
+ #
+ # validates_presence_of :name
+ # validates_inclusion_of :age, in: 0..99
+ # end
+ #
+ # Person.validators_on(:name)
+ # # => [
+ # # #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
+ # # #<ActiveModel::Validations::InclusionValidator:0x007fe603bb8780 @attributes=[:age], @options={:in=>0..99}>
+ # # ]
def validators_on(*attributes)
attributes.map do |attribute|
_validators[attribute.to_sym]
end.flatten
end
- # Check if method is an attribute method or not.
+ # Returns +true+ if +attribute+ is an attribute method, +false+ otherwise.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # end
+ #
+ # User.attribute_method?(:name) # => true
+ # User.attribute_method?(:age) # => false
def attribute_method?(attribute)
method_defined?(attribute)
end
# Copy validators on inheritance.
- def inherited(base)
+ def inherited(base) #:nodoc:
dup = _validators.dup
base._validators = dup.each { |k, v| dup[k] = v.dup }
super
end
end
- # Clean the +Errors+ object if instance is duped
- def initialize_dup(other) # :nodoc:
+ # Clean the +Errors+ object if instance is duped.
+ def initialize_dup(other) #:nodoc:
@errors = nil
super
end
- # Returns the +Errors+ object that holds all information about attribute error messages.
+ # Returns the +Errors+ object that holds all information about attribute
+ # error messages.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name
+ # end
+ #
+ # person = Person.new
+ # person.valid? # => false
+ # person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={:name=>["can't be blank"]}>
def errors
@errors ||= Errors.new(self)
end
- # Runs all the specified validations and returns true if no errors were added
- # otherwise false. Context can optionally be supplied to define which callbacks
- # to test against (the context is defined on the validations using :on).
+ # Runs all the specified validations and returns +true+ if no errors were
+ # added otherwise +false+.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.valid? # => false
+ # person.name = 'david'
+ # person.valid? # => true
+ #
+ # Context can optionally be supplied to define which callbacks to test
+ # against (the context is defined on the validations using <tt>:on</tt>).
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name, on: :new
+ # end
+ #
+ # person = Person.new
+ # person.valid? # => true
+ # person.valid?(:new) # => false
def valid?(context = nil)
current_context, self.validation_context = validation_context, context
errors.clear
@@ -212,8 +275,35 @@ module ActiveModel
self.validation_context = current_context
end
- # Performs the opposite of <tt>valid?</tt>. Returns true if errors were added,
- # false otherwise.
+ # Performs the opposite of <tt>valid?</tt>. Returns +true+ if errors were
+ # added, +false+ otherwise.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.invalid? # => true
+ # person.name = 'david'
+ # person.invalid? # => false
+ #
+ # Context can optionally be supplied to define which callbacks to test
+ # against (the context is defined on the validations using <tt>:on</tt>).
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name, on: :new
+ # end
+ #
+ # person = Person.new
+ # person.invalid? # => false
+ # person.invalid?(:new) # => true
def invalid?(context = nil)
!valid?(context)
end
@@ -238,7 +328,7 @@ module ActiveModel
protected
- def run_validations!
+ def run_validations! #:nodoc:
run_callbacks :validate
errors.empty?
end
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index 43651094cf..8d5ebf527f 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -27,7 +27,7 @@ module ActiveModel
#
# class Person < ActiveRecord::Base
# validates_acceptance_of :terms_of_service
- # validates_acceptance_of :eula, :message => "must be abided"
+ # validates_acceptance_of :eula, message: "must be abided"
# end
#
# If the database column does not exist, the +terms_of_service+ attribute
@@ -37,29 +37,17 @@ module ActiveModel
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "must be
# accepted").
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default
- # is true).
+ # is +true+).
# * <tt>:accept</tt> - Specifies value that is considered accepted.
# The default value is a string "1", which makes it easy to relate to
# an HTML checkbox. This should be set to +true+ if you are validating
# a database column, since the attribute is typecast from "1" to +true+
# before validation.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
- # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
- # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false
- # value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to
- # determine if the validation should not occur (for example,
- # <tt>:unless => :skip_validation</tt>, or
- # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
- # The method, proc or string should return or evaluate to a true or
- # false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_acceptance_of(*attr_names)
validates_with AcceptanceValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
index dbafd0bd1a..bf3fe7ff04 100644
--- a/activemodel/lib/active_model/validations/callbacks.rb
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -2,24 +2,24 @@ require 'active_support/callbacks'
module ActiveModel
module Validations
+ # == Active Model Validation callbacks
+ #
+ # Provides an interface for any class to have +before_validation+ and
+ # +after_validation+ callbacks.
+ #
+ # First, include ActiveModel::Validations::Callbacks from the class you are
+ # creating:
+ #
+ # class MyModel
+ # include ActiveModel::Validations::Callbacks
+ #
+ # before_validation :do_stuff_before_validation
+ # after_validation :do_stuff_after_validation
+ # end
+ #
+ # Like other <tt>before_*</tt> callbacks if +before_validation+ returns
+ # +false+ then <tt>valid?</tt> will not be called.
module Callbacks
- # == Active Model Validation callbacks
- #
- # Provides an interface for any class to have <tt>before_validation</tt> and
- # <tt>after_validation</tt> callbacks.
- #
- # First, include ActiveModel::Validations::Callbacks from the class you are
- # creating:
- #
- # class MyModel
- # include ActiveModel::Validations::Callbacks
- #
- # before_validation :do_stuff_before_validation
- # after_validation :do_stuff_after_validation
- # end
- #
- # Like other before_* callbacks if <tt>before_validation</tt> returns false
- # then <tt>valid?</tt> will not be called.
extend ActiveSupport::Concern
included do
@@ -28,6 +28,30 @@ module ActiveModel
end
module ClassMethods
+ # Defines a callback that will get called right before validation
+ # happens.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # include ActiveModel::Validations::Callbacks
+ #
+ # attr_accessor :name
+ #
+ # validates_length_of :name, maximum: 6
+ #
+ # before_validation :remove_whitespaces
+ #
+ # private
+ #
+ # def remove_whitespaces
+ # name.strip!
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = ' bob '
+ # person.valid? # => true
+ # person.name # => "bob"
def before_validation(*args, &block)
options = args.last
if options.is_a?(Hash) && options[:on]
@@ -37,6 +61,33 @@ module ActiveModel
set_callback(:validation, :before, *args, &block)
end
+ # Defines a callback that will get called right after validation
+ # happens.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # include ActiveModel::Validations::Callbacks
+ #
+ # attr_accessor :name, :status
+ #
+ # validates_presence_of :name
+ #
+ # after_validation :set_status
+ #
+ # private
+ #
+ # def set_status
+ # self.status = errors.empty?
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.valid? # => false
+ # person.status # => false
+ #  person.name = 'bob'
+ # person.valid? # => true
+ # person.status # => true
def after_validation(*args, &block)
options = args.extract_options!
options[:prepend] = true
@@ -49,7 +100,7 @@ module ActiveModel
protected
# Overwrite run validations to include callbacks.
- def run_validations!
+ def run_validations! #:nodoc:
run_callbacks(:validation) { super }
end
end
diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb
index b632a2bd6b..cf1415b6c2 100644
--- a/activemodel/lib/active_model/validations/clusivity.rb
+++ b/activemodel/lib/active_model/validations/clusivity.rb
@@ -2,12 +2,12 @@ require 'active_support/core_ext/range.rb'
module ActiveModel
module Validations
- module Clusivity
- ERROR_MESSAGE = "An object with the method #include? or a proc or lambda is required, " <<
- "and must be supplied as the :in option of the configuration hash"
+ module Clusivity #:nodoc:
+ ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " <<
+ "and must be supplied as the :in (or :within) option of the configuration hash"
def check_validity!
- unless [:include?, :call].any?{ |method| options[:in].respond_to?(method) }
+ unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym)
raise ArgumentError, ERROR_MESSAGE
end
end
@@ -15,11 +15,21 @@ module ActiveModel
private
def include?(record, value)
- delimiter = options[:in]
- exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
+ exclusions = if delimiter.respond_to?(:call)
+ delimiter.call(record)
+ elsif delimiter.respond_to?(:to_sym)
+ record.send(delimiter)
+ else
+ delimiter
+ end
+
exclusions.send(inclusion_method(exclusions), value)
end
+ def delimiter
+ @delimiter ||= options[:in] || options[:within]
+ end
+
# In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible values in the
# range for equality, so it may be slow for large ranges. The new <tt>Range#cover?</tt>
# uses the previous logic of comparing a value with the range endpoints.
diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb
index b6cf82fb19..baa034eca6 100644
--- a/activemodel/lib/active_model/validations/confirmation.rb
+++ b/activemodel/lib/active_model/validations/confirmation.rb
@@ -25,7 +25,7 @@ module ActiveModel
# class Person < ActiveRecord::Base
# validates_confirmation_of :user_name, :password
# validates_confirmation_of :email_address,
- # :message => "should match confirmation"
+ # message: 'should match confirmation'
# end
#
# View:
@@ -38,29 +38,18 @@ module ActiveModel
# attribute.
#
# NOTE: This check is performed only if +password_confirmation+ is not
- # +nil+. To require confirmation, make sure
- # to add a presence check for the confirmation attribute:
+ # +nil+. To require confirmation, make sure to add a presence check for
+ # the confirmation attribute:
#
- # validates_presence_of :password_confirmation, :if => :password_changed?
+ # validates_presence_of :password_confirmation, if: :password_changed?
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
# confirmation").
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
- # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
- # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false
- # value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to
- # determine if the validation should not occur (e.g.
- # <tt>:unless => :skip_validation</tt>, or
- # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_confirmation_of(*attr_names)
validates_with ConfirmationValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index c8d7057606..3ec552c372 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -9,7 +9,7 @@ module ActiveModel
def validate_each(record, attribute, value)
if include?(record, value)
- record.errors.add(attribute, :exclusion, options.except(:in).merge!(:value => value))
+ record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(:value => value))
end
end
end
@@ -19,37 +19,30 @@ module ActiveModel
# particular enumerable object.
#
# class Person < ActiveRecord::Base
- # validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
- # validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
- # validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %{value} is not allowed"
- # validates_exclusion_of :password, :in => lambda { |p| [p.username, p.first_name] },
- # :message => "should not be the same as your username or first name"
+ # validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
+ # validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
+ # validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
+ # validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
+ # message: 'should not be the same as your username or first name'
+ # validates_exclusion_of :karma, in: :reserved_karmas
# end
#
# Configuration options:
- # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be
- # part of. This can be supplied as a proc or lambda which returns an
+ # * <tt>:in</tt> - An enumerable object of items that the value shouldn't
+ # be part of. This can be supplied as a proc, lambda or symbol which returns an
# enumerable. If the enumerable is a range the test is performed with
+ # * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
# reserved").
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute
- # is +nil+ (default is +false+).
+ # * <tt>:allow_nil</tt> - If set to true, skips this validation if the
+ # attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
# attribute is blank(default is +false+).
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
- # the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
- # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
- # or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
- # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
- # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_exclusion_of(*attr_names)
validates_with ExclusionValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index d48987c482..80150229a0 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -57,14 +57,14 @@ module ActiveModel
# attribute matches the regular expression:
#
# class Person < ActiveRecord::Base
- # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :on => :create
+ # validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
# end
#
# Alternatively, you can require that the specified attribute does _not_
# match the regular expression:
#
# class Person < ActiveRecord::Base
- # validates_format_of :email, :without => /NOSPAM/
+ # validates_format_of :email, without: /NOSPAM/
# end
#
# You can also provide a proc or lambda which will determine the regular
@@ -73,15 +73,16 @@ module ActiveModel
# class Person < ActiveRecord::Base
# # Admin can have number as a first letter in their screen name
# validates_format_of :screen_name,
- # :with => lambda{ |person| person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
+ # with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
# end
#
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
#
- # Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass the
- # :multiline => true option in case you use any of these two anchors in the provided
- # regular expression. In most cases, you should be using <tt>\A</tt> and <tt>\z</tt>.
+ # Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
+ # the <tt>multiline: true</tt> option in case you use any of these two
+ # anchors in the provided regular expression. In most cases, you should be
+ # using <tt>\A</tt> and <tt>\z</tt>.
#
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
# In addition, both must be a regular expression or a proc or lambda, or
@@ -89,32 +90,24 @@ module ActiveModel
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute
- # is +nil+ (default is +false+).
+ # * <tt>:allow_nil</tt> - If set to true, skips this validation if the
+ # attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
# attribute is blank (default is +false+).
# * <tt>:with</tt> - Regular expression that if the attribute matches will
- # result in a successful validation. This can be provided as a proc or lambda
- # returning regular expression which will be called at runtime.
- # * <tt>:without</tt> - Regular expression that if the attribute does not match
- # will result in a successful validation. This can be provided as a proc or
+ # result in a successful validation. This can be provided as a proc or
# lambda returning regular expression which will be called at runtime.
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
- # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
- # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
- # or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
- # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
- # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ # * <tt>:without</tt> - Regular expression that if the attribute does not
+ # match will result in a successful validation. This can be provided as
+ # a proc or lambda returning regular expression which will be called at
+ # runtime.
# * <tt>:multiline</tt> - Set to true if your regular expression contains
# anchors that match the beginning or end of lines as opposed to the
# beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_format_of(*attr_names)
validates_with FormatValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 154db5aedc..babc8982da 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -9,7 +9,7 @@ module ActiveModel
def validate_each(record, attribute, value)
unless include?(record, value)
- record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
+ record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(:value => value))
end
end
end
@@ -19,36 +19,29 @@ module ActiveModel
# particular enumerable object.
#
# class Person < ActiveRecord::Base
- # validates_inclusion_of :gender, :in => %w( m f )
- # validates_inclusion_of :age, :in => 0..99
- # validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %{value} is not included in the list"
- # validates_inclusion_of :states, :in => lambda{ |person| STATES[person.country] }
+ # validates_inclusion_of :gender, in: %w( m f )
+ # validates_inclusion_of :age, in: 0..99
+ # validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
+ # validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
+ # validates_inclusion_of :karma, in: :available_karmas
# end
#
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items. This can be
- # supplied as a proc or lambda which returns an enumerable. If the enumerable
- # is a range the test is performed with <tt>Range#cover?</tt>, otherwise with
- # <tt>include?</tt>.
- # * <tt>:message</tt> - Specifies a custom error message (default is: "is not
- # included in the list").
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute
- # is +nil+ (default is +false+).
- # * <tt>:allow_blank</tt> - If set to true, skips this validation if the
+ # supplied as a proc, lambda or symbol which returns an enumerable. If the
+ # enumerable is a range the test is performed with <tt>Range#cover?</tt>,
+ # otherwise with <tt>include?</tt>.
+ # * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
+ # * <tt>:message</tt> - Specifies a custom error message (default is: "is
+ # not included in the list").
+ # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
+ # attribute is +nil+ (default is +false+).
+ # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
# attribute is blank (default is +false+).
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
- # the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
- # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
- # or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
- # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
- # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_inclusion_of(*attr_names)
validates_with InclusionValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index 40ebe0cd2e..e4a1f9e80a 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -36,12 +36,12 @@ module ActiveModel
def validate_each(record, attribute, value)
value = tokenize(value)
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
-
+ errors_options = options.except(*RESERVED_OPTIONS)
+
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
next if value_length.send(validity_check, check_value)
- errors_options = options.except(*RESERVED_OPTIONS)
errors_options[:count] = check_value
default_message = options[MESSAGES[key]]
@@ -62,56 +62,48 @@ module ActiveModel
module HelperMethods
- # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
+ # Validates that the specified attribute matches the length restrictions
+ # supplied. Only one option can be used at a time:
#
# class Person < ActiveRecord::Base
- # validates_length_of :first_name, :maximum => 30
- # validates_length_of :last_name, :maximum => 30, :message => "less than 30 if you don't mind"
- # validates_length_of :fax, :in => 7..32, :allow_nil => true
- # validates_length_of :phone, :in => 7..32, :allow_blank => true
- # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
- # validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least 5 characters"
- # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with 4 characters... don't play me."
- # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least 100 words.",
- # :tokenizer => lambda { |str| str.scan(/\w+/) }
+ # validates_length_of :first_name, maximum: 30
+ # validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
+ # validates_length_of :fax, in: 7..32, allow_nil: true
+ # validates_length_of :phone, in: 7..32, allow_blank: true
+ # validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
+ # validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
+ # validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
+ # validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
+ # tokenizer: ->(str) { str.scan(/\w+/) }
# end
#
# Configuration options:
# * <tt>:minimum</tt> - The minimum size of the attribute.
# * <tt>:maximum</tt> - The maximum size of the attribute.
# * <tt>:is</tt> - The exact size of the attribute.
- # * <tt>:within</tt> - A range specifying the minimum and maximum size of the
- # attribute.
- # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
+ # * <tt>:within</tt> - A range specifying the minimum and maximum size of
+ # the attribute.
+ # * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
# * <tt>:too_long</tt> - The error message if the attribute goes over the
# maximum (default is: "is too long (maximum is %{count} characters)").
# * <tt>:too_short</tt> - The error message if the attribute goes under the
# minimum (default is: "is too short (min is %{count} characters)").
- # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method
- # and the attribute is the wrong size (default is: "is the wrong length
- # (should be %{count} characters)").
+ # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt>
+ # method and the attribute is the wrong size (default is: "is the wrong
+ # length (should be %{count} characters)").
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
- # the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
- # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
- # or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
- # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
- # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
- # proc or string should return or evaluate to a true or false value.
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
- # (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to count words
- # as in above example). Defaults to <tt>lambda{ |value| value.split(//) }</tt>
+ # (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
+ # as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
# which counts individual characters.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_length_of(*attr_names)
validates_with LengthValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 1069ed3906..edebca94a8 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -79,48 +79,40 @@ module ActiveModel
end
module HelperMethods
- # Validates whether the value of the specified attribute is numeric by trying
- # to convert it to a float with Kernel.Float (if <tt>only_integer</tt> is false)
- # or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt> (if
- # <tt>only_integer</tt> is set to true).
+ # Validates whether the value of the specified attribute is numeric by
+ # trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
+ # is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt>
+ # (if <tt>only_integer</tt> is set to +true+).
#
# class Person < ActiveRecord::Base
- # validates_numericality_of :value, :on => :create
+ # validates_numericality_of :value, on: :create
# end
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:only_integer</tt> - Specifies whether the value has to be an integer,
- # e.g. an integral value (default is +false+).
+ # * <tt>:only_integer</tt> - Specifies whether the value has to be an
+ # integer, e.g. an integral value (default is +false+).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
# +false+). Notice that for fixnum and float columns empty strings are
# converted to +nil+.
# * <tt>:greater_than</tt> - Specifies the value must be greater than the
# supplied value.
- # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater
- # than or equal the supplied value.
- # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
- # * <tt>:less_than</tt> - Specifies the value must be less than the supplied
- # value.
- # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or
- # equal the supplied value.
- # * <tt>:other_than</tt> - Specifies the value must be other than the supplied
+ # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be
+ # greater than or equal the supplied value.
+ # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied
# value.
+ # * <tt>:less_than</tt> - Specifies the value must be less than the
+ # supplied value.
+ # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less
+ # than or equal the supplied value.
+ # * <tt>:other_than</tt> - Specifies the value must be other than the
+ # supplied value.
# * <tt>:odd</tt> - Specifies the value must be an odd number.
# * <tt>:even</tt> - Specifies the value must be an even number.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
- # the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
- # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
- # or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
- # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
- # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+ .
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
#
# The following checks can also be supplied with a proc or a symbol which
# corresponds to a method:
@@ -134,8 +126,8 @@ module ActiveModel
# For example:
#
# class Person < ActiveRecord::Base
- # validates_numericality_of :width, :less_than => Proc.new { |person| person.height }
- # validates_numericality_of :width, :greater_than => :minimum_weight
+ # validates_numericality_of :width, less_than: Proc.new { |person| person.height }
+ # validates_numericality_of :width, greater_than: :minimum_weight
# end
def validates_numericality_of(*attr_names)
validates_with NumericalityValidator, _merge_attributes(attr_names)
diff --git a/activemodel/lib/active_model/validations/presence.rb b/activemodel/lib/active_model/validations/presence.rb
index a7dcdbba3d..f159e40858 100644
--- a/activemodel/lib/active_model/validations/presence.rb
+++ b/activemodel/lib/active_model/validations/presence.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActiveModel
@@ -20,28 +19,19 @@ module ActiveModel
#
# The first_name attribute must be in the object and it cannot be blank.
#
- # If you want to validate the presence of a boolean field (where the real values
- # are true and false), you will want to use
- # <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
+ # If you want to validate the presence of a boolean field (where the real
+ # values are +true+ and +false+), you will want to use
+ # <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
#
# This is due to the way Object#blank? handles boolean values:
# <tt>false.blank? # => true</tt>.
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
- # the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
- # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
- # or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
- # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
- # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
- # proc or string should return or evaluate to a true or false value.
- # * <tt>:strict</tt> - Specifies whether validation should be strict.
- # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
def validates_presence_of(*attr_names)
validates_with PresenceValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
index 6c13d2b4a2..eb6e604851 100644
--- a/activemodel/lib/active_model/validations/validates.rb
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -11,18 +11,18 @@ module ActiveModel
#
# Examples of using the default rails validators:
#
- # validates :terms, :acceptance => true
- # validates :password, :confirmation => true
- # validates :username, :exclusion => { :in => %w(admin superuser) }
- # validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }
- # validates :age, :inclusion => { :in => 0..9 }
- # validates :first_name, :length => { :maximum => 30 }
- # validates :age, :numericality => true
- # validates :username, :presence => true
- # validates :username, :uniqueness => true
+ # validates :terms, acceptance: true
+ # validates :password, confirmation: true
+ # validates :username, exclusion: { in: %w(admin superuser) }
+ # validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create }
+ # validates :age, inclusion: { in: 0..9 }
+ # validates :first_name, length: { maximum: 30 }
+ # validates :age, numericality: true
+ # validates :username, presence: true
+ # validates :username, uniqueness: true
#
# The power of the +validates+ method comes when using custom validators
- # and default validators in one call for a given attribute e.g.
+ # and default validators in one call for a given attribute.
#
# class EmailValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
@@ -35,12 +35,12 @@ module ActiveModel
# include ActiveModel::Validations
# attr_accessor :name, :email
#
- # validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 }
- # validates :email, :presence => true, :email => true
+ # validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
+ # validates :email, presence: true, email: true
# end
#
# Validator classes may also exist within the class being validated
- # allowing custom modules of validators to be included as needed e.g.
+ # allowing custom modules of validators to be included as needed.
#
# class Film
# include ActiveModel::Validations
@@ -51,33 +51,53 @@ module ActiveModel
# end
# end
#
- # validates :name, :title => true
+ # validates :name, title: true
# end
#
- # Additionally validator classes may be in another namespace and still used within any class.
+ # Additionally validator classes may be in another namespace and still
+ # used within any class.
#
# validates :name, :'film/title' => true
#
- # The validators hash can also handle regular expressions, ranges,
- # arrays and strings in shortcut form, e.g.
+ # The validators hash can also handle regular expressions, ranges, arrays
+ # and strings in shortcut form.
#
- # validates :email, :format => /@/
- # validates :gender, :inclusion => %w(male female)
- # validates :password, :length => 6..20
+ # validates :email, format: /@/
+ # validates :gender, inclusion: %w(male female)
+ # validates :password, length: 6..20
#
# When using shortcut form, ranges and arrays are passed to your
- # validator's initializer as +options[:in]+ while other types including
- # regular expressions and strings are passed as +options[:with]+
+ # validator's initializer as <tt>options[:in]</tt> while other types
+ # including regular expressions and strings are passed as <tt>options[:with]</tt>.
#
- # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+ and +:strict+
- # can be given to one specific validator, as a hash:
+ # There is also a list of options that could be used along with validators:
#
- # validates :password, :presence => { :if => :password_required? }, :confirmation => true
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or
+ # +false+ value.
+ # * <tt>:strict</tt> - if the <tt>:strict</tt> option is set to true
+ # will raise ActiveModel::StrictValidationFailed instead of adding the error.
+ # <tt>:strict</tt> option can also be set to any other exception.
#
- # Or to all at the same time:
+ # Example:
#
- # validates :password, :presence => true, :confirmation => true, :if => :password_required?
+ # validates :password, presence: true, confirmation: true, if: :password_required?
+ # validates :token, uniqueness: true, strict: TokenGenerationException
#
+ #
+ # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+
+ # and +:strict+ can be given to one specific validator, as a hash:
+ #
+ # validates :password, presence: { if: :password_required? }, confirmation: true
def validates(*attributes)
defaults = attributes.extract_options!.dup
validations = defaults.slice!(*_validates_default_keys)
@@ -105,8 +125,20 @@ module ActiveModel
# users and are considered exceptional. So each validator defined with bang
# or <tt>:strict</tt> option set to <tt>true</tt> will always raise
# <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
- # when validation fails.
- # See <tt>validates</tt> for more information about the validation itself.
+ # when validation fails. See <tt>validates</tt> for more information about
+ # the validation itself.
+ #
+ # class Person
+ #  include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates! :name, presence: true
+ # end
+ #
+ # person = Person.new
+ #  person.name = ''
+ #  person.valid?
+ # # => ActiveModel::StrictValidationFailed: Name can't be blank
def validates!(*attributes)
options = attributes.extract_options!
options[:strict] = true
@@ -117,7 +149,7 @@ module ActiveModel
# When creating custom validators, it might be useful to be able to specify
# additional default keys. This can be done by overwriting this method.
- def _validates_default_keys
+ def _validates_default_keys #:nodoc:
[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
end
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index 3c516f8b22..869591cd9e 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -34,7 +34,7 @@ module ActiveModel
# class MyValidator < ActiveModel::Validator
# def validate(record)
# if some_complex_logic
- # record.errors.add :base, "This record is invalid"
+ # record.errors.add :base, 'This record is invalid'
# end
# end
#
@@ -48,30 +48,32 @@ module ActiveModel
#
# class Person
# include ActiveModel::Validations
- # validates_with MyValidator, MyOtherValidator, :on => :create
+ # validates_with MyValidator, MyOtherValidator, on: :create
# end
#
# Configuration options:
# * <tt>:on</tt> - Specifies when this validation is active
- # (<tt>:create</tt> or <tt>:update</tt>
+ # (<tt>:create</tt> or <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
- # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
- # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
- # The method, proc or string should return or evaluate to a true or false value.
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
+ # The method, proc or string should return or evaluate to a +true+ or
+ # +false+ value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
# determine if the validation should not occur
- # (e.g. <tt>:unless => :skip_validation</tt>, or
- # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
- # The method, proc or string should return or evaluate to a true or false value.
+ # (e.g. <tt>unless: :skip_validation</tt>, or
+ # <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>).
+ # The method, proc or string should return or evaluate to a +true+ or
+ # +false+ value.
# * <tt>:strict</tt> - Specifies whether validation should be strict.
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
#
# If you pass any additional configuration options, they will be passed
- # to the class and available as <tt>options</tt>:
+ # to the class and available as +options+:
#
# class Person
# include ActiveModel::Validations
- # validates_with MyValidator, :my_custom_key => "my custom value"
+ # validates_with MyValidator, my_custom_key: 'my custom value'
# end
#
# class MyValidator < ActiveModel::Validator
@@ -119,17 +121,17 @@ module ActiveModel
# class Person
# include ActiveModel::Validations
#
- # validate :instance_validations, :on => :create
+ # validate :instance_validations, on: :create
#
# def instance_validations
# validates_with MyValidator, MyOtherValidator
# end
# end
#
- # Standard configuration options (:on, :if and :unless), which are
- # available on the class version of +validates_with+, should instead be
- # placed on the +validates+ method as these are applied and tested
- # in the callback.
+ # Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and
+ # <tt>:unless</tt>), which are available on the class version of
+ # +validates_with+, should instead be placed on the +validates+ method
+ # as these are applied and tested in the callback.
#
# If you pass any additional configuration options, they will be passed
# to the class and available as +options+, please refer to the
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 2953126c3c..85aec00f25 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -1,8 +1,6 @@
require "active_support/core_ext/module/anonymous"
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/object/inclusion'
-module ActiveModel #:nodoc:
+module ActiveModel
# == Active Model Validator
#
@@ -28,7 +26,7 @@ module ActiveModel #:nodoc:
# end
#
# Any class that inherits from ActiveModel::Validator must implement a method
- # called <tt>validate</tt> which accepts a <tt>record</tt>.
+ # called +validate+ which accepts a +record+.
#
# class Person
# include ActiveModel::Validations
@@ -42,8 +40,8 @@ module ActiveModel #:nodoc:
# end
# end
#
- # To cause a validation error, you must add to the <tt>record</tt>'s errors directly
- # from within the validators message
+ # To cause a validation error, you must add to the +record+'s errors directly
+ # from within the validators message.
#
# class MyValidator < ActiveModel::Validator
# def validate(record)
@@ -63,16 +61,16 @@ module ActiveModel #:nodoc:
# end
#
# The easiest way to add custom validators for validating individual attributes
- # is with the convenient <tt>ActiveModel::EachValidator</tt>. For example:
+ # is with the convenient <tt>ActiveModel::EachValidator</tt>.
#
# class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
- # record.errors.add attribute, 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.'])
+ # record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
# end
# end
#
# This can now be used in combination with the +validates+ method
- # (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this)
+ # (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this).
#
# class Person
# include ActiveModel::Validations
@@ -83,8 +81,7 @@ module ActiveModel #:nodoc:
#
# Validator may also define a +setup+ instance method which will get called
# with the class that using that validator as its argument. This can be
- # useful when there are prerequisites such as an +attr_accessor+ being present
- # for example:
+ # useful when there are prerequisites such as an +attr_accessor+ being present.
#
# class MyValidator < ActiveModel::Validator
# def setup(klass)
@@ -94,15 +91,13 @@ module ActiveModel #:nodoc:
#
# This setup method is only called when used with validation macros or the
# class level <tt>validates_with</tt> method.
- #
class Validator
attr_reader :options
- # Returns the kind of the validator. Examples:
+ # Returns the kind of the validator.
#
# PresenceValidator.kind # => :presence
# UniquenessValidator.kind # => :uniqueness
- #
def self.kind
@kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
end
@@ -113,6 +108,9 @@ module ActiveModel #:nodoc:
end
# Return the kind for this validator.
+ #
+ # PresenceValidator.new.kind # => :presence
+ # UniquenessValidator.new.kind # => :uniqueness 
def kind
self.class.kind
end
@@ -129,7 +127,7 @@ module ActiveModel #:nodoc:
# record, attribute and value.
#
# All Active Model validations are built on top of this validator.
- class EachValidator < Validator
+ class EachValidator < Validator #:nodoc:
attr_reader :attributes
# Returns a new validator instance. All options will be available via the
@@ -168,7 +166,7 @@ module ActiveModel #:nodoc:
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
# and call this block for each attribute being validated. +validates_each+ uses this validator.
- class BlockValidator < EachValidator
+ class BlockValidator < EachValidator #:nodoc:
def initialize(options, &block)
@block = block
super
diff --git a/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb b/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
index 418a24294a..b141cec059 100644
--- a/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
+++ b/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
@@ -1,6 +1,5 @@
require "cases/helper"
require 'active_support/logger'
-require 'active_support/core_ext/object/inclusion'
class SanitizerTest < ActiveModel::TestCase
attr_accessor :logger
diff --git a/activemodel/test/cases/mass_assignment_security_test.rb b/activemodel/test/cases/mass_assignment_security_test.rb
index 0c6352cd71..45757615f5 100644
--- a/activemodel/test/cases/mass_assignment_security_test.rb
+++ b/activemodel/test/cases/mass_assignment_security_test.rb
@@ -11,7 +11,6 @@ class CustomSanitizer < ActiveModel::MassAssignmentSecurity::Sanitizer
end
class MassAssignmentSecurityTest < ActiveModel::TestCase
-
def test_attribute_protection
user = User.new
expected = { "name" => "John Smith", "email" => "john@smith.com" }
@@ -96,7 +95,6 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase
assert_blank TightDescendant.protected_attributes(:admin) - TightDescendant.attributes_protected_by_default
assert_equal Set.new(['name', 'address', 'admin', 'super_powers']), TightDescendant.accessible_attributes(:admin)
-
end
def test_mass_assignment_multiparameter_protector
@@ -107,14 +105,14 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase
end
def test_custom_sanitizer
+ old_sanitizer = User._mass_assignment_sanitizer
+
user = User.new
User.mass_assignment_sanitizer = CustomSanitizer.new
assert_raise StandardError do
user.sanitize_for_mass_assignment("admin" => true)
end
ensure
- User.mass_assignment_sanitizer = nil
-
+ User.mass_assignment_sanitizer = old_sanitizer
end
-
-end
+end \ No newline at end of file
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
index 5f18909301..8650b0e495 100644
--- a/activemodel/test/cases/secure_password_test.rb
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -1,5 +1,6 @@
require 'cases/helper'
require 'models/user'
+require 'models/oauthed_user'
require 'models/visitor'
require 'models/administrator'
@@ -8,6 +9,7 @@ class SecurePasswordTest < ActiveModel::TestCase
setup do
@user = User.new
@visitor = Visitor.new
+ @oauthed_user = OauthedUser.new
end
test "blank password" do
@@ -73,4 +75,10 @@ class SecurePasswordTest < ActiveModel::TestCase
@user.run_callbacks :create
end
end
+
+ test "Oauthed user can be created with blank digest" do
+ assert_nothing_raised do
+ @oauthed_user.run_callbacks :create
+ end
+ end
end
diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb
index a93323a3a8..8c5a3c5efd 100644..100755
--- a/activemodel/test/cases/serializers/xml_serialization_test.rb
+++ b/activemodel/test/cases/serializers/xml_serialization_test.rb
@@ -28,7 +28,7 @@ class Address
extend ActiveModel::Naming
include ActiveModel::Serializers::Xml
- attr_accessor :street, :city, :state, :zip
+ attr_accessor :street, :city, :state, :zip, :apt_number
def attributes
instance_values
@@ -56,6 +56,7 @@ class XmlSerializationTest < ActiveModel::TestCase
@contact.address.city = "Springfield"
@contact.address.state = "CA"
@contact.address.zip = 11111
+ @contact.address.apt_number = 35
@contact.friends = [Contact.new, Contact.new]
end
@@ -222,4 +223,39 @@ class XmlSerializationTest < ActiveModel::TestCase
assert_match %r{<friends>}, xml
assert_match %r{<friend>}, xml
end
+
+ test "propagates skip-types option to included associations and attributes" do
+ xml = @contact.to_xml :skip_types => true, :include => :address, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number>}, xml
+ end
+
+ test "propagates camelize option to included associations and attributes" do
+ xml = @contact.to_xml :camelize => true, :include => :address, :indent => 0
+ assert_match %r{<Address>}, xml
+ assert_match %r{<AptNumber type="integer">}, xml
+ end
+
+ test "propagates dasherize option to included associations and attributes" do
+ xml = @contact.to_xml :dasherize => false, :include => :address, :indent => 0
+ assert_match %r{<apt_number type="integer">}, xml
+ end
+
+ test "don't propagate skip_types if skip_types is defined at the included association level" do
+ xml = @contact.to_xml :skip_types => true, :include => { :address => { :skip_types => false } }, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "don't propagate camelize if camelize is defined at the included association level" do
+ xml = @contact.to_xml :camelize => true, :include => { :address => { :camelize => false } }, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "don't propagate dasherize if dasherize is defined at the included association level" do
+ xml = @contact.to_xml :dasherize => false, :include => { :address => { :dasherize => true } }, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
end
diff --git a/activemodel/test/cases/validations/callbacks_test.rb b/activemodel/test/cases/validations/callbacks_test.rb
index e4f602bd80..0015b3c196 100644
--- a/activemodel/test/cases/validations/callbacks_test.rb
+++ b/activemodel/test/cases/validations/callbacks_test.rb
@@ -20,7 +20,7 @@ class DogWithMethodCallbacks < Dog
def set_after_validation_marker; self.history << 'after_validation_marker' ; end
end
-class DogValidtorsAreProc < Dog
+class DogValidatorsAreProc < Dog
before_validation { self.history << 'before_validation_marker' }
after_validation { self.history << 'after_validation_marker' }
end
@@ -49,7 +49,7 @@ class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase
end
def test_before_validation_and_after_validation_callbacks_should_be_called_with_proc
- d = DogValidtorsAreProc.new
+ d = DogValidatorsAreProc.new
d.valid?
assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
end
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
index adab8ccb2b..7d5af27f3d 100644
--- a/activemodel/test/cases/validations/exclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -28,6 +28,16 @@ class ExclusionValidationTest < ActiveModel::TestCase
assert_equal ["option monkey is restricted"], t.errors[:title]
end
+ def test_validates_exclusion_of_with_within_option
+ Topic.validates_exclusion_of( :title, :within => %w( abe monkey ) )
+
+ assert Topic.new("title" => "something", "content" => "abc")
+
+ t = Topic.new("title" => "monkey")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ end
+
def test_validates_exclusion_of_for_ruby_class
Person.validates_exclusion_of :karma, :in => %w( abe monkey )
@@ -54,4 +64,29 @@ class ExclusionValidationTest < ActiveModel::TestCase
t.title = "wasabi"
assert t.valid?
end
+
+ def test_validates_inclusion_of_with_symbol
+ Person.validates_exclusion_of :karma, :in => :reserved_karmas
+
+ p = Person.new
+ p.karma = "abe"
+
+ def p.reserved_karmas
+ %w(abe)
+ end
+
+ assert p.invalid?
+ assert_equal ["is reserved"], p.errors[:karma]
+
+ p = Person.new
+ p.karma = "abe"
+
+ def p.reserved_karmas
+ %w()
+ end
+
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
end
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index bb751cf9c5..4f8b7327c0 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -159,6 +159,17 @@ class I18nValidationTest < ActiveModel::TestCase
end
end
+ # validates_inclusion_of using :within w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_inclusion_of using :within on generated message #{name}" do
+ Person.validates_inclusion_of :title, validation_options.merge(:within => %w(a b c))
+ @person.title = 'z'
+ @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z'))
+ @person.valid?
+ end
+ end
+
# validates_exclusion_of w/ mocha
COMMON_CASES.each do |name, validation_options, generate_message_options|
@@ -170,6 +181,17 @@ class I18nValidationTest < ActiveModel::TestCase
end
end
+ # validates_exclusion_of using :within w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_exclusion_of using :within generated message #{name}" do
+ Person.validates_exclusion_of :title, validation_options.merge(:within => %w(a b c))
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a'))
+ @person.valid?
+ end
+ end
+
# validates_numericality_of without :only_integer w/ mocha
COMMON_CASES.each do |name, validation_options, generate_message_options|
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 851d345eab..117e9109fc 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -60,6 +60,16 @@ class InclusionValidationTest < ActiveModel::TestCase
assert_equal ["option uhoh is not in the list"], t.errors[:title]
end
+ def test_validates_inclusion_of_with_within_option
+ Topic.validates_inclusion_of( :title, :within => %w( a b c d e f g ) )
+
+ assert Topic.new("title" => "a", "content" => "abc").valid?
+
+ t = Topic.new("title" => "uhoh", "content" => "abc")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ end
+
def test_validates_inclusion_of_for_ruby_class
Person.validates_inclusion_of :karma, :in => %w( abe monkey )
@@ -86,4 +96,29 @@ class InclusionValidationTest < ActiveModel::TestCase
t.title = "elephant"
assert t.valid?
end
+
+ def test_validates_inclusion_of_with_symbol
+ Person.validates_inclusion_of :karma, :in => :available_karmas
+
+ p = Person.new
+ p.karma = "Lifo"
+
+ def p.available_karmas
+ %w()
+ end
+
+ assert p.invalid?
+ assert_equal ["is not included in the list"], p.errors[:karma]
+
+ p = Person.new
+ p.karma = "Lifo"
+
+ def p.available_karmas
+ %w(Lifo)
+ end
+
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 8ea9745fbf..a9d32808da 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -11,6 +11,8 @@ require 'active_support/xml_mini'
class ValidationsTest < ActiveModel::TestCase
+ class CustomStrictValidationException < StandardError; end
+
def setup
Topic._validators.clear
end
@@ -323,6 +325,13 @@ class ValidationsTest < ActiveModel::TestCase
end
end
+ def test_strict_validation_custom_exception
+ Topic.validates_presence_of :title, :strict => CustomStrictValidationException
+ assert_raises CustomStrictValidationException do
+ Topic.new.valid?
+ end
+ end
+
def test_validates_with_bang
Topic.validates! :title, :presence => true
assert_raises ActiveModel::StrictValidationFailed do
diff --git a/activemodel/test/models/oauthed_user.rb b/activemodel/test/models/oauthed_user.rb
new file mode 100644
index 0000000000..9750bc19d4
--- /dev/null
+++ b/activemodel/test/models/oauthed_user.rb
@@ -0,0 +1,11 @@
+class OauthedUser
+ extend ActiveModel::Callbacks
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ has_secure_password(validations: false)
+
+ attr_accessor :password_digest, :password_salt
+end
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 36d94fb38b..85880e97ea 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,5 +1,143 @@
## Rails 4.0.0 (unreleased) ##
+* Allow to pass Symbol or Proc into :limit option of #accepts_nested_attributes_for
+
+ *Mikhail Dieterle*
+
+* ActiveRecord::SessionStore has been extracted from Active Record as `activerecord-session_store`
+ gem. Please read the `README.md` file on the gem for the usage. *Prem Sichanugrist*
+
+* Fix `reset_counters` when there are multiple `belongs_to` association with the
+ same foreign key and one of them have a counter cache.
+ Fixes #5200.
+
+ *Dave Desrochers*
+
+* `serialized_attributes` and `_attr_readonly` become class method only. Instance reader methods are deprecated.
+
+ *kennyj*
+
+* Round usec when comparing timestamp attributes in the dirty tracking.
+ Fixes #6975.
+
+ *kennyj*
+
+* Use inversed parent for first and last child of has_many association.
+
+ *Ravil Bayramgalin*
+
+* Fix Column.microseconds and Column.fast_string_to_date to avoid converting
+ timestamp seconds to a float, since it occasionally results in inaccuracies
+ with microsecond-precision times. Fixes #7352.
+
+ *Ari Pollak*
+
+* Raise `ArgumentError` if list of attributes to change is empty in `update_all`.
+
+ *Roman Shatsov*
+
+* Fix AR#create to return an unsaved record when AR::RecordInvalid is
+ raised. Fixes #3217.
+
+ *Dave Yeu*
+
+* Fixed table name prefix that is generated in engines for namespaced models
+ *Wojciech Wnętrzak*
+
+* Make sure `:environment` task is executed before `db:schema:load` or `db:structure:load`
+ Fixes #4772.
+
+ *Seamus Abshere*
+
+* Allow Relation#merge to take a proc.
+
+ This was requested by DHH to allow creating of one's own custom
+ association macros.
+
+ For example:
+
+ module Commentable
+ def has_many_comments(extra)
+ has_many :comments, -> { where(:foo).merge(extra) }
+ end
+ end
+
+ class Post < ActiveRecord::Base
+ extend Commentable
+ has_many_comments -> { where(:bar) }
+ end
+
+ *Jon Leighton*
+
+* Add CollectionProxy#scope
+
+ This can be used to get a Relation from an association.
+
+ Previously we had a #scoped method, but we're deprecating that for
+ AR::Base, so it doesn't make sense to have it here.
+
+ This was requested by DHH, to facilitate code like this:
+
+ Project.scope.order('created_at DESC').page(current_page).tagged_with(@tag).limit(5).scoping do
+ @topics = @project.topics.scope
+ @todolists = @project.todolists.scope
+ @attachments = @project.attachments.scope
+ @documents = @project.documents.scope
+ end
+
+ *Jon Leighton*
+
+* Add `Relation#load`
+
+ This method explicitly loads the records and then returns `self`.
+
+ Rather than deciding between "do I want an array or a relation?",
+ most people are actually asking themselves "do I want to eager load
+ or lazy load?" Therefore, this method provides a way to explicitly
+ eager-load without having to switch from a `Relation` to an array.
+
+ Example:
+
+ @posts = Post.where(published: true).load
+
+ *Jon Leighton*
+
+* `Model.all` now returns an `ActiveRecord::Relation`, rather than an
+ array of records. Use ``Relation#to_a` if you really want an array.
+
+ In some specific cases, this may cause breakage when upgrading.
+ However in most cases the `ActiveRecord::Relation` will just act as a
+ lazy-loaded array and there will be no problems.
+
+ Note that calling `Model.all` with options (e.g.
+ `Model.all(conditions: '...')` was already deprecated, but it will
+ still return an array in order to make the transition easier.
+
+ `Model.scoped` is deprecated in favour of `Model.all`.
+
+ `Relation#all` still returns an array, but is deprecated (since it
+ would serve no purpose if we made it return a `Relation`).
+
+ *Jon Leighton*
+
+* `:finder_sql` and `:counter_sql` options on collection associations
+ are deprecated. Please transition to using scopes.
+
+ *Jon Leighton*
+
+* `:insert_sql` and `:delete_sql` options on `has_and_belongs_to_many`
+ associations are deprecated. Please transition to using `has_many
+ :through`
+
+ *Jon Leighton*
+
+* The migration generator now creates a join table with (commented) indexes every time
+ the migration name contains the word `join_table`:
+
+ rails g migration create_join_table_for_artists_and_musics artist_id:index music_id
+
+ *Aleksey Magusev*
+
* Add `add_reference` and `remove_reference` schema statements. Aliases, `add_belongs_to`
and `remove_belongs_to` are acceptable. References are reversible.
Examples:
@@ -23,11 +161,11 @@
* `ActiveRecord::Relation#inspect` now makes it clear that you are
dealing with a `Relation` object rather than an array:.
- User.where(:age => 30).inspect
- # => <ActiveRecord::Relation [#<User ...>, #<User ...>, ...]>
+ User.where(:age => 30).inspect
+ # => <ActiveRecord::Relation [#<User ...>, #<User ...>, ...]>
- User.where(:age => 30).to_a.inspect
- # => [#<User ...>, #<User ...>]
+ User.where(:age => 30).to_a.inspect
+ # => [#<User ...>, #<User ...>]
The number of records displayed will be limited to 10.
@@ -36,18 +174,25 @@
* Add `collation` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later.
Example:
- development:
- adapter: postgresql
- host: localhost
- database: rails_development
- username: foo
- password: bar
- encoding: UTF8
- collation: ja_JP.UTF8
- ctype: ja_JP.UTF8
+ development:
+ adapter: postgresql
+ host: localhost
+ database: rails_development
+ username: foo
+ password: bar
+ encoding: UTF8
+ collation: ja_JP.UTF8
+ ctype: ja_JP.UTF8
*kennyj*
+* Changed validates_presence_of on an association so that children objects
+ do not validate as being present if they are marked for destruction. This
+ prevents you from saving the parent successfully and thus putting the parent
+ in an invalid state.
+
+ *Nick Monje & Brent Wheeldon*
+
* `FinderMethods#exists?` now returns `false` with the `false` argument.
*Egor Lynko*
@@ -124,29 +269,6 @@
*Joost Baaij & Carlos Antonio da Silva*
-* `composed_of` was removed. You'll have to write your own accessor
- and mutator methods if you'd like to use value objects to represent some
- portion of your models. So, instead of:
-
- class Person < ActiveRecord::Base
- composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
- end
-
- you could write something like this:
-
- def address
- @address ||= Address.new(address_street, address_city)
- end
-
- def address=(address)
- self[:address_street] = @address.street
- self[:address_city] = @address.city
-
- @address = address
- end
-
- *Steve Klabnik*
-
* PostgreSQL default log level is now 'warning', to bypass the noisy notice
messages. You can change the log level using the `min_messages` option
available in your config/database.yml.
@@ -155,12 +277,6 @@
* Add uuid datatype support to PostgreSQL adapter. *Konstantin Shabanov*
-* `update_attribute` has been removed. Use `update_column` if
- you want to bypass mass-assignment protection, validations, callbacks,
- and touching of updated_at. Otherwise please use `update_attributes`.
-
- *Steve Klabnik*
-
* Added `ActiveRecord::Migration.check_pending!` that raises an error if
migrations are pending. *Richard Schneeman*
@@ -204,7 +320,7 @@
`where(...).first_or_create!`
The implementation of the deprecated dynamic finders has been moved
- to the `active_record_deprecated_finders` gem. See below for details.
+ to the `activerecord-deprecated_finders` gem. See below for details.
*Jon Leighton*
@@ -220,13 +336,12 @@
Note that as an interim step, it is possible to rewrite the above as:
- Post.scoped(:where => { :comments_count => 10 }, :limit => 5)
+ Post.all.merge(:where => { :comments_count => 10 }, :limit => 5)
This could save you a lot of work if there is a lot of old-style
finder usage in your application.
- Calling `Post.scoped(options)` is a shortcut for
- `Post.scoped.merge(options)`. `Relation#merge` now accepts a hash of
+ `Relation#merge` now accepts a hash of
options, but they must be identical to the names of the equivalent
finder method. These are mostly identical to the old-style finder
option names, except in the following cases:
@@ -236,7 +351,7 @@
* `:extend` becomes `:extending`
The code to implement the deprecated features has been moved out to
- the `active_record_deprecated_finders` gem. This gem is a dependency
+ the `activerecord-deprecated_finders` gem. This gem is a dependency
of Active Record in Rails 4.0. It will no longer be a dependency
from Rails 4.1, but if your app relies on the deprecated features
then you can add it to your own Gemfile. It will be maintained by
@@ -371,7 +486,7 @@
RAILS_ENV=production bundle exec rake db:schema:cache:dump
=> generate db/schema_cache.dump
- 2) add config.use_schema_cache_dump = true in config/production.rb. BTW, true is default.
+ 2) add config.active_record.use_schema_cache_dump = true in config/production.rb. BTW, true is default.
3) boot rails.
RAILS_ENV=production bundle exec rails server
@@ -388,11 +503,11 @@
The `add_index` method now supports a `where` option that receives a
string with the partial index criteria.
- add_index(:accounts, :code, :where => "active")
+ add_index(:accounts, :code, :where => "active")
- Generates
+ Generates
- CREATE INDEX index_accounts_on_code ON accounts(code) WHERE active
+ CREATE INDEX index_accounts_on_code ON accounts(code) WHERE active
*Marcelo Silveira*
@@ -409,24 +524,13 @@
* Added the `ActiveRecord::NullRelation` class implementing the null
object pattern for the Relation class. *Juanjo Bazán*
-* Added deprecation for the `:dependent => :restrict` association option.
-
- Please note:
-
- * Up until now `has_many` and `has_one`, `:dependent => :restrict`
- option raised a `DeleteRestrictionError` at the time of destroying
- the object. Instead, it will add an error on the model.
-
- * To fix this warning, make sure your code isn't relying on a
- `DeleteRestrictionError` and then add
- `config.active_record.dependent_restrict_raises = false` to your
- application config.
+* Added new `:dependent => :restrict_with_error` option. This will add
+ an error to the model, rather than raising an exception.
- * New rails application would be generated with the
- `config.active_record.dependent_restrict_raises = false` in the
- application config.
+ The `:restrict` option is renamed to `:restrict_with_exception` to
+ make this distinction explicit.
- *Manoj Kumar*
+ *Manoj Kumar & Jon Leighton*
* Added `create_join_table` migration helper to create HABTM join tables
@@ -512,6866 +616,104 @@
* PostgreSQL hstore types are automatically deserialized from the database.
+## Rails 3.2.8 (Aug 9, 2012) ##
-## Rails 3.2.5 (Jun 1, 2012) ##
-
-* Restore behavior of Active Record 3.2.3 scopes.
- A series of commits relating to preloading and scopes caused a regression.
-
- *Andrew White*
-
-
-## Rails 3.2.4 (May 31, 2012) ##
-
-* Perf fix: Don't load the records when doing assoc.delete_all.
- GH #6289. *Jon Leighton*
-
-* Association preloading shouldn't be affected by the current scoping.
- This could cause infinite recursion and potentially other problems.
- See GH #5667. *Jon Leighton*
-
-* Datetime attributes are forced to be changed. GH #3965
-
-* Fix attribute casting. GH #5549
-
-* Fix #5667. Preloading should ignore scoping.
-
-* Predicate builder should not recurse for determining where columns.
- Thanks to Ben Murphy for reporting this! CVE-2012-2661
-
-
-## Rails 3.2.3 (March 30, 2012) ##
-
-* Added find_or_create_by_{attribute}! dynamic method. *Andrew White*
-
-* Whitelist all attribute assignment by default. Change the default for newly generated applications to whitelist all attribute assignment. Also update the generated model classes so users are reminded of the importance of attr_accessible. *NZKoz*
-
-* Update ActiveRecord::AttributeMethods#attribute_present? to return false for empty strings. *Jacobkg*
-
-* Fix associations when using per class databases. *larskanis*
-
-* Revert setting NOT NULL constraints in add_timestamps *fxn*
-
-* Fix mysql to use proper text types. Fixes #3931. *kennyj*
-
-* Fix #5069 - Protect foreign key from mass assignment through association builder. *byroot*
-
-
-## Rails 3.2.2 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.1 (January 26, 2012) ##
-
-* The threshold for auto EXPLAIN is ignored if there's no logger. *fxn*
-
-* Call `to_s` on the value passed to `table_name=`, in particular symbols
- are supported (regression). *Sergey Nartimov*
-
-* Fix possible race condition when two threads try to define attribute
- methods for the same class. *Jon Leighton*
-
-
-## Rails 3.2.0 (January 20, 2012) ##
-
-* Added a `with_lock` method to ActiveRecord objects, which starts
- a transaction, locks the object (pessimistically) and yields to the block.
- The method takes one (optional) parameter and passes it to `lock!`.
-
- Before:
-
- class Order < ActiveRecord::Base
- def cancel!
- transaction do
- lock!
- # ... cancelling logic
- end
- end
- end
-
- After:
-
- class Order < ActiveRecord::Base
- def cancel!
- with_lock do
- # ... cancelling logic
- end
- end
- end
-
- *Olek Janiszewski*
-
-* 'on' and 'ON' boolean columns values are type casted to true
- *Santiago Pastorino*
-
-* Added ability to run migrations only for given scope, which allows
- to run migrations only from one engine (for example to revert changes
- from engine that you want to remove).
-
- Example:
- rake db:migrate SCOPE=blog
-
- *Piotr Sarnacki*
-
-* Migrations copied from engines are now scoped with engine's name,
- for example 01_create_posts.blog.rb. *Piotr Sarnacki*
-
-* Implements `AR::Base.silence_auto_explain`. This method allows the user to
- selectively disable automatic EXPLAINs within a block. *fxn*
-
-* Implements automatic EXPLAIN logging for slow queries.
-
- A new configuration parameter `config.active_record.auto_explain_threshold_in_seconds`
- determines what's to be considered a slow query. Setting that to `nil` disables
- this feature. Defaults are 0.5 in development mode, and `nil` in test and production
- modes.
-
- As of this writing there's support for SQLite, MySQL (mysql2 adapter), and
- PostgreSQL.
-
- *fxn*
-
-* Implemented ActiveRecord::Relation#pluck method
-
- Method returns Array of column value from table under ActiveRecord model
-
- Client.pluck(:id)
-
- *Bogdan Gusiev*
-
-* Automatic closure of connections in threads is deprecated. For example
- the following code is deprecated:
-
- Thread.new { Post.find(1) }.join
-
- It should be changed to close the database connection at the end of
- the thread:
-
- Thread.new {
- Post.find(1)
- Post.connection.close
- }.join
-
- Only people who spawn threads in their application code need to worry
- about this change.
-
-* Deprecated:
-
- * `set_table_name`
- * `set_inheritance_column`
- * `set_sequence_name`
- * `set_primary_key`
- * `set_locking_column`
-
- Use an assignment method instead. For example, instead of `set_table_name`, use `self.table_name=`:
-
- class Project < ActiveRecord::Base
- self.table_name = "project"
- end
-
- Or define your own `self.table_name` method:
-
- class Post < ActiveRecord::Base
- def self.table_name
- "special_" + super
- end
- end
- Post.table_name # => "special_posts"
-
- *Jon Leighton*
-
-* Generated association methods are created within a separate module to allow overriding and
- composition using `super`. For a class named `MyModel`, the module is named
- `MyModel::GeneratedFeatureMethods`. It is included into the model class immediately after
- the `generated_attributes_methods` module defined in ActiveModel, so association methods
- override attribute methods of the same name. *Josh Susser*
-
-* Implemented ActiveRecord::Relation#explain. *fxn*
-
-* Add ActiveRecord::Relation#uniq for generating unique queries.
-
- Before:
-
- Client.select('DISTINCT name')
-
- After:
-
- Client.select(:name).uniq
-
- This also allows you to revert the uniqueness in a relation:
-
- Client.select(:name).uniq.uniq(false)
-
- *Jon Leighton*
-
-* Support index sort order in sqlite, mysql and postgres adapters. *Vlad Jebelev*
-
-* Allow the :class_name option for associations to take a symbol (:Client) in addition to
- a string ('Client').
-
- This is to avoid confusing newbies, and to be consistent with the fact that other options
- like :foreign_key already allow a symbol or a string.
-
- *Jon Leighton*
-
-* In development mode the db:drop task also drops the test database. For symmetry with
- the db:create task. *Dmitriy Kiriyenko*
-
-* Added ActiveRecord::Base.store for declaring simple single-column key/value stores *DHH*
-
- class User < ActiveRecord::Base
- store :settings, accessors: [ :color, :homepage ]
- end
-
- u = User.new(color: 'black', homepage: '37signals.com')
- u.color # Accessor stored attribute
- u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
-
-
-* MySQL: case-insensitive uniqueness validation avoids calling LOWER when
- the column already uses a case-insensitive collation. Fixes #561.
-
- *Joseph Palermo*
-
-* Transactional fixtures enlist all active database connections. You can test
- models on different connections without disabling transactional fixtures.
-
- *Jeremy Kemper*
-
-* Add first_or_create, first_or_create!, first_or_initialize methods to Active Record. This is a
- better approach over the old find_or_create_by dynamic methods because it's clearer which
- arguments are used to find the record and which are used to create it:
-
- User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson")
-
- *Andrés Mejía*
-
-* Fix nested attributes bug where _destroy parameter is taken into account
- during :reject_if => :all_blank (fixes #2937)
-
- *Aaron Christy*
-
-
-## Rails 3.1.4 (March 1, 2012) ##
-
- * Fix a custom primary key regression *GH 3987*
-
- *Jon Leighton*
-
- * Perf fix (second try): don't load records for `has many :dependent =>
- :delete_all` *GH 3672*
-
- *Jon Leighton*
-
- * Fix accessing `proxy_association` method from an association extension
- where the calls are chained. *GH #3890*
-
- (E.g. `post.comments.where(bla).my_proxy_method`)
-
- *Jon Leighton*
-
- * Perf fix: MySQL primary key lookup was still slow for very large
- tables. *GH 3678*
-
- *Kenny J*
-
- * Perf fix: If a table has no primary key, don't repeatedly ask the database for it.
-
- *Julius de Bruijn*
-
-
-### Rails 3.1.3 (November 20, 2011) ##
-
-* Perf fix: If we're deleting all records in an association, don't add a IN(..) clause
- to the query. *GH 3672*
-
- *Jon Leighton*
-
-* Fix bug with referencing other mysql databases in set_table_name. *GH 3690*
-
-* Fix performance bug with mysql databases on a server with lots of other databses. *GH 3678*
-
- *Christos Zisopoulos and Kenny J*
-
-
-### Rails 3.1.2 (November 18, 2011) ##
-
-* Fix bug with PostgreSQLAdapter#indexes. When the search path has multiple schemas, spaces
- were not being stripped from the schema names after the first.
-
- *Sean Kirby*
-
-* Preserve SELECT columns on the COUNT for finder_sql when possible. *GH 3503*
-
- *Justin Mazzi*
-
-* Reset prepared statement cache when schema changes impact statement results. *GH 3335*
-
- *Aaron Patterson*
-
-* Postgres: Do not attempt to deallocate a statement if the connection is no longer active.
-
- *Ian Leitch*
-
-* Prevent QueryCache leaking database connections. *GH 3243*
-
- *Mark J. Titorenko*
-
-* Fix bug where building the conditions of a nested through association could potentially
- modify the conditions of the through and/or source association. If you have experienced
- bugs with conditions appearing in the wrong queries when using nested through associations,
- this probably solves your problems. *GH #3271*
-
- *Jon Leighton*
-
-* If a record is removed from a has_many :through, all of the join records relating to that
- record should also be removed from the through association's target.
-
- *Jon Leighton*
-
-* Fix adding multiple instances of the same record to a has_many :through. *GH #3425*
-
- *Jon Leighton*
-
-* Fix creating records in a through association with a polymorphic source type. *GH #3247*
-
- *Jon Leighton*
-
-* MySQL: use the information_schema than the describe command when we look for a primary key. *GH #3440*
-
- *Kenny J*
-
-
-## Rails 3.1.1 (October 7, 2011) ##
-
-* Add deprecation for the preload_associations method. Fixes #3022.
-
- *Jon Leighton*
-
-* Don't require a DB connection when loading a model that uses set_primary_key. GH #2807.
-
- *Jon Leighton*
-
-* Fix using select() with a habtm association, e.g. Person.friends.select(:name). GH #3030 and
- \#2923.
-
- *Hendy Tanata*
-
-* Fix belongs_to polymorphic with custom primary key on target. GH #3104.
-
- *Jon Leighton*
-
-* CollectionProxy#replace should change the DB records rather than just mutating the array.
- Fixes #3020.
-
- *Jon Leighton*
-
-* LRU cache in mysql and sqlite are now per-process caches.
-
- * lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache keys are per process id.
- * lib/active_record/connection_adapters/sqlite_adapter.rb: ditto
- *Aaron Patterson*
-
-* Support bulk change_table in mysql2 adapter, as well as the mysql one. *Jon Leighton*
-
-* If multiple parameters are sent representing a date, and some are blank, the
- resulting object is nil. In previous releases those values defaulted to 1. This only affects existing but blank parameters, missing ones still raise an error. [Akira Matsuda]
-* ActiveRecord::Base.establish_connection now takes a string that contains
- a URI that specifies the connection configuration. For example:
- ActiveRecord::Base.establish_connection 'postgres://localhost/foo'
-
-## Rails 3.1.0 (August 30, 2011) ##
-
-* Add a proxy_association method to association proxies, which can be called by association
- extensions to access information about the association. This replaces proxy_owner etc with
- proxy_association.owner.
-
- *Jon Leighton*
-
-* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature.
-
- Before: def build_association(*options)
- After: def build_association(*options, &block)
-
- Users who are redefining this method to extend functionality should ensure that the block is
- passed through to ActiveRecord::Base#new.
-
- This change is necessary to fix https://github.com/rails/rails/issues/1842.
-
- *Jon Leighton*
-
-* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model:
-
- class User < ActiveRecord::Base
- self.pluralize_table_names = false
- end
-
- Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. *Guillermo Iguaran*
-
-* Add block setting of attributes to singular associations:
-
- class User < ActiveRecord::Base
- has_one :account
- end
-
- user.build_account{ |a| a.credit_limit = 100.0 }
-
- The block is called after the instance has been initialized. *Andrew White*
-
-* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. *Prem Sichanugrist*
-
-* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0
+* Do not consider the numeric attribute as changed if the old value is zero and the new value
+ is not a string.
+ Fixes #7237.
-* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you
- to specify which role to consider when assigning attributes. This is built on top of ActiveModel's
- new mass assignment capabilities:
-
- class Post < ActiveRecord::Base
- attr_accessible :title
- attr_accessible :title, :published_at, :as => :admin
- end
-
- Post.new(params[:post], :as => :admin)
-
- assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated.
-
- Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly.
-
- *Josh Kalderimis*
-
-* default_scope can take a block, lambda, or any other object which responds to `call` for lazy
- evaluation:
-
- default_scope { ... }
- default_scope lambda { ... }
- default_scope method(:foo)
-
- This feature was originally implemented by Tim Morgan, but was then removed in favour of
- defining a 'default_scope' class method, but has now been added back in by Jon Leighton.
- The relevant lighthouse ticket is #1812.
-
-* Default scopes are now evaluated at the latest possible moment, to avoid problems where
- scopes would be created which would implicitly contain the default scope, which would then
- be impossible to get rid of via Model.unscoped.
-
- Note that this means that if you are inspecting the internal structure of an
- ActiveRecord::Relation, it will *not* contain the default scope, though the resulting
- query will do. You can get a relation containing the default scope by calling
- ActiveRecord#with_default_scope, though this is not part of the public API.
-
- *Jon Leighton*
-
-* If you wish to merge default scopes in special ways, it is recommended to define your default
- scope as a class method and use the standard techniques for sharing code (inheritance, mixins,
- etc.):
-
- class Post < ActiveRecord::Base
- def self.default_scope
- where(:published => true).where(:hidden => false)
- end
- end
-
- *Jon Leighton*
-
-* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
-
-* ConnectionManagement middleware is changed to clean up the connection pool
- after the rack body has been flushed.
-
-* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks.
- It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of
- the updated_at column. It should not be called on new records.
- Example:
-
- User.first.update_column(:name, "sebastian") # => true
-
- *Sebastian Martinez*
-
-* Associations with a :through option can now use *any* association as the
- through or source association, including other associations which have a
- :through option and has_and_belongs_to_many associations
-
- *Jon Leighton*
-
-* The configuration for the current database connection is now accessible via
- ActiveRecord::Base.connection_config. *fxn*
-
-* limits and offsets are removed from COUNT queries unless both are supplied.
- For example:
-
- People.limit(1).count # => 'SELECT COUNT(*) FROM people'
- People.offset(1).count # => 'SELECT COUNT(*) FROM people'
- People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
+ *Rafael Mendonça França*
- *lighthouse #6262*
+* Removes the deprecation of `update_attribute`. *fxn*
-* ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class
- (and subclasses) which are responsible for operating on associations, and then a separate,
- thin wrapper called CollectionProxy, which proxies collection associations.
+* Reverted the deprecation of `composed_of`. *Rafael Mendonça França*
- This prevents namespace pollution, separates concerns, and will allow further refactorings.
+* Reverted the deprecation of `*_sql` association options. They will
+ be deprecated in 4.0 instead. *Jon Leighton*
- Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return
- the associated record or nil. This means that you should not use undocumented methods such
- as bob.mother.create - use bob.create_mother instead.
+* Do not eager load AR session store. ActiveRecord::SessionStore depends on the abstract store
+ in Action Pack. Eager loading this class would break client code that eager loads Active Record
+ standalone.
+ Fixes #7160
- *Jon Leighton*
+ *Xavier Noria*
-* Make has_many :through associations work correctly when you build a record and then save it. This
- requires you to set the :inverse_of option on the source reflection on the join model, like so:
+* Do not set RAILS_ENV to "development" when using `db:test:prepare` and related rake tasks.
+ This was causing the truncation of the development database data when using RSpec.
+ Fixes #7175.
- class Post < ActiveRecord::Base
- has_many :taggings
- has_many :tags, :through => :taggings
- end
+ *Rafael Mendonça França*
- class Tagging < ActiveRecord::Base
- belongs_to :post
- belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set!
- end
- class Tag < ActiveRecord::Base
- has_many :taggings
- has_many :posts, :through => :taggings
- end
+## Rails 3.2.7 (Jul 26, 2012) ##
- post = Post.first
- tag = post.tags.build :name => "ruby"
- tag.save # will save a Taggable linking to the post
+* `:finder_sql` and `:counter_sql` options on collection associations
+ are deprecated. Please transition to using scopes.
*Jon Leighton*
-* Support the :dependent option on has_many :through associations. For historical and practical
- reasons, :delete_all is the default deletion strategy employed by association.delete(*records),
- despite the fact that the default strategy is :nullify for regular has_many. Also, this only
- works at all if the source reflection is a belongs_to. For other situations, you should directly
- modify the through association.
+* `:insert_sql` and `:delete_sql` options on `has_and_belongs_to_many`
+ associations are deprecated. Please transition to using `has_many
+ :through`
*Jon Leighton*
-* Changed the behaviour of association.destroy for has_and_belongs_to_many and has_many :through.
- From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link',
- not (necessarily) 'get rid of the associated records'.
-
- Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It
- would not delete any records in the join table. Now, it deletes the records in the join table.
-
- Previously, has_many_through.destroy(*records) would destroy the records themselves, and the
- records in the join table. [Note: This has not always been the case; previous version of Rails
- only deleted the records themselves.] Now, it destroys only the records in the join table.
+* `composed_of` has been deprecated. You'll have to write your own accessor
+ and mutator methods if you'd like to use value objects to represent some
+ portion of your models.
- Note that this change is backwards-incompatible to an extent, but there is unfortunately no
- way to 'deprecate' it before changing it. The change is being made in order to have
- consistency as to the meaning of 'destroy' or 'delete' across the different types of associations.
+ *Steve Klabnik*
- If you wish to destroy the records themselves, you can do records.association.each(&:destroy)
+* `update_attribute` has been deprecated. Use `update_column` if
+ you want to bypass mass-assignment protection, validations, callbacks,
+ and touching of updated_at. Otherwise please use `update_attributes`.
- *Jon Leighton*
+ *Steve Klabnik*
-* Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. *Pratik Naik*
- Example:
+## Rails 3.2.6 (Jun 12, 2012) ##
- change_table(:users, :bulk => true) do |t|
- t.string :company_name
- t.change :birthdate, :datetime
- end
+* protect against the nesting of hashes changing the
+ table context in the next call to build_from_hash. This fix
+ covers this case as well.
- This will now result in:
+ CVE-2012-2695
- ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL
+* Revert earlier 'perf fix' (see 3.2.4 changelog / GH #6289). This
+ change introduced a regression (GH #6609). assoc.clear and
+ assoc.delete_all have loaded the association before doing the delete
+ since at least Rails 2.3. Doing the delete without loading the
+ records means that the `before_remove` and `after_remove` callbacks do
+ not get invoked. Therefore, this change was less a fix a more an
+ optimisation, which should only have gone into master.
-* Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been
- documented as deprecated behaviour since April 2006. Please use has_many :through instead.
*Jon Leighton*
-* Added a create_association! method for has_one and belongs_to associations. *Jon Leighton*
-
-* Migration files generated from model and constructive migration generators
- (for example, add_name_to_users) use the reversible migration's `change`
- method instead of the ordinary `up` and `down` methods. *Prem Sichanugrist*
-
-* Removed support for interpolating string SQL conditions on associations. Instead, you should
- use a proc, like so:
-
- Before:
-
- has_many :things, :conditions => 'foo = #{bar}'
-
- After:
-
- has_many :things, :conditions => proc { "foo = #{bar}" }
-
- Inside the proc, 'self' is the object which is the owner of the association, unless you are
- eager loading the association, in which case 'self' is the class which the association is within.
-
- You can have any "normal" conditions inside the proc, so the following will work too:
-
- has_many :things, :conditions => proc { ["foo = ?", bar] }
-
- Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call
- 'record' to get the record being inserted or deleted. This is now passed as an argument to
- the proc.
-
-* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example:
-
- # Schema: User(name:string, password_digest:string, password_salt:string)
- class User < ActiveRecord::Base
- has_secure_password
- end
-
- user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
- user.save # => false, password required
- user.password = "mUc3m00RsqyRe"
- user.save # => false, confirmation doesn't match
- user.password_confirmation = "mUc3m00RsqyRe"
- user.save # => true
- user.authenticate("notright") # => false
- user.authenticate("mUc3m00RsqyRe") # => user
- User.find_by_name("david").try(:authenticate, "notright") # => nil
- User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
-
-
-* When a model is generated add_index is added by default for belongs_to or references columns
-
- rails g model post user:belongs_to will generate the following:
-
- class CreatePosts < ActiveRecord::Migration
- def up
- create_table :posts do |t|
- t.belongs_to :user
- t.timestamps
- end
-
- add_index :posts, :user_id
- end
-
- def down
- drop_table :posts
- end
- end
-
- *Santiago Pastorino*
-
-* Setting the id of a belongs_to object will update the reference to the
- object. [#2989 state:resolved]
-* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed
- to closer match normal Ruby dup and clone semantics.
-* Calling ActiveRecord::Base#clone will result in a shallow copy of the record,
- including copying the frozen state. No callbacks will be called.
-* Calling ActiveRecord::Base#dup will duplicate the record, including calling
- after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.
-* Migrations can be defined as reversible, meaning that the migration system
- will figure out how to reverse your migration. To use reversible migrations, just define the "change" method. For example:
- class MyMigration < ActiveRecord::Migration
- def change
- create_table(:horses) do
- t.column :content, :text
- t.column :remind_at, :datetime
- end
- end
- end
-
- Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define 'up' and 'down' in your migration. If you define something in `change` that cannot be reversed, an IrreversibleMigration exception will be raised when going down.
-* Migrations should use instance methods rather than class methods:
- class FooMigration < ActiveRecord::Migration
- def up
- ...
- end
- end
-
- *Aaron Patterson*
-
-* has_one maintains the association with separate after_create/after_update instead
- of a single after_save. *fxn*
-
-* The following code:
-
- Model.limit(10).scoping { Model.count }
-
- now generates the following SQL:
-
- SELECT COUNT(*) FROM models LIMIT 10
-
- This may not return what you want. Instead, you may with to do something
- like this:
-
- Model.limit(10).scoping { Model.all.size }
-
- *Aaron Patterson*
-
-
-## Rails 3.0.12 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.0.11 (November 18, 2011) ##
-
-* Exceptions from database adapters should not lose their backtrace.
-
-* Backport "ActiveRecord::Persistence#touch should not use default_scope" (GH #1519)
-
-* Psych errors with poor yaml formatting are proxied. Fixes GH #2645 and
- GH #2731
-
-* Fix ActiveRecord#exists? when passsed a nil value
-
-
-## Rails 3.0.10 (August 16, 2011) ##
-
-* Magic encoding comment added to schema.rb files
-
-* schema.rb is written as UTF-8 by default.
-
-* Ensuring an established connection when running `rake db:schema:dump`
-
-* Association conditions will not clobber join conditions.
-* Destroying a record will destroy the HABTM record before destroying itself.
- GH #402.
-
-* Make `ActiveRecord::Batches#find_each` to not return `self`.
-
-* Update `table_exists?` in PG to to always use current search_path or schema if explictly set.
-
-
-## Rails 3.0.9 (June 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.8 (June 7, 2011) ##
-
-* Fix various problems with using :primary_key and :foreign_key options in conjunction with
- :through associations. [Jon Leighton]
-
-* Correctly handle inner joins on polymorphic relationships.
-
-* Fixed infinity and negative infinity cases in PG date columns.
-
-* Creating records with invalid associations via `create` or `save` will no longer raise exceptions.
-
-
-## Rails 3.0.7 (April 18, 2011) ##
-
-* Destroying records via nested attributes works independent of reject_if LH #6006 *Durran Jordan*
-
-* Delegate any? and many? to Model.scoped for consistency *Andrew White*
+## Rails 3.2.5 (Jun 1, 2012) ##
-* Quote the ORDER BY clause in batched finds - fixes #6620 *Andrew White*
+* Restore behavior of Active Record 3.2.3 scopes.
+ A series of commits relating to preloading and scopes caused a regression.
-* Change exists? so records are not instantiated - fixes #6127. This prevents after_find
- and after_initialize callbacks being triggered when checking for record existence.
*Andrew White*
-* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we
- cache type-casted values when the column returned from the db contains non-standard chars.
- *Jon Leighton*
-
-* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8
- related to read_attribute method *Stian Grytøyr*
-
-
-## Rails 3.0.6 (April 5, 2011) ##
-
-* Un-deprecate reorder method *Sebastian Martinez*
-
-* Extensions are applied when calling +except+ or +only+ on relations.
- Thanks to Iain Hecker.
-
-* Schemas set in set_table_name are respected by the mysql adapter. LH #5322
-
-* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded.
- LH #5829
-
-* Reapply extensions when using except and only. Thanks Iain Hecker.
-
-* Binary data is escaped when being inserted to SQLite3 Databases. Thanks
- Naruse!
-
-
-## Rails 3.0.5 (February 26, 2011) ##
-
-* Model.where(:column => 1).where(:column => 2) will always produce an AND
- query.
- *Aaron Patterson*
-
-* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'.
-
- Instead, you should use a proc, like so:
-
- Before:
-
- has_many :things, :conditions => 'foo = #{bar}'
-
- After:
-
- has_many :things, :conditions => proc { "foo = #{bar}" }
-
- Inside the proc, 'self' is the object which is the owner of the association, unless you are
- eager loading the association, in which case 'self' is the class which the association is within.
-
- You can have any "normal" conditions inside the proc, so the following will work too:
-
- has_many :things, :conditions => proc { ["foo = ?", bar] }
-
- Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call
- 'record' to get the record being inserted or deleted. This is now passed as an argument to
- the proc.
-
- *Jon Leighton*
-
-
-## Rails 3.0.4 (February 8, 2011) ##
-
-* Added deprecation warning for has_and_belongs_to_many associations where the join table has
- additional attributes other than the keys. Access to these attributes is removed in 3.1.
- Please use has_many :through instead. *Jon Leighton*
-
-
-## Rails 3.0.3 (November 16, 2010) ##
-
-* Support find by class like this: Post.where(:name => Post)
-
-
-## Rails 3.0.2 (November 15, 2010) ##
-
-* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) *Aaron Patterson*
-
-* reorder is deprecated in favor of except(:order).order(...) *Santiago Pastorino*
-
-* except is now AR public API
-
- Model.order('name').except(:order).order('salary')
-
- generates:
-
- SELECT * FROM models ORDER BY salary
-
- *Santiago Pastorino*
-
-* The following code:
-
- Model.limit(10).scoping { Model.count }
-
- now generates the following SQL:
-
- SELECT COUNT(*) FROM models LIMIT 10
-
- This may not return what you want. Instead, you may with to do something
- like this:
-
- Model.limit(10).scoping { Model.all.size }
-
- *Aaron Patterson*
-
-
-## Rails 3.0.1 (October 15, 2010) ##
-
-* Introduce a fix for CVE-2010-3993
-
-
-## Rails 3.0.0 (August 29, 2010) ##
-
-* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope *José Valim*
-
-* New rake task, db:migrate:status, displays status of migrations #4947 *Kevin Skoglund*
-
-* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten *Santiago Pastorino*
-
-* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 *Aaron Patterson*
-
-* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 *Andrew Bloomgarden, Andrew White*
-
-* Add index length support for MySQL. #1852 *Emili Parreno, Pratik Naik*
-
- Example:
-
- add_index(:accounts, :name, :name => 'by_name', :length => 10)
- => CREATE INDEX by_name ON accounts(name(10))
-
- add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15})
- => CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
-* find_or_create_by_attr(value, ...) works when attr is protected. #4457 *Santiago Pastorino, Marc-André Lafortune*
-
-* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 *Brian Durand*
-
-* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). *José Valim*
-
-* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 *Curtis Hawthorne*
-
-* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. *Jeremy Kemper*
-
-* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 *Mislav Marohnić*
-
-* Add Relation extensions. *Pratik Naik*
-
- users = User.where(:admin => true).extending(User::AdminPowers)
-
- latest_users = User.order('created_at DESC') do
- def posts_count
- Post.count(:user_id => to_a.map(&:id))
- end
- end
-
-* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 *Andrew White*
-
-* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development *DHH*
-
-* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 *Jack Christensen*
-
-* Allow relations to be used as scope.
-
- class Item
- scope :red, where(:colour => 'red')
- end
-
- Item.red.limit(10) # Ten red items
-
-* Rename named_scope to scope. *Pratik Naik*
-
-* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default *DHH*
-
-* Add Relation#except. *Pratik Naik*
-
- one_red_item = Item.where(:colour => 'red').limit(1)
- all_items = one_red_item.except(:where, :limit)
-
-* Add Relation#delete_all. *Pratik Naik*
-
- Item.where(:colour => 'red').delete_all
-
-* Add Model.having and Relation#having. *Pratik Naik*
-
- Developer.group("salary").having("sum(salary) > 10000").select("salary")
-
-* Add Relation#count. *Pratik Naik*
-
- legends = People.where("age > 100")
- legends.count
- legends.count(:age, :distinct => true)
- legends.select('id').count
-
-* Add Model.readonly and association_collection#readonly finder method. *Pratik Naik*
-
- Post.readonly.to_a # Load all posts in readonly mode
- @user.items.readonly(false).to_a # Load all the user items in writable mode
-
-* Add .lock finder method *Pratik Naik*
-
- User.lock.where(:name => 'lifo').to_a
-
- old_items = Item.where("age > 100")
- old_items.lock.each {|i| .. }
-
-* Add Model.from and association_collection#from finder methods *Pratik Naik*
-
- user = User.scoped
- user.select('*').from('users, items')
-
-* Add relation.destroy_all *Pratik Naik*
-
- old_items = Item.where("age > 100")
- old_items.destroy_all
-
-* Add relation.exists? *Pratik Naik*
-
- red_items = Item.where(:colours => 'red')
- red_items.exists?
- red_items.exists?(1)
-
-* Add find(ids) to relations. *Pratik Naik*
-
- old_users = User.order("age DESC")
- old_users.find(1)
- old_users.find(1, 2, 3)
-
-* Add new finder methods to association collection. *Pratik Naik*
-
- class User < ActiveRecord::Base
- has_many :items
- end
-
- user = User.first
- user.items.where(:items => {:colour => 'red'})
- user.items.select('items.id')
-
-* Add relation.reload to force reloading the records. *Pratik Naik*
-
- topics = Topic.scoped
- topics.to_a # force load
- topics.first # returns a cached record
- topics.reload
- topics.first # Fetches a new record from the database
-
-* Rename Model.conditions and relation.conditions to .where. *Pratik Naik*
-
- Before :
- User.conditions(:name => 'lifo')
- User.select('id').conditions(["age > ?", 21])
-
- Now :
- User.where(:name => 'lifo')
- User.select('id').where(["age > ?", 21])
-
-* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. *Pratik Naik*
-
- Examples :
-
- posts = Post.select('id).order('name') # Returns a lazy relation
- posts.each {|p| puts p.id } # Fires "select id from posts order by name"
-
-* Model.scoped now returns a relation if invoked without any arguments. *Pratik Naik*
-
- Example :
-
- posts = Post.scoped
- posts.size # Fires "select count(*) from posts" and returns the count
- posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
-* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 *Murray Steele*
-
- # post.comments sets each comment's post without needing to :include
- class Post < ActiveRecord::Base
- has_many :comments, :inverse_of => :post
- end
-
-* MySQL: add_ and change_column support positioning. #3286 *Ben Marini*
-
-* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 *Mike Breen, Gabe da Silveira*
-
-* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git *Pratik Naik*
-
-* PostgreSQL: XML datatype support. #1874 *Leonardo Borges*
-
-* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 *Geoff Buesing*
-
-* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 *Paul Hinze, Jeremy Kemper*
-
-* Added :primary_key option to belongs_to associations. #765 *Szymon Nowak, Philip Hallstrom, Noel Rocha*
- # employees.company_name references companies.name
- Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name'
-
-* Implement #many? for NamedScope and AssociationCollection using #size. #1500 *Chris Kampmeier*
-
-* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed *DHH*
-
-* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time *DHH*
-
-
-## 2.3.2 Final (March 15, 2009) ##
-
-* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing *DHH/Jamis Buck*
-
-* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 *Scott Taylor*
-
-* Add Support for updating deeply nested models from a single form. #1202 *Eloy Duran*
-
- class Book < ActiveRecord::Base
- has_one :author
- has_many :pages
-
- accepts_nested_attributes_for :author, :pages
- end
-
-* Make after_save callbacks fire only if the record was successfully saved. #1735 *Michael Lovitt*
-
- Previously the callbacks would fire if a before_save cancelled saving.
-
-* Support nested transactions using database savepoints. #383 *Jonathan Viney, Hongli Lai*
-
-* Added dynamic scopes ala dynamic finders #1648 *Yaroslav Markin*
-
-* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 *Yaroslav Markin*
-
-* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 *Akira Matsuda*
-
-* Add :having as a key to find and the relevant associations. *Emilio Tagua*
-
-* Added default_scope to Base #1381 [Paweł Kondzior]. Example:
-
- class Person < ActiveRecord::Base
- default_scope :order => 'last_name, first_name'
- end
-
- class Company < ActiveRecord::Base
- has_many :people
- end
-
- Person.all # => Person.find(:all, :order => 'last_name, first_name')
- Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 })
-
-
-## 2.2.1 RC2 (November 14th, 2008) ##
-
-* Ensure indices don't flip order in schema.rb #1266 *Jordi Bunster*
-
-* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 *Andreas Korth*
-
-
-## 2.2.0 RC1 (October 24th, 2008) ##
-
-* Skip collection ids reader optimization if using :finder_sql *Jeremy Kemper*
-
-* Add Model#delete instance method, similar to Model.delete class method. #1086 *Hongli Lai (Phusion)*
-
-* MySQL: cope with quirky default values for not-null text columns. #1043 *Frederick Cheung*
-
-* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] *Geoff Buesing*
-
-* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] *Emilio Tagua*
-
-* Added find_last_by dynamic finder #762 *Emilio Tagua*
-
-* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 *Hongli Lai (Phusion)*
-
-* Changed benchmarks to be reported in milliseconds *David Heinemeier Hansson*
-
-* Connection pooling. #936 *Nick Sieger*
-
-* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 *Andrew White*
-
-* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 *Xavier Noria*
-
-* Transactional migrations for databases which support them. #834 *divoxx, Adam Wiggins, Tarmo Tänav*
-
-* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. *Andrew Stone, Nik Wakelin*
-
-* change_column_default preserves the not-null constraint. #617 *Tarmo Tänav*
-
-* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) *#334*
-
-* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example :
-
- \# Ensure essay contains at least 100 words.
- validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
-
-* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example:
-
- User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } }
- Item.first :conditions => { :items => { :color => 'red' } }
-
-* Always treat integer :limit as byte length. #420 *Tarmo Tänav*
-
-* Partial updates don't update lock_version if nothing changed. #426 *Daniel Morrison*
-
-* Fix column collision with named_scope and :joins. #46 *Duncan Beevers, Mark Catley*
-
-* db:migrate:down and :up update schema_migrations. #369 *Michael Raidel, RaceCondition*
-
-* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. *Tarmo Tänav*
-
-* MySQL: rename_column preserves column defaults. #466 *Diego Algorta*
-
-* Add :from option to calculations. #397 *Ben Munat*
-
-* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. *Jan De Poorter*
-
-* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. *Jeremy Kemper*
-
-* Added SQL escaping for :limit and :offset in MySQL *Jonathan Wiess*
-
-
-## 2.1.0 (May 31st, 2008) ##
-
-* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. *Rick Olson*
-
-* Add first/last methods to associations/named_scope. Resolved #226. *Ryan Bates*
-
-* Added SQL escaping for :limit and :offset #288 *Aaron Bedra, Steven Bristol, Jonathan Wiess*
-
-* Added first/last methods to associations/named_scope. Resolved #226. *Ryan Bates*
-
-* Ensure hm:t preloading honours reflection options. Resolves #137. *Frederick Cheung*
-
-* Added protection against duplicate migration names (Aslak Hellesøy) *#112*
-
-* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true *Geoff Buesing*
-
-* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. *Scott Fleckenstein, Geoff Buesing*
-
-* Added change_table for migrations (Jeff Dean) [#71]. Example:
-
- change_table :videos do |t|
- t.timestamps # adds created_at, updated_at
- t.belongs_to :goat # adds goat_id integer
- t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit
- t.remove :name, :email # removes the name and email columns
- end
-
-* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) *#85*
-
-* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) *#39*
-
-* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) *#67*
-
-* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] *#26*
-
-* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL *David Heinemeier Hansson*
-
-* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. *Rick Olson*
-
-* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 *Jordi Bunster*
-
-* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 *Kamal Fariz Mahyuddin*
-
-* Ensure that respond_to? considers dynamic finder methods. Closes #11538. *James Mead*
-
-* Ensure that save on parent object fails for invalid has_one association. Closes #10518. *Pratik Naik*
-
-* Remove duplicate code from associations. *Pratik Naik*
-
-* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 *Ruy Asan*
-
-* Ensure HABTM#create and HABTM#build do not load entire association. *Pratik Naik*
-
-* Improve documentation. *Xavier Noria, Jack Danger Canty, leethal*
-
-* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} *Rick Olson*
-
- Post.find(1).to_json # => {"title": ...}
- config.active_record.include_root_in_json = true
- Post.find(1).to_json # => {"post": {"title": ...}}
-
-* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). *stopdropandrew*
-
-* PostgreSQL: create_ and drop_database support. #9042 *ez, pedz, Nick Sieger*
-
-* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. *Nik Wakelin, cavalle*
-
-* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. *Jeremy Kemper*
-
-* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled *Geoff Buesing*
-
-* Fixed that validates_size_of :within works in associations #11295, #10019 *cavalle*
-
-* Track changes to unsaved attributes. *Jeremy Kemper*
-
-* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 *John Barnette*
-
-* Fixed that has_many :through would ignore the hash conditions #11447 *Emilio Tagua*
-
-* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 *cavalle*
-
-* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 *cavalle*
-
-* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 *Jack Danger Canty*
-
-* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
-
-* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 *Emilio Tagua*
-
-* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 *nkallen, Chris O'Sullivan*
-
-* Merge the has_finder gem, renamed as 'named_scope'. #11404 *nkallen*
-
- class Article < ActiveRecord::Base
- named_scope :published, :conditions => {:published => true}
- named_scope :popular, :conditions => ...
- end
-
- Article.published.paginate(:page => 1)
- Article.published.popular.count
- Article.popular.find(:first)
- Article.popular.find(:all, :conditions => {...})
-
- See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries
-
-* Add has_one :through support. #4756 *Chris O'Sullivan*
-
-* Migrations: create_table supports primary_key_prefix_type. #10314 *student, Chris O'Sullivan*
-
-* Added logging for dependency load errors with fixtures #11056 *stuthulhu*
-
-* Time zone aware attributes use Time#in_time_zone *Geoff Buesing*
-
-* Fixed that scoped joins would not always be respected #6821 *Theory/Jack Danger Canty*
-
-* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 *cavalle*
-
-* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 *jramirez*
-
-* Added ActiveRecord::Base.find(:last) #11338 *Emilio Tagua*
-
-* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition *Geoff Buesing*
-
-* Add :readonly option to HasManyThrough associations. #11156 *Emilio Tagua*
-
-* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 *dasil003*
-
-* Perf fix: Avoid the use of named block arguments. Closes #11109 *adymo*
-
-* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 *jdavis*
-
-* Ensure association preloading doesn't break when an association returns nil. ##11145 *GMFlash*
-
-* Make dynamic finders respect the :include on HasManyThrough associations. #10998. *cpytel*
-
-* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability *Geoff Buesing*
-
-* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback *Geoff Buesing*
-
-* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 *adymo*
-
-* Optimise the BigDecimal conversion code. #11110 *adymo*
-
-* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 *Emilio Tagua*
-
-* Multiparameter attributes for time columns fail over to DateTime when out of range of Time *Geoff Buesing*
-
-* Base#instantiate_time_object uses Time.zone.local() *Geoff Buesing*
-
-* Add timezone-aware attribute readers and writers. #10982 *Geoff Buesing*
-
-* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 *Rick Olson*
-
-* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 *Xavier Noria*
-
-* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 *mdeiters*
-
-* belongs_to supports :dependent => :destroy and :delete. #10592 *Jonathan Viney*
-
-* Introduce preload query strategy for eager :includes. #9640 *Frederick Cheung, Aliaksey Kandratsenka, codafoo*
-
-* Support aggregations in finder conditions. #10572 *Ryan Kinderman*
-
-* Organize and clean up the Active Record test suite. #10742 *John Barnette*
-
-* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 *john.andrews*
-
-* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 *railsjitsu*
-
-* Fixtures: removed support for the ancient pre-YAML file format. #10736 *John Barnette*
-
-* More thoroughly quote table names. #10698 *dimdenis, lotswholetime, Jeremy Kemper*
-
-* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 *Brendan Ribera*
-
-* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries *David Heinemeier Hansson*
-
-* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. *JEG2*
-
-* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 *Sam*
-
-* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 *jamesh, Frederick Cheung, protocool*
-
-* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 *stopdropandrew, canadaduane*
-
-* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 *Jonathan Viney*
-
-* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 *Brandon Keepers*
-
-* Ruby 1.9 compatibility. #10655 *Jeremy Kemper, Dirkjan Bussink*
-
-
-## 2.0.2 (December 16th, 2007) ##
-
-* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 *Rick Olson*
-
-* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 *brynary*
-
-* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 *Josh Susser*
-
-* Ensure that the :uniq option for has_many :through associations retains the order. #10463 *remvee*
-
-* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 *Michael Klishin*
-
-* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 *Michael Klishin*
-
-
-## 2.0.1 (December 7th, 2007) ##
-
-* Removed query cache rescue as it could cause code to be run twice (closes #10408) *David Heinemeier Hansson*
-
-
-## 2.0.0 (December 6th, 2007) ##
-
-* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ *Geoff Buesing*
-
-* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) *David Heinemeier Hansson*
-
-* Fixed that the truncation of strings longer than 50 chars should use inspect
- so newlines etc are escaped #10385 [Norbert Crombach]
-* Fixed that habtm associations should be able to set :select as part of their definition and have that honored *David Heinemeier Hansson*
-
-* Document how the :include option can be used in Calculations::calculate. Closes #7446 *adamwiggins, ultimoamore*
-
-* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 *johnjosephbachir*
-
-* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 *adamwiggins, mikong*
-
-* More complete documentation for find_by_sql. Closes #7912 *fearoffish*
-
-* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example:
-
- render :partial => @client.becomes(Company) # renders companies/company instead of clients/client
-
-* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 *Cheah Chu Yeow*
-
-* Fix documentation typo introduced in [8250]. Closes #10339 *Henrik N*
-
-* Foxy fixtures: support single-table inheritance. #10234 *tom*
-
-* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 *lotswholetime*
-
-* Make the record_timestamps class-inheritable so it can be set per model. #10004 *tmacedo*
-
-* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 *ambethia*
-
-* DateTimes use Ruby's default calendar reform setting. #10201 *Geoff Buesing*
-
-* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 *Patrick Joyce, Rick Olson, Jack Danger Canty*
-
-* Add 'foxy' support for fixtures of polymorphic associations. #10183 *John Barnette, David Lowenfels*
-
-* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 *devrieda, Mike Naberezny*
-
-* attr_readonly behaves well with optimistic locking. #10188 *Nick Bugajski*
-
-* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 *Jonathan del Strother*
-
-* Change plings to the more conventional quotes in the documentation. Closes #10104 *Jack Danger Canty*
-
-* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 *Jack Danger Canty*
-
-* Ensure that column names are quoted. Closes #10134 *wesley.moxam*
-
-* Smattering of grammatical fixes to documentation. Closes #10083 *Bob Silva*
-
-* Enhance explanation with more examples for attr_accessible macro. Closes #8095 *fearoffish, Marcel Molina Jr.*
-
-* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 *Pratik Naik*
-
-* Explain semantics of having several different AR instances in a transaction block. Closes #9036 *jacobat, Marcel Molina Jr.*
-
-* Update Schema documentation to use updated sexy migration notation. Closes #10086 *Sam Granieri*
-
-* Make fixtures work with the new test subclasses. *Tarmo Tänav, Michael Koziarski*
-
-* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 *RubyRedRick*
- # Find users with an avatar
- User.find(:all, :joins => :avatar)
-
- # Find posts with a high-rated comment.
- Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3')
-
-* Associations: speedup duplicate record check. #10011 *Pratik Naik*
-
-* Make sure that << works on has_many associations on unsaved records. Closes #9989 *Josh Susser*
-
-* Allow association redefinition in subclasses. #9346 *wildchild*
-
-* Fix has_many :through delete with custom foreign keys. #6466 *naffis*
-
-* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README)
- - stable, autogenerated IDs
- - specify associations (belongs_to, has_one, has_many) by label, not ID
- - specify HABTM associations as inline lists
- - autofill timestamp columns
- - support YAML defaults
- - fixture label interpolation
- Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 *John Barnette*
-
-* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 *boone, rmm5t*
-
-* Update add_index documentation to use new options api. Closes #9787 *Kamal Fariz Mahyuddin*
-
-* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 *krishna*
-
-* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 *sur*
-
-* Limited eager loading no longer ignores scoped :order. Closes #9561 *Jack Danger Canty, Josh Peek*
-
-* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 *brandon, Chris Cruft*
-
-* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 *Chris Cruft*
-
-* Ensure that mysql quotes table names with database names correctly. Closes #9911 *crayz*
-
- "foo.bar" => "`foo`.`bar`"
-
-* Complete the assimilation of Sexy Migrations from ErrFree *Chris Wanstrath, PJ Hyett*
- http://errtheblog.com/post/2381
-
-* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 *Jack Danger Canty*
-
-* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 *Bryan Helmkamp*
-
-* Refactor association create and build so before & after callbacks behave consistently. #8854 *Pratik Naik, mortent*
-
-* Quote table names. Defaults to column quoting. #4593 *Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper*
-
-* Alias association #build to #new so it behaves predictably. #8787 *Pratik Naik*
-
-* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 *saimonmoore, Rick Olson*
-
-* Observers can observe model names as symbols properly now. Closes #9869 *queso*
-
-* find_and_(initialize|create)_by methods can now properly initialize protected attributes *Tobias Lütke*
-
-* belongs_to infers the foreign key from the association name instead of from the class name. *Jeremy Kemper*
-
-* PostgreSQL: support multiline default values. #7533 *Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav*
-
-* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 *Jonathan Viney, Tarmo Tänav*
-
-* validates_uniqueness_of behaves well with abstract superclasses and
- single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat]
-* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 *Henrik N*
-
-* Speedup database date/time parsing. *Jeremy Kemper, Tarmo Tänav*
-
-* Fix calling .clear on a has_many :dependent=>:delete_all association. *Tarmo Tänav*
-
-* Allow change_column to set NOT NULL in the PostgreSQL adapter *Tarmo Tänav*
-
-* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. *Rick Olson*
-
-* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. *Rick Olson*
-
-* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. *Jeremy Kemper, Derrick Spell*
-
-
-## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.14.2 - 1.15.3 ##
-
-* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 *Dan Manges*
-
- class Comment < ActiveRecord::Base
- # Automatically sets Article#comments_count as readonly.
- belongs_to :article, :counter_cache => :comments_count
- end
-
- class Article < ActiveRecord::Base
- attr_readonly :approved_comments_count
- end
-
-* Make size for has_many :through use counter cache if it exists. Closes #9734 *Xavier Shay*
-
-* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. *Jeremy Kemper*
-
-* Extract Oracle, SQLServer, and Sybase adapters into gems. *Jeremy Kemper*
-
-* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 *Frederick Cheung*
-
-* Correctly quote id list for limited eager loading. #7482 *tmacedo*
-
-* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 *valeksenko*
-
-* Fixed rename_column for SQLite when using symbols for the column names #8616 *drodriguez*
-
-* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 *Robby Russell, Tarmo Tänav*
-
-* Added ActiveRecord::Base#to_json/from_json *David Heinemeier Hansson, Cheah Chu Yeow*
-
-* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example:
-
- xml = "<person><name>David</name></person>"
- Person.new.from_xml(xml).name # => "David"
-
-* Define dynamic finders as real methods after first usage. *bscofield*
-
-* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. *Jeremy Kemper*
-
-* Associations macros accept extension blocks alongside modules. #9346 *Josh Peek*
-
-* Speed up and simplify query caching. *Jeremy Kemper*
-
-* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 *Michael Schuerig*
-
-* Eager loading respects explicit :joins. #9496 *dasil003*
-
-* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 *Jeremy Kemper*
-
-* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. *Jeremy Kemper*
-
-* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 *TimoMihaljov/brandon*
-
-* Fix association writer with :dependent => :nullify. #7314 *Jonathan Viney*
-
-* OpenBase: update for new lib and latest Rails. Support migrations. #8748 *dcsesq*
-
-* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 *Pratik Naik*
-
-* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 *Josh Peek*
-
-* Moved acts_as_list into a plugin of the same name on the official Rails svn. *Josh Peek*
-
-* Explicitly require active_record/query_cache before using it. *Jeremy Kemper*
-
-* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. *Rick Olson, marclove*
-
-* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. *Jeremy Kemper*
-
-* Fixed that eager loading queries and with_scope should respect the :group option *David Heinemeier Hansson*
-
-* Improve performance and functionality of the postgresql adapter. Closes #8049 *roderickvd*
-
- For more information see: http://dev.rubyonrails.org/ticket/8049
-
-* Don't clobber includes passed to has_many.count *Jack Danger Canty*
-
-* Make sure has_many uses :include when counting *Jack Danger Canty*
-
-* Change the implementation of ActiveRecord's attribute reader and writer methods *Michael Koziarski*
- - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns. - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns. - Move method definition to the class, instead of the instance - Always generate the readers, writers and predicate methods.
-* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. *Rick Olson*
-
- \# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik]
-* Added :unless clause to validations #8003 [monki]. Example:
-
- def using_open_id?
- !identity_url.blank?
- end
-
- validates_presence_of :identity_url, :if => using_open_id?
- validates_presence_of :username, :unless => using_open_id?
- validates_presence_of :password, :unless => using_open_id?
-
-* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 *Pratik Naik*
-
-* Fix and properly document/test count(column_name) usage. Closes #8999 *Pratik Naik*
-
-* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 *Pratik Naik*
-
-* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 *Josh Susser*
-
- OLD
- belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id
-
- NEW
- belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id
-
-* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 *Pratik Naik*
-
-* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 *Pratik Naik*
-
-* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 *dasil003*
-
-* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, *Manfred Stienstra, jwilger*
-
-* Define collection singular ids method for has_many :through associations. #8763 *Pratik Naik*
-
-* Array attribute conditions work with proxied association collections. #8318 *Kamal Fariz Mahyuddin, theamazingrando*
-
-* Fix polymorphic has_one associations declared in an abstract class. #8638 *Pratik Naik, Dax Huiberts*
-
-* Fixed validates_associated should not stop on the first error. #4276 *mrj, Manfred Stienstra, Josh Peek*
-
-* Rollback if commit raises an exception. #8642 *kik, Jeremy Kemper*
-
-* Update tests' use of fixtures for the new collections api. #8726 *Kamal Fariz Mahyuddin*
-
-* Save associated records only if the association is already loaded. #8713 *Blaine*
-
-* MySQL: fix show_variable. #8448 *matt, Jeremy Kemper*
-
-* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 *Michael Schuerig*
-
-* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 *technomancy, Josh Peek*
-
-* Calculations support non-numeric foreign keys. #8154 *Kamal Fariz Mahyuddin*
-
-* with_scope is protected. #8524 *Josh Peek*
-
-* Quickref for association methods. #7723 *marclove, Mindsweeper*
-
-* Calculations: return nil average instead of 0 when there are no rows to average. #8298 *davidw*
-
-* acts_as_nested_set: direct_children is sorted correctly. #4761 *Josh Peek, rails@33lc0.net*
-
-* Raise an exception if both attr_protected and attr_accessible are declared. #8507 *stellsmi*
-
-* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 *marclove, lorenjohnson*
-
-* Allow nil serialized attributes with a set class constraint. #7293 *sandofsky*
-
-* Oracle: support binary fixtures. #7987 *Michael Schoen*
-
-* Fixtures: pull fixture insertion into the database adapters. #7987 *Michael Schoen*
-
-* Announce migration versions as they're performed. *Jeremy Kemper*
-
-* find gracefully copes with blank :conditions. #7599 *Dan Manges, johnnyb*
-
-* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 *Bob Silva, Dan Kubb, Josh Peek*
-
-* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 *matt*
-
-* Find with a list of ids supports limit/offset. #8437 *hrudududu*
-
-* Optimistic locking: revert the lock version when an update fails. #7840 *plang*
-
-* Migrations: add_column supports custom column types. #7742 *jsgarvin, Theory*
-
-* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. *Jeremy Kemper*
-
-* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 *Jack Danger Canty, Josh Peek, Rick Olson*
-
-* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 *mmangino@elevatedrails.com*
-
-* Fix column type detection while loading fixtures. Closes #7987 *roderickvd*
-
-* Document deep eager includes. #6267 *Josh Susser, Dan Manges*
-
-* Document warning that associations names shouldn't be reserved words. #4378 *murphy@cYcnus.de, Josh Susser*
-
-* Sanitize Base#inspect. #8392, #8623 *Nik Wakelin, jnoon*
-
-* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. *Michael Koziarski*
-
-* Oracle: extract column length for CHAR also. #7866 *ymendel*
-
-* Document :allow_nil option for validates_acceptance_of since it defaults to true. *tzaharia*
-
-* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. *Jack Danger Canty*
-
-* Add documentation caveat about when to use count_by_sql. *fearoffish*
-
-* Enhance documentation for increment_counter and decrement_counter. *fearoffish*
-
-* Provide brief introduction to what optimistic locking is. *fearoffish*
-
-* Add documentation for :encoding option to mysql adapter. *marclove*
-
-* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example:
-
- create_table "products" do |t|
- t.column "shop_id", :integer
- t.column "creator_id", :integer
- t.column "name", :string, :default => "Untitled"
- t.column "value", :string, :default => "Untitled"
- t.column "created_at", :datetime
- t.column "updated_at", :datetime
- end
-
- ...can now be written as:
-
- create_table :products do |t|
- t.integer :shop_id, :creator_id
- t.string :name, :value, :default => "Untitled"
- t.timestamps
- end
-
-* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. *Michael Koziarski, jstrachan*
-
-* Improve performance of calling .create on has_many :through associations. *evan*
-
-* Improved cloning performance by relying less on exception raising #8159 *Blaine*
-
-* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> *David Heinemeier Hansson*
-
-* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls *David Heinemeier Hansson*
-
-* Small additions and fixes for ActiveRecord documentation. Closes #7342 *Jeremy McAnally*
-
-* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. *court3nay*
-
-* SQLite: binary escaping works with $KCODE='u'. #7862 *tsuka*
-
-* Base#to_xml supports serialized attributes. #7502 *jonathan*
-
-* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. *Jeremy Kemper*
-
-* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 *Michael Koziarski, Jeremy Kemper*
-
-* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. *Jeremy Kemper*
-
-* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 *Josh Susser*
-
-* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. *Michael Koziarski*
-
-* Allow a polymorphic :source for has_many :through associations. Closes #7143 *protocool*
-
-* Consistent public/protected/private visibility for chained methods. #7813 *Dan Manges*
-
-* Oracle: fix quoted primary keys and datetime overflow. #7798 *Michael Schoen*
-
-* Consistently quote primary key column names. #7763 *toolmantim*
-
-* Fixtures: fix YAML ordered map support. #2665 *Manuel Holtgrewe, nfbuckley*
-
-* DateTimes assume the default timezone. #7764 *Geoff Buesing*
-
-* Sybase: hide timestamp columns since they're inherently read-only. #7716 *Mike Joyce*
-
-* Oracle: overflow Time to DateTime. #7718 *Michael Schoen*
-
-* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 *flowdelic, toolmantim*
-
-* Fix has_many :through << with custom foreign keys. #6466, #7153 *naffis, Rich Collins*
-
-* Test DateTime native type in migrations, including an edge case with dates
- during calendar reform. #7649, #7724 [fedot, Geoff Buesing]
-* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 *Jakob Skjerning, Tom Ward*
-
-* SQLServer: recognize real column type as Ruby float. #7057 *sethladd, Tom Ward*
-
-* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 *Manfred Stienstra*
-
-* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example:
-
- transaction do |transaction|
- david.withdrawal(100)
- mary.deposit(100)
- transaction.rollback! # rolls back the transaction that was otherwise going to be successful
- end
-
-* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method *Jamis Buck*
-
-* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however *Tobias Lütke*
- Task.cache { Task.find(1); Task.find(1) } # => 1 query
-
-* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck*
-
-* Oracle: fix lob and text default handling. #7344 *gfriedrich, Michael Schoen*
-
-* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning*
-
-* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 *Dan Kubb*
-
-* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 *sandofsky, Assaf*
-
-* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc*
-
-* Use Date#to_s(:db) for quoted dates. #7411 *Michael Schoen*
-
-* Don't create instance writer methods for class attributes. Closes #7401 *Rick Olson*
-
-* Docs: validations examples. #7343 *zackchandler*
-
-* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 *sandofsky*
-
-* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden*
-
-* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 *Josh Susser*
-
-* Fix minor doc typos. Closes #7157 *Josh Susser*
-
-* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 *Josh Susser*
-
-* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org*
-
-* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 *BertG, nick+rails@ag.arizona.edu*
-
-* Make sure sqlite3 driver closes open connections on disconnect *Rob Rasmussen*
-
-* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally*
-
-* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper*
-
-* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com*
-
-* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen*
-
-* MySQL: retain SSL settings on reconnect. #6976 *randyv2*
-
-* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. *Cody Fauser*
-
-* SQLServer: handle [quoted] table names. #6635 *rrich*
-
-* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser*
-
-* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen*
-
-* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges*
- Student.find(:all, :conditions => { :grade => 9..12 })
-
-* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler*
-
-* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell*
-
-* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot*
-
-* Bring the sybase adapter up to scratch for 1.2 release. *jsheets*
-
-* Rollback new_record? and id when an exception is raised in a save callback. #6910 *Ben Curren, outerim*
-
-* Pushing a record on an association collection doesn't unnecessarily load all the associated records. *Obie Fernandez, Jeremy Kemper*
-
-* Oracle: fix connection reset failure. #6846 *leonlleslie*
-
-* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper*
-
-* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool*
-
-* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 *Alexander Dymo, Tobias Lütke*
-
-* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper*
-
-* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute *Cody Fauser*
-
-* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form *David Heinemeier Hansson*
-
-* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 *Zach Dennis*
-
-* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov*
-
-* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 *Jonathan Viney*
-
-* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz*
-
-* Run validations in the order they were declared. #6657 *obrie*
-
-* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper*
-
-* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 *martin*
-
-* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen*
-
-* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen*
-
-* Don't inspect unloaded associations. #2905 *lmarlow*
-
-* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 *careo, lukfugl*
-
-* Cache inheritance_column. #6592 *Stefan Kaes*
-
-* Firebird: decimal/numeric support. #6408 *macrnic*
-
-* make add_order a tad faster. #6567 *Stefan Kaes*
-
-* Find with :include respects scoped :order. #5850
-
-* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper*
- find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
-
-* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si*
-
-* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. *Jeremy Kemper*
-
-* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 *Bob Silva*
-
-* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes*
-
-* Deprecation: object transactions warning. *Jeremy Kemper*
-
-* has_one :dependent => :nullify ignores nil associates. #4848, #6528 *bellis@deepthought.org, janovetz, Jeremy Kemper*
-
-* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen*
-
-* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie*
-
-* Document other options available to migration's add_column. #6419 *grg*
-
-* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper*
-
-* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney*
-
-* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson*
-
-* Restore eager condition interpolation, document it's differences *Rick Olson*
-
-* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper*
-
-* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers*
-
-* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson*
-
-* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com*
-
-* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com*
-
-* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan*
-
-* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva*
-
-* The has_many create method works with polymorphic associations. #6361 *Dan Peterson*
-
-* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes*
-
-* save! shouldn't validate twice. #6324 *maiha, Bob Silva*
-
-* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig*
-
-* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson*
-
-* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva*
-
-* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper*
-
-* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski*
-
-* Add a :namespace option to AR::Base#to_xml *Michael Koziarski*
-
-* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper*
-
-* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson*
-
-* Improve yaml fixtures error reporting. #6205 *Bruce Williams*
-
-* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski*
-
-* Add deprecation warning for inferred foreign key. #6029 *Josh Susser*
-
-* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com*
-
-* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser*
-
-* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 *Bob Silva*
-
-* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward*
-
-* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher*
-
-* Deprecation: update docs. #5998 *Jakob Skjerning, Kevin Clark*
-
-* Add some XmlSerialization tests for ActiveRecord *Rick Olson*
-
-* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com*
-
-* Tighten rescue clauses. #5985 *james@grayproductions.net*
-
-* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck*
-
-* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney*
-
-* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney*
-
-* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi*
-
-* SQLServer: fix eager association test. #5901 *Tom Ward*
-
-* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark*
-
-* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com*
-
-* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com*
-
-* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward*
-
-* to_xml: correct naming of included associations. #5831 *Josh Starcher*
-
-* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser*
-
-* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper*
-
- # Create a tagging to associate the post and tag.
- post.tags << Tag.find_by_name('old')
- post.tags.create! :name => 'general'
-
- # Would have been:
- post.taggings.create!(:tag => Tag.find_by_name('finally')
- transaction do
- post.taggings.create!(:tag => Tag.create!(:name => 'general'))
- end
-
-* Cache nil results for :included has_one associations also. #5787 *Michael Schoen*
-
-* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke*
-
-* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper*
- Example: Invoice::Lineitem is given table name invoice_lineitems
-
-* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper*
- # people_active_last_name_index, people_active_deactivated_at_index
- add_index :people, [:active, :last_name]
- add_index :people, [:active, :deactivated_at]
- remove_index :people, [:active, :last_name]
- remove_index :people, [:active, :deactivated_at]
-
- WARNING: backward-incompatibility. Multicolumn indexes created before this
- revision were named using the first column name only. Now they're uniquely
- named using all indexed columns.
-
- To remove an old multicolumn index, remove_index :table_name, :first_column
-
-* Fix for deep includes on the same association. *richcollins@gmail.com*
-
-* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark*
-
-* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson*
-
-* Document find's :from option. Closes #5762. *andrew@redlinesoftware.com*
-
-* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com*
-
-* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
-
-* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen*
-
-* Add documentation for how to disable timestamps on a per model basis. Closes #5684. *matt@mattmargolis.net Marcel Molina Jr.*
-
-* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney*
-
-* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson*
-
-* Formally deprecate the deprecated finders. *Michael Koziarski*
-
-* Formally deprecate rich associations. *Michael Koziarski*
-
-* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com*
-
-* Fix announcement of very long migration names. #5722 *blake@near-time.com*
-
-* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com*
-
-* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com*
-
-* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples:
-
- assert (Topic.exists?(:author_name => "David"))
- assert (Topic.exists?(:author_name => "Mary", :approved => true))
- assert (Topic.exists?(["parent_id = ?", 1]))
-
-* Schema dumper quotes date :default values. *Dave Thomas*
-
-* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson*
-
-* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper*
-
-* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck*
-
-* Allow #count through a has_many association to accept :include. *Dan Peterson*
-
-* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw*
-
-* PostgreSQL: return array fields as strings. #4664 *Robby Russell*
-
-* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward*
-
-* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers*
-
-* Oracle: BigDecimal support. #5667 *Michael Schoen*
-
-* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk*
-
-* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>*
-
-* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com*
-
-* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>*
-
-* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net*
-
-* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com*
-
-* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net*
-
-* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen*
-
-* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen*
-
-* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org*
-
-* Minor tweak to improve performance of ActiveRecord::Base#to_param.
-
-* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au*
-
-* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper*
-
-* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com*
-
-* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com*
-
-* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum.
-
-* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson*
-
-* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda*
- # Obtain an exclusive lock on person 1 so we can safely increment visits.
- Person.transaction do
- # select * from people where id=1 for update
- person = Person.find(1, :lock => true)
- person.visits += 1
- person.save!
- end
-
-* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper*
-
-* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper*
-
-* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar*
-
-* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de)
-
-* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson*
-
-* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example:
-
- Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2)
-
- ...is the same as:
- Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2)
-
- This makes it easier to pass in the options from a form or otherwise outside.
-
-
-* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com*
-
-* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net*
-
-* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com*
-
-* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com*
-
-* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp*
-
-* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net*
-
-* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>*
-
-* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp*
-
-* Records and arrays of records are bound as quoted ids. *Jeremy Kemper*
- Foo.find(:all, :conditions => ['bar_id IN (?)', bars])
- Foo.find(:first, :conditions => ['bar_id = ?', bar])
-
-* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson*
-
-* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson*
-
-* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser*
-
-* Provide Association Extensions access to the instance that the association is being accessed from.
- Closes #4433 *Josh Susser*
-
-* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell*
-
-* Add a quick note about :select and eagerly included associations. *Rick Olson*
-
-* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com*
-
-* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson*
-
-* Added :allow_nil option for aggregations #5091 *Ian White*
-
-* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen*
-
-* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper*
-
-* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com*
-
-* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk*
-
-* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org*
-
-* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com*
-
-* Allow :uniq => true with has_many :through associations. *Jeremy Kemper*
-
-* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.*
-
-* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com*
-
-* Replace superfluous name_to_class_name variant with camelize. *Marcel Molina Jr.*
-
-* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
-
-* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
-
-* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>*
-
-* Update FrontBase adapter to check binding version. Closes #4920. *mlaster@metavillage.com*
-
-* New Frontbase connections don't start in auto-commit mode. Closes #4922. *mlaster@metavillage.com*
-
-* When grouping, use the appropriate option key. *Marcel Molina Jr.*
-
-* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. *Marcel Molina Jr.*
-
-* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com*
-
-* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>*
-
-* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić*
-
-* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu*
-
-* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com*
-
-* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net*
-
-* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>*
-
-* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com*
-
-* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net*
-
-* Fix bug where calculations with long alias names return null. *Rick Olson*
-
-* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson*
-
- @post.tags << @tag # BAD
- @post.taggings.create(:tag => @tag) # GOOD
-
-* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson*
-
-* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com*
-
-* Add ActiveRecord::Errors#to_xml *Jamis Buck*
-
-* Properly quote index names in migrations (closes #4764) *John Long*
-
-* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson*
-
-* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson*
-
-* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson*
-
-* DRY up association collection reader method generation. *Marcel Molina Jr.*
-
-* DRY up and tweak style of the validation error object. *Marcel Molina Jr.*
-
-* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson*
-
- class Account < ActiveRecord::Base
- validates_uniqueness_of :email, :case_sensitive => false
- end
-
-* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser*
-
- class Account < ActiveRecord::Base
- has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
- end
-
- *1.15.3* (March 12th, 2007)
-
- * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool]
-
- * Consistently quote primary key column names. #7763 [toolmantim]
-
- * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley]
-
- * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins]
-
-
-## 1.15.2 (February 5th, 2007) ##
-
-* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges*
- Student.find(:all, :conditions => { :grade => 9..12 })
-
-* Don't create instance writer methods for class attributes. *Rick Olson*
-
-* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck*
-
-* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning*
-
-* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si*
-
-* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc*
-
-* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden*
-
-* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org*
-
-
-## 1.15.1 (January 17th, 2007) ##
-
-* Fix nodoc breaking of adapters
-
-
-## 1.15.0 (January 16th, 2007) ##
-
-* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally*
-
-* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper*
-
-* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com*
-
-* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen*
-
-* MySQL: retain SSL settings on reconnect. #6976 *randyv2*
-
-* SQLServer: handle [quoted] table names. #6635 *rrich*
-
-* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser*
-
-* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen*
-
-* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler*
-
-* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell*
-
-* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot*
-
-* Bring the sybase adapter up to scratch for 1.2 release. *jsheets*
-
-* Oracle: fix connection reset failure. #6846 *leonlleslie*
-
-* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper*
-
-* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool*
-
-* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper*
-
-* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper*
- find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
-
-* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov*
-
-* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper*
-
-* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz*
-
-* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen*
-
-* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen*
-
-* Firebird: decimal/numeric support. #6408 *macrnic*
-
-* Find with :include respects scoped :order. #5850
-
-* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes*
-
-* Deprecation: object transactions warning. *Jeremy Kemper*
-
-* has_one :dependent => :nullify ignores nil associates. #6528 *janovetz, Jeremy Kemper*
-
-* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen*
-
-* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie*
-
-* Document other options available to migration's add_column. #6419 *grg*
-
-* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper*
-
-* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney*
-
-* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson*
-
-* Restore eager condition interpolation, document it's differences *Rick Olson*
-
-* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper*
-
-* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers*
-
-* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson*
-
-* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com*
-
-* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com*
-
-* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan*
-
-* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva*
-
-* The has_many create method works with polymorphic associations. #6361 *Dan Peterson*
-
-* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes*
-
-* save! shouldn't validate twice. #6324 *maiha, Bob Silva*
-
-* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig*
-
-* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson*
-
-* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva*
-
-* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper*
-
-* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski*
-
-* Add a :namespace option to AR::Base#to_xml *Michael Koziarski*
-
-* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper*
-
-* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson*
-
-* Improve yaml fixtures error reporting. #6205 *Bruce Williams*
-
-* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski*
-
-* Add deprecation warning for inferred foreign key. #6029 *Josh Susser*
-
-* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com*
-
-* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser*
-
-* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward*
-
-* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher*
-
-* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com*
-
-* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck*
-
-* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney*
-
-* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney*
-
-* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi*
-
-* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark*
-
-* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com*
-
-* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com*
-
-* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward*
-
-* to_xml: correct naming of included associations. #5831 *Josh Starcher*
-
-* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser*
-
-* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper*
-
- # Create a tagging to associate the post and tag.
- post.tags << Tag.find_by_name('old')
- post.tags.create! :name => 'general'
-
- # Would have been:
- post.taggings.create!(:tag => Tag.find_by_name('finally')
- transaction do
- post.taggings.create!(:tag => Tag.create!(:name => 'general'))
- end
-
-* Cache nil results for :included has_one associations also. #5787 *Michael Schoen*
-
-* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke*
-
-* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper*
- Example: Invoice::Lineitem is given table name invoice_lineitems
-
-* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper*
- # people_active_last_name_index, people_active_deactivated_at_index
- add_index :people, [:active, :last_name]
- add_index :people, [:active, :deactivated_at]
- remove_index :people, [:active, :last_name]
- remove_index :people, [:active, :deactivated_at]
-
- WARNING: backward-incompatibility. Multicolumn indexes created before this
- revision were named using the first column name only. Now they're uniquely
- named using all indexed columns.
-
- To remove an old multicolumn index, remove_index :table_name, :first_column
-
-* Fix for deep includes on the same association. *richcollins@gmail.com*
-
-* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark*
-
-* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson*
-
-* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com*
-
-* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
-
-* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen*
-
-* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney*
-
-* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson*
-
-* Formally deprecate the deprecated finders. *Michael Koziarski*
-
-* Formally deprecate rich associations. *Michael Koziarski*
-
-* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com*
-
-* Fix announcement of very long migration names. #5722 *blake@near-time.com*
-
-* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com*
-
-* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com*
-
-* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples:
-
- assert (Topic.exists?(:author_name => "David"))
- assert (Topic.exists?(:author_name => "Mary", :approved => true))
- assert (Topic.exists?(["parent_id = ?", 1]))
-
-* Schema dumper quotes date :default values. *Dave Thomas*
-
-* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson*
-
-* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper*
-
-* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck*
-
-* Allow #count through a has_many association to accept :include. *Dan Peterson*
-
-* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw*
-
-* PostgreSQL: return array fields as strings. #4664 *Robby Russell*
-
-* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward*
-
-* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers*
-
-* Oracle: BigDecimal support. #5667 *Michael Schoen*
-
-* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk*
-
-* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>*
-
-* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com*
-
-* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net*
-
-* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com*
-
-* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net*
-
-* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen*
-
-* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen*
-
-* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org*
-
-* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au*
-
-* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper*
-
-* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com*
-
-* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com*
-
-* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum.
-
-* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson*
-
-* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda*
- # Obtain an exclusive lock on person 1 so we can safely increment visits.
- Person.transaction do
- # select * from people where id=1 for update
- person = Person.find(1, :lock => true)
- person.visits += 1
- person.save!
- end
-
-* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper*
-
-* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper*
-
-* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar*
-
-* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de)
-
-* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson*
-
-* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example:
-
- Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2)
-
- ...is the same as:
- Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2)
-
- This makes it easier to pass in the options from a form or otherwise outside.
-
-
-* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com*
-
-* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net*
-
-* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com*
-
-* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com*
-
-* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp*
-
-* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net*
-
-* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>*
-
-* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp*
-
-* Records and arrays of records are bound as quoted ids. *Jeremy Kemper*
- Foo.find(:all, :conditions => ['bar_id IN (?)', bars])
- Foo.find(:first, :conditions => ['bar_id = ?', bar])
-
-* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson*
-
-* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson*
-
-* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser*
-
-* Provide Association Extensions access to the instance that the association is being accessed from.
- Closes #4433 *Josh Susser*
-
-* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell*
-
-* Add a quick note about :select and eagerly included associations. *Rick Olson*
-
-* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com*
-
-* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson*
-
-* Added :allow_nil option for aggregations #5091 *Ian White*
-
-* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen*
-
-* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper*
-
-* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com*
-
-* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk*
-
-* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org*
-
-* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com*
-
-* Allow :uniq => true with has_many :through associations. *Jeremy Kemper*
-
-* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.*
-
-* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com*
-
-* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>*
-
-* When grouping, use the appropriate option key. *Marcel Molina Jr.*
-
-* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com*
-
-* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>*
-
-* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić*
-
-* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu*
-
-* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com*
-
-* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net*
-
-* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>*
-
-* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com*
-
-* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net*
-
-* Fix bug where calculations with long alias names return null. *Rick Olson*
-
-* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson*
-
- @post.tags << @tag # BAD
- @post.taggings.create(:tag => @tag) # GOOD
-
-* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson*
-
-* Add ActiveRecord::Errors#to_xml *Jamis Buck*
-
-* Properly quote index names in migrations (closes #4764) *John Long*
-
-* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson*
-
-* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson*
-
-* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson*
-
-* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson*
-
- class Account < ActiveRecord::Base
- validates_uniqueness_of :email, :case_sensitive => false
- end
-
-* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser*
-
- class Account < ActiveRecord::Base
- has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
- end
-
-
-## 1.14.4 (August 8th, 2006) ##
-
-* Add warning about the proper way to validate the presence of a foreign key. #4147 *Francois Beausoleil <francois.beausoleil@gmail.com>*
-
-* Fix syntax error in documentation. #4679 *Mislav Marohnić*
-
-* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com*
-
-
-## 1.14.3 (June 27th, 2006) ##
-
-* Fix announcement of very long migration names. #5722 *blake@near-time.com*
-
-* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>*
-
-* Properly quote index names in migrations (closes #4764) *John Long*
-
-* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson*
-
-* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson*
-
-
-## 1.14.2 (April 9th, 2006) ##
-
-* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen*
-
-
-## 1.14.1 (April 6th, 2006) ##
-
-* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar*
-
-* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind*
-
-* Enable Limit/Offset in Calculations (closes #4558) *lmarlow*
-
-* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson*
-
-* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr*
-
-* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis*
-
-* Support eager includes when going through a polymorphic has_many association. *Rick Olson*
-
-* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson*
-
- class Post < ActiveRecord::Base
- has_one :tagging, :as => :taggable
- end
-
- Post.find :all, :include => :tagging
-
-* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson*
-
-* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson*
-
- class PhotoCollection < ActiveRecord::Base
- has_many :photos, :as => :photographic
- belongs_to :firm
- end
-
- class Firm < ActiveRecord::Base
- has_many :photo_collections
- has_many :photos, :through => :photo_collections
- end
-
-* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com*
-
-* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber*
-
-* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan*
-
-* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson*
-
-* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson*
-
-* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson*
-
-* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.*
-
-* Fixed broken OCIAdapter #4457 *Michael Schoen*
-
-
-## 1.14.0 (March 27th, 2006) ##
-
-* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar*
-
-* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson*
-
-* Add support for :include to with_scope *andrew@redlinesoftware.com*
-
-* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen*
-
-* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com*
-
-* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson*
-
-* Fixed issue that kept :select options from being scoped *Rick Olson*
-
-* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson*
-
-* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson*
-
-* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson*
-
- class Connection < ActiveRecord::Base
- belongs_to :user
- belongs_to :channel
- end
-
- class Channel < ActiveRecord::Base
- has_many :connections
- has_many :contacts, :through => :connections, :class_name => 'User' # OLD
- has_many :contacts, :through => :connections, :source => :user # NEW
- end
-
-* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de*
-
-* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson*
-
- In this example, :include => false disables the default eager association from loading. :select changes the standard
- select clause. :joins specifies a join that is added to the end of the has_many :through query.
-
- class Post < ActiveRecord::Base
- has_many :tags, :through => :taggings, :include => :tagging do
- def add_joins_and_select
- find :all, :select => 'tags.*, authors.id as author_id', :include => false,
- :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
- end
- end
- end
-
-* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson*
-
-* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney*
-
-* Quit ignoring default :include options in has_many :through calls *Mark James*
-
-* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney*
-
-* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson*
-
-* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example:
-
- class Firm < ActiveRecord::Base
- has_many :clients
- has_many :invoices, :through => :clients
- end
-
- class Client < ActiveRecord::Base
- belongs_to :firm
- has_many :invoices
- end
-
- class Invoice < ActiveRecord::Base
- belongs_to :client
- end
-
-* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser*
-
-* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney*
-
-* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson*
-
-* SQL Server adapter gets some love #4298 *Ryan Tomayko*
-
-* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com*
-
-* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI):
-
- Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body')
-
-* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson*
-
-* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski*
-
-* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski*
-
-* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward*
-
-* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com*
-
-* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck*
-
-* Use association's :conditions when eager loading. [Jeremy Evans] #4144
-
-* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans*
-
- This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous.
-
- Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL')
-
-* Oracle adapter gets some love #4230 *Michael Schoen*
-
- * Changes :text to CLOB rather than BLOB [Moses Hohman]
- * Fixes an issue with nil numeric length/scales (several)
- * Implements support for XMLTYPE columns [wilig / Kubo Takehiro]
- * Tweaks a unit test to get it all green again
- * Adds support for #current_database
-
-* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson*
-
- class CachedModel < ActiveRecord::Base
- self.abstract_class = true
- end
-
- class Post < CachedModel
- end
-
- CachedModel.abstract_class?
- => true
-
- Post.abstract_class?
- => false
-
- Post.base_class
- => Post
-
- Post.table_name
- => 'posts'
-
-* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson*
-
- class Foo < ActiveRecord::Base
- has_many :attachments, :as => :attachable, :dependent => :delete_all
- end
-
-* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay*
-
-* Upgrade to Transaction::Simple 1.3 *Jamis Buck*
-
-* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson*
-
-* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com*
-
-* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com*
-
-* Dynamically set allow_concurrency. #4044 *Stefan Kaes*
-
-* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example:
-
- topic.to_xml
-
- ...returns:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <id type="integer">1</id>
- <approved type="boolean">false</approved>
- <replies-count type="integer">0</replies-count>
- <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time>
- <written-on type="datetime">2003-07-16 09:28:00</written-on>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- ...and you can configure with:
-
- topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ])
-
- ...that'll return:
-
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <approved type="boolean">false</approved>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- You can even do load first-level associations as part of the document:
-
- firm.to_xml :include => [ :account, :clients ]
-
- ...that'll return something like:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <firm>
- <id type="integer">1</id>
- <rating type="integer">1</rating>
- <name>37signals</name>
- <clients>
- <client>
- <rating type="integer">1</rating>
- <name>Summit</name>
- </client>
- <client>
- <rating type="integer">1</rating>
- <name>Microsoft</name>
- </client>
- </clients>
- <account>
- <id type="integer">1</id>
- <credit-limit type="integer">50</credit-limit>
- </account>
- </firm>
-
-* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck*
-
-* Documentation fixes for :dependent *robby@planetargon.com*
-
-* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney*
-
-* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org*
-
-* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson*
-
-* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>*
-
-* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson*
-
- * The first time a table is referenced in a join, no alias is used.
- * After that, the parent class name and the reflection name are used.
-
- Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ...
-
- * Any additional join references get a numerical suffix like '_2', '_3', etc.
-
-* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to.
-
-* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples:
-
- # cascaded in two levels
- >> Author.find(:all, :include=>{:posts=>:comments})
- => authors
- +- posts
- +- comments
-
- # cascaded in two levels and normal association
- >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations])
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in two levels with two has_many associations
- >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]})
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in three levels
- >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}})
- => companies
- +- groups
- +- members
- +- favorites
-
-* Make counter cache work when replacing an association #3245 *eugenol@gmail.com*
-
-* Make migrations verbose *Jamis Buck*
-
-* Make counter_cache work with polymorphic belongs_to *Jamis Buck*
-
-* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp*
-
-* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats:
-
- * Does not support DATE SQL column types; use DATETIME instead.
- * Date columns on HABTM join tables are returned as String, not Time.
- * Insertions are potentially broken for :polymorphic join tables
- * BLOB column access not yet fully supported
-
-* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper*
-
-* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper*
-
-* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen*
-
-* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson*
-
-* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes*
-
-* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark*
-
-* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net*
-
-* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney*
-
-* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward*
-
-* Added support for nested scopes #3407 [anna@wota.jp]. Examples:
-
- Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10
-
- # inner rule is used. (all previous parameters are ignored)
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis')
- end
-
- # parameters are merged
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10
- end
- end
-
-* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com*
-
-* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh*
-
-* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind*
-
-* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples:
-
- Person.average :age
- Person.minimum :age
- Person.maximum :age
- Person.sum :salary, :group => :last_name
-
-* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath*
-
-* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper*
-
-* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net*
-
-* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de*
-
-* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes*
-
-* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva*
-
-* Allow :include to be used with has_many :through associations #3611 *Michael Schoen*
-
-* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac*
-
-* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward*
-
-* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson*
-
-* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org*
-
-* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark*
-
-* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke*
-
-* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson*
-
-* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar*
-
-* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt*
-
-* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda*
-
-* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>*
-
-* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen*
-
-* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson*
-
-* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.*
-
-* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar*
-
-* Make .count work for has_many associations with multi line finder sql *Michael Schoen*
-
-* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck*
-
-* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com*
-
-* Don't hardcode 'id' in acts as list. *ror@philippeapril.com*
-
-* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark*
-
-* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp*
-
-* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com*
-
-* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke*
-
-* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.*
-
-* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de*
-
-* Sanitize scoped conditions. *Marcel Molina Jr.*
-
-* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson*
-
-* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke*
-
-* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke*
-
-* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber*
-
-* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron*
-
-* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke*
-
-* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke*
-
-* made .find() work on :through relations. *Tobias Lütke*
-
-* Fix typo in association docs. #3296. *Blair Zajac*
-
-* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke*
-
-## 1.13.2 (December 13th, 2005) ##
-
-* Become part of Rails 1.0
-
-* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper*
-
-* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example:
-
- class Post
- has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author
- end
-
- post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors
- post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors
- post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors
-
-* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson*
-
-* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder*
-
-* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com*
-
-* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org*
-
-* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com*
-
-* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko*
-
-* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com*
-
-* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen*
-
-* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes*
-
-* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil*
-
-* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond*
-
-* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson*
-
-* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen*
-
-* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper*
-
-* Added preliminary support for polymorphic associations *David Heinemeier Hansson*
-* Added preliminary support for join models *David Heinemeier Hansson*
-
-* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.*
-
-* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>*
-
-* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>*
-
-* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper*
-
-* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen*
-
-* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com*
-
-* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper*
-
-* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen*
-
-* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda*
-
-* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper*
-
-* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda*
-
-* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.*
-
-* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes*
-
-* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes*
-
-* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>*
-
-* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans*
-
-* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
-
-* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>*
-
-* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
-
-* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com*
-
-* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
-
-* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>*
-
-* Correct documentation for Base.delete_all. #1568 *Newhydra*
-
-* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>*
-
-* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>*
-
-* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper*
-
-* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>*
-
-* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper*
-
-* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper*
-
-* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper*
-
-* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko*
-
-* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>*
-
-* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de*
-
-* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>*
-
-* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com*
-
-* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar*
-
-* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney*
-
-* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper*
-
-* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.*
-
-* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com*
-
-* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper*
-
-* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper*
-
-* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>*
-
-
-## 1.13.0 (November 7th, 2005) ##
-
-* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko*
-
-* Added :include as an option for association declarations [David Heinemeier Hansson]. Example:
-
- has_many :posts, :include => [ :author, :comments ]
-
-* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example:
-
- Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do
- # Find where name = ? and active=true
- Comment.find :all, :conditions => ['name = ?', name]
- # Create comment associated with :post_id
- Comment.create :body => "Hello world"
- end
-
-* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko*
-
-* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example:
-
- Comment.constrain(:creation => { :post_id => 5 }) do
- # Associated with :post_id
- Comment.create :body => "Hello world"
- end
-
- This is rarely used directly, but allows for find_or_create on associations. So you can do:
-
- # If the tag doesn't exist, a new one is created that's associated with the person
- person.tags.find_or_create_by_name("Summer")
-
-* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example:
-
- # No 'Summer' tag exists
- Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
-
- # Now the 'Summer' tag does exist
- Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
-
-* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example:
-
- class Account < ActiveRecord::Base
- has_many :people do
- def find_or_create_by_name(name)
- first_name, *last_name = name.split
- last_name = last_name.join " "
-
- find_or_create_by_first_name_and_last_name(first_name, last_name)
- end
- end
- end
-
- person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
- person.first_name # => "David"
- person.last_name # => "Heinemeier Hansson"
-
- Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation).
-
-* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko*
-
-* Quote column names in generated SQL. #2728 *Ryan Tomayko*
-
-* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper*
-
-* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper*
-
-* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>*
-
-* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson*
-
-* Added migration support for Oracle #2647 *Michael Schoen*
-
-* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>*
-
-* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko*
-
-* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward*
-
-* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward*
-
-* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com*
-
-* Constraints are cloned so they can't be inadvertently modified while they're
- in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>]
-* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com*
-
-* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen*
-
-* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt*
-
-
-## 1.12.2 (October 26th, 2005) ##
-
-* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark*
-
-* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>*
-
-* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes*
-
-* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>*
-
-* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>*
-
-* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>*
-
-
-## 1.12.1 (October 19th, 2005) ##
-
-* Always parenthesize :conditions options so they may be safely combined with STI and constraints.
-
-* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com*
-
-* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
-
-
-## 1.12.0 (October 16th, 2005) ##
-
-* Update/clean up documentation (rdoc)
-
-* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>*
-
-* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson*
-
-* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net*
-
-* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>*
-
-* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.
-
-* Avoid memleak in dev mode when using fcgi
-
-* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>*
-
-* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>*
-
-* Fix errors caused by assigning a has-one or belongs-to property to itself
-
-* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson*
-
-* Update DB2 adapter. #2206. *contact@maik-schmidt.de*
-
-* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com*
-
-* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency.
-
-* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>*
-
-* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code*
-
-* Add test coverage for content_columns. #2432. *coffee2code*
-
-* Speed up for unthreaded environments. #2431. *Stefan Kaes*
-
-* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes*
-
-* Speed up the setting of table_name. #2428. *Stefan Kaes*
-
-* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>*
-
-* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>*
-
-* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick*
-
-* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar*
-
-* Added :force option to create_table that'll try to drop the table if it already exists before creating
-
-* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar*
-
-* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>*
-
-* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>*
-
-* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman*
-
-* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>*
-
-* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>*
-
-* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>*
-
-* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>*
-
-* Make update_attribute use the same writer method that update_attributes uses.
- \#2237 [trevor@protocool.com]
-* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.*
-
-* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org*
-
-* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com*
-
-* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior)
-
-* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example:
-
- ActiveRecord::Base.observers = :cacher, :garbage_collector
-
-* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com*
-
-* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck*
-
-* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck*
-
-* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck*
-
-* Fixed migrations for Windows when using more than 10 *David Naseby*
-
-* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber*
-
-* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke*
-
-* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar*
-
-* Fixed that Observers didn't observe sub-classes #627 *Florian Weber*
-
-* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.*
-
-* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae*
-
-* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber*
-
-* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil*
-
-* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com*
-
-* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg*
-
-* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward*
-
-* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code*
-
-* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net*
-
-* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/
-
-* Make sure the schema_info table is created before querying the current version #1903
-
-* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning*
-
-* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine*
-
-* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz*
-
-* Make destroy return self #1913 *Sebastian Kanthak*
-
-* Fix typo in validations documentation #1938 *court3nay*
-
-* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org*
-
-* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky*
-
-* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com*
-
-* Fix create_table so that id column is implicitly added *Rick Olson*
-
-* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798
-
-* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798
-
-* Fixed the handling of camelCase columns names in Oracle #1798
-
-* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798
-
-* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798
-
-* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke*
-
- class Comment < AR:B
- def self.search(q)
- find(:all, :conditions => ["body = ?", q])
- end
- end
-
- class Post < AR:B
- has_many :comments
- end
-
- Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi'
-
- NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as
- by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on
- details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself
- noticed :)
-
-* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson*
-
-* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar*
-
-* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions
-
-* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt*
-
-* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes*
-
-
-## 1.11.1 (11 July, 2005) ##
-
-* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson*
-
-* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com*
-
-* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson*
-
-* Correct reflected table name for singular associations. #1688 *court3nay*
-
-* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net*
-
-* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current
-
-* Added better error message for "packets out of order" #1630 *court3nay*
-
-* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640
-
-
-## 1.11.0 (6 July, 2005) ##
-
-* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar*
-
-* Changed logging of SQL statements to use the DEBUG level instead of INFO
-
-* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator.
-
-* Added callback hooks to association collections #1549 [Florian Weber]. Example:
-
- class Project
- has_and_belongs_to_many :developers, :before_add => :evaluate_velocity
-
- def evaluate_velocity(developer)
- ...
- end
- end
-
- ..raising an exception will cause the object not to be added (or removed, with before_remove).
-
-
-* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry*
-
-* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato*
-
-* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber*
-
-* Speed up ActiveRecord#method_missing for the common case (read_attribute).
-
-* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes*
-
-* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath*
-
-* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at*
-
-* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig*
-
-* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry*
-
-* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry*
-
-* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net*
-
-* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl*
-
-* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be:
-
- Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1'
-
- ...should instead be:
-
- Developer.find(
- :all,
- :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
- :conditions => 'project_id=1'
- )
-
-* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.*
-
-* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon*
-
-* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379
-
-* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid*
-
-* Fixed saving of in-memory association structures to happen as an after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice
-
-* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper*
-
-* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak].
- Example:
-
- david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")]
- david.save
-
- If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new
- project is saved when david.save is called.
-
- Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do:
-
- david.project_ids = [1, 5, 7]
-
-* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com*
-
-* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke*
-
-* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org*
-
-* Corrected @@configurations typo #1410 *david@ruppconsulting.com*
-
-* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com*
-
-* Allow before/after update hooks to work on models using optimistic locking
-
-* Eager loading of dependent has_one associations won't delete the association #1212
-
-* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it.
-
-* Using transactional fixtures now causes the data to be loaded only once.
-
-* Added fixture accessor methods that can be used when instantiated fixtures are disabled.
-
- fixtures :web_sites
-
- def test_something
- assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
- end
-
-* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar*
-
-* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar*
-
-* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309
-
-* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead
-
-* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples:
-
- Conditional validations such as the following are made possible:
- validates_numericality_of :income, :if => :employed?
-
- Conditional validations can also solve the salted login generator problem:
- validates_confirmation_of :password, :if => :new_password?
-
- Using blocks:
- validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 }
-
-* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net*
-
-* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson*
-
-* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper*
-
-* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed.
-
-* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first.
-
-* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example:
-
- # SELECT * FROM topics WHERE title IN ('First', 'Second')
- Topic.find_all_by_title(["First", "Second"])
-
-* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor*
-
-* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor*
-
-* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid*
-
-* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com*
-
-* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example:
-
- development:
- adapter: postgresql
- database: rails_development
- host: localhost
- username: postgres
- password:
- encoding: UTF8
- min_messages: ERROR
-
-* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck*
-
-* Added validates_exclusion_of as a negative of validates_inclusion_of
-
-* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls
-
-
-## 1.10.1 (20th April, 2005) ##
-
-* Fixed frivilous database queries being triggered with eager loading on empty associations and other things
-
-* Fixed order of loading in eager associations
-
-* Fixed stray comma when using eager loading and ordering together from has_many associations #1143
-
-
-## 1.10.0 (19th April, 2005) ##
-
-* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example:
-
- for post in Post.find(:all, :limit => 100)
- puts "Post: " + post.title
- puts "Written by: " + post.author.name
- puts "Last comment on: " + post.comments.first.created_on
- end
-
- This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as:
-
- for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ])
-
- ...and the number of database queries needed is now 1.
-
-* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples:
-
- Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(:first, :order => "created_on DESC", :offset => 5)
- Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
- Person.find(:all, :offset => 10, :limit => 10)
-
-* Added acts_as_nested_set #1000 [wschenk]. Introduction:
-
- This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with
- the added feature that you can select the children and all of it's descendants with
- a single query. A good use case for this is a threaded post system, where you want
- to display every reply to a comment without multiple selects.
-
-* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas*
-
-* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com*
-
-* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com*
-
-* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com*
-
-* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher*
-
-* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle*
-
-* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com*
-
-* Added insert_at(position) to acts_as_list #1083 *DeLynnB*
-
-* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order)
-
-* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com*
-
-* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org*
-
-* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864
-
-* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt*
-
-* Added quoting of column names for fixtures #997 *jcfischer@gmail.com*
-
-* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis*
-
-* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes*
-
-* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org*
-
-* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper*
-
-* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org*
-
-* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes*
-
-* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes*
-
-* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas*
-
-* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias)
-
-
-## 1.9.1 (27th March, 2005) ##
-
-* Fixed that Active Record objects with float attribute could not be cloned #808
-
-* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar*
-
-* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count
-
-* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron*
-
-* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb*
-
-
-## 1.9.0 (22th March, 2005) ##
-
-* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example:
-
- Developer.find_all nil, 'id ASC', 5 # return the first five developers
- Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward
-
- This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged.
-
-* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson*
-
-* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins*
-
-* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org*
-
-* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel*
-
-* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid*
-
-* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com*
-
-* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net*
-
-* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak*
-
-* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak*
-
-* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm*
-
-* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself
-
-* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body)
-
-
-## 1.8.0 (7th March, 2005) ##
-
-* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default)
-
-* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron*
-
-* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation:
-
- * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
- +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
- objects that should be inspected to determine which attributes triggered the errors.
- * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
- You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
-
-* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k*
-
-* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper*
-
-* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example:
-
- class Account < ActiveRecord::Base
- has_one :credit_card, :dependent => true
- end
- class CreditCard < ActiveRecord::Base
- belongs_to :account
- end
-
- account.credit_card # => returns existing credit card, lets say id = 12
- account.credit_card = CreditCard.create("number" => "123")
- account.save # => CC with id = 12 is destroyed
-
-
-* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation:
-
- Validates whether the value of the specified attribute is numeric by trying to convert it to
- a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
- <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true).
-
- class Person < ActiveRecord::Base
- validates_numericality_of :value, :on => :create
- end
-
- Configuration options:
- * <tt>message</tt> - A custom error message (default is: "is not a number")
- * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
- * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
-
-
-* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron*
-
-* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed)
-
-* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com*
-
-
-## 1.7.0 (24th February, 2005) ##
-
-* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck*
-
-* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes:
-
- 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple
- and safe way of passing table-specific sequence information to the adapter.)
- 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to
- resort to some hacks to get data converted to Date or Time in Ruby.
- If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the
- hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time.
- This is nasty - but if you use Duck Typing you'll probably not care very much.
- In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is
- valid - too many databases use DATE for both.
- Timezones and sub-second precision on timestamps are not supported.
- 3. Default values that are functions (such as "SYSDATE") are not supported. This is a
- restriction of the way active record supports default values.
- 4. Referential integrity constraints are not fully supported. Under at least
- some circumstances, active record appears to delete parent and child records out of
- sequence and out of transaction scope. (Or this may just be a problem of test setup.)
-
- The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/
-
-* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke*
-
-* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm*
-
-* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka*
-
-* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar*
-
-* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com*
-
-* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au*
-
-* Fixed that find_by_* would fail when column names had numbers #670 *demetrius*
-
-* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn*
-
- 1. Created a new columns method that is much cleaner.
- 2. Corrected a problem with the select and select_all methods
- that didn't account for the LIMIT clause being passed into raw SQL statements.
- 3. Implemented the string_to_time method in order to create proper instances of the time class.
- 4. Added logic to the simplified_type method that allows the database to specify the scale of float data.
- 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string.
-
-* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow*
-
-* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example:
-
- class Person < ActiveRecord::Base
- validates_each :first_name, :last_name do |record, attr|
- record.errors.add attr, 'starts with z.' if attr[0] == ?z
- end
- end
-
-* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper*
-
-* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example:
-
- class Person < ActiveRecord::Base
- validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID }
- end
-
-* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates*
-
-* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example:
-
- class Project < ActiveRecord::Base
- primary_key "sysid"
- table_name "XYZ_PROJECT"
- inheritance_column { original_inheritance_column + "_id" }
- end
-
-* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu*
-
-
-## 1.6.0 (January 25th, 2005) ##
-
-* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once.
-
-* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336
-
-* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once.
-
-* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example
-
- people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
- Person.update(people.keys, people.values)
-
-* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron*
-
-* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat*
-
-* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius*
-
-* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper*
-
-* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson*
-
-* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson*
-
-* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not
-
-* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription
-
-* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius*
-
-* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron*
-
-
-## 1.5.1 (January 18th, 2005) ##
-
-* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates*
-
-* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle*
-
-
-## 1.5.0 (January 17th, 2005) ##
-
-* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel*
-
-* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example:
-
- class Book < ActiveRecord::Base
- has_many :pages
- belongs_to :library
-
- validates_associated :pages, :library
- end
-
-* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition:
-
- == Unsaved objects and associations
-
- You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
- aware of, mostly involving the saving of associated objects.
-
- === One-to-one associations
-
- * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in
- order to update their primary keys - except if the parent object is unsaved (new_record? == true).
- * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
- is cancelled.
- * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
- * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
- not save the parent either.
-
- === Collections
-
- * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
- (the owner of the collection) is not yet stored in the database.
- * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
- * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
- * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
-
-* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates*
-
-* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates*
-
-* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates*
-
-* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates*
-
-* Fixed binary support for PostgreSQL #444 *alex@byzantine.no*
-
-* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the
- collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If
- it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards,
- it'll take one less SELECT query if you use length.
-
-* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de*
-
-* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson*
-
-* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey*
-
-* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz*
-
-* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper*
-
-* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower*
-
-* Added that Observers can use the observes class method instead of overwriting self.observed_class().
-
- Before:
- class ListSweeper < ActiveRecord::Base
- def self.observed_class() [ List, Item ]
- end
-
- After:
- class ListSweeper < ActiveRecord::Base
- observes List, Item
- end
-
-* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is
-
-* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name
-
-* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag.
-
- Before: topic.update_attribute(:approved, !approved?)
- After : topic.toggle!(:approved)
-
-* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example:
-
- page.views # => 1
- page.increment!(:views) # executes an UPDATE statement
- page.views # => 2
-
- page.increment(:views).increment!(:views)
- page.views # => 4
-
-* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns.
-
-
-
-
-## 1.14.2 (April 9th, 2005) ##
-
-* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen*
-
-
-## 1.14.1 (April 6th, 2006) ##
-
-* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar*
-
-* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind*
-
-* Enable Limit/Offset in Calculations (closes #4558) *lmarlow*
-
-* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson*
-
-* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr*
-
-* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis*
-
-* Support eager includes when going through a polymorphic has_many association. *Rick Olson*
-
-* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson*
-
- class Post < ActiveRecord::Base
- has_one :tagging, :as => :taggable
- end
-
- Post.find :all, :include => :tagging
-
-* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson*
-
-* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson*
-
- class PhotoCollection < ActiveRecord::Base
- has_many :photos, :as => :photographic
- belongs_to :firm
- end
-
- class Firm < ActiveRecord::Base
- has_many :photo_collections
- has_many :photos, :through => :photo_collections
- end
-
-* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com*
-
-* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber*
-
-* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan*
-
-* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson*
-
-* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson*
-
-* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson*
-
-* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.*
-
-* Fixed broken OCIAdapter #4457 *Michael Schoen*
-
-
-## 1.14.0 (March 27th, 2006) ##
-
-* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar*
-
-* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson*
-
-* Add support for :include to with_scope *andrew@redlinesoftware.com*
-
-* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen*
-
-* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com*
-
-* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson*
-
-* Fixed issue that kept :select options from being scoped *Rick Olson*
-
-* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson*
-
-* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson*
-
-* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson*
-
- class Connection < ActiveRecord::Base
- belongs_to :user
- belongs_to :channel
- end
-
- class Channel < ActiveRecord::Base
- has_many :connections
- has_many :contacts, :through => :connections, :class_name => 'User' # OLD
- has_many :contacts, :through => :connections, :source => :user # NEW
- end
-
-* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de*
-
-* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson*
-
- In this example, :include => false disables the default eager association from loading. :select changes the standard
- select clause. :joins specifies a join that is added to the end of the has_many :through query.
-
- class Post < ActiveRecord::Base
- has_many :tags, :through => :taggings, :include => :tagging do
- def add_joins_and_select
- find :all, :select => 'tags.*, authors.id as author_id', :include => false,
- :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
- end
- end
- end
-
-* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson*
-
-* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney*
-
-* Quit ignoring default :include options in has_many :through calls *Mark James*
-
-* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney*
-
-* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson*
-
-* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example:
-
- class Firm < ActiveRecord::Base
- has_many :clients
- has_many :invoices, :through => :clients
- end
-
- class Client < ActiveRecord::Base
- belongs_to :firm
- has_many :invoices
- end
-
- class Invoice < ActiveRecord::Base
- belongs_to :client
- end
-
-* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser*
-
-* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney*
-
-* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson*
-
-* SQL Server adapter gets some love #4298 *Ryan Tomayko*
-
-* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com*
-
-* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI):
-
- Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body')
-
-* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson*
-
-* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski*
-
-* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski*
-
-* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward*
-
-* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com*
-
-* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck*
-
-* Use association's :conditions when eager loading. [Jeremy Evans] #4144
-
-* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans*
-
- This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous.
-
- Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL')
-
-* Oracle adapter gets some love #4230 *Michael Schoen*
-
- * Changes :text to CLOB rather than BLOB [Moses Hohman]
- * Fixes an issue with nil numeric length/scales (several)
- * Implements support for XMLTYPE columns [wilig / Kubo Takehiro]
- * Tweaks a unit test to get it all green again
- * Adds support for #current_database
-
-* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson*
-
- class CachedModel < ActiveRecord::Base
- self.abstract_class = true
- end
-
- class Post < CachedModel
- end
-
- CachedModel.abstract_class?
- => true
-
- Post.abstract_class?
- => false
-
- Post.base_class
- => Post
-
- Post.table_name
- => 'posts'
-
-* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson*
-
- class Foo < ActiveRecord::Base
- has_many :attachments, :as => :attachable, :dependent => :delete_all
- end
-
-* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay*
-
-* Upgrade to Transaction::Simple 1.3 *Jamis Buck*
-
-* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson*
-
-* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com*
-
-* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com*
-
-* Dynamically set allow_concurrency. #4044 *Stefan Kaes*
-
-* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example:
-
- topic.to_xml
-
- ...returns:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <id type="integer">1</id>
- <approved type="boolean">false</approved>
- <replies-count type="integer">0</replies-count>
- <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time>
- <written-on type="datetime">2003-07-16 09:28:00</written-on>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- ...and you can configure with:
-
- topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ])
-
- ...that'll return:
-
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <approved type="boolean">false</approved>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- You can even do load first-level associations as part of the document:
-
- firm.to_xml :include => [ :account, :clients ]
-
- ...that'll return something like:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <firm>
- <id type="integer">1</id>
- <rating type="integer">1</rating>
- <name>37signals</name>
- <clients>
- <client>
- <rating type="integer">1</rating>
- <name>Summit</name>
- </client>
- <client>
- <rating type="integer">1</rating>
- <name>Microsoft</name>
- </client>
- </clients>
- <account>
- <id type="integer">1</id>
- <credit-limit type="integer">50</credit-limit>
- </account>
- </firm>
-
-* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck*
-
-* Documentation fixes for :dependent *robby@planetargon.com*
-
-* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney*
-
-* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org*
-
-* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson*
-
-* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>*
-
-* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson*
-
- * The first time a table is referenced in a join, no alias is used.
- * After that, the parent class name and the reflection name are used.
-
- Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ...
-
- * Any additional join references get a numerical suffix like '_2', '_3', etc.
-
-* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to.
-
-* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples:
-
- # cascaded in two levels
- >> Author.find(:all, :include=>{:posts=>:comments})
- => authors
- +- posts
- +- comments
-
- # cascaded in two levels and normal association
- >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations])
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in two levels with two has_many associations
- >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]})
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in three levels
- >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}})
- => companies
- +- groups
- +- members
- +- favorites
-
-* Make counter cache work when replacing an association #3245 *eugenol@gmail.com*
-
-* Make migrations verbose *Jamis Buck*
-
-* Make counter_cache work with polymorphic belongs_to *Jamis Buck*
-
-* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp*
-
-* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats:
-
- * Does not support DATE SQL column types; use DATETIME instead.
- * Date columns on HABTM join tables are returned as String, not Time.
- * Insertions are potentially broken for :polymorphic join tables
- * BLOB column access not yet fully supported
-
-* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper*
-
-* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper*
-
-* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen*
-
-* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson*
-
-* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes*
-
-* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark*
-
-* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net*
-
-* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney*
-
-* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward*
-
-* Added support for nested scopes #3407 [anna@wota.jp]. Examples:
-
- Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10
-
- # inner rule is used. (all previous parameters are ignored)
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis')
- end
-
- # parameters are merged
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10
- end
- end
-
-* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com*
-
-* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh*
-
-* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind*
-
-* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples:
-
- Person.average :age
- Person.minimum :age
- Person.maximum :age
- Person.sum :salary, :group => :last_name
-
-* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath*
-
-* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper*
-
-* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net*
-
-* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de*
-
-* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes*
-
-* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva*
-
-* Allow :include to be used with has_many :through associations #3611 *Michael Schoen*
-
-* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac*
-
-* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward*
-
-* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson*
-
-* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org*
-
-* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark*
-
-* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke*
-
-* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson*
-
-* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar*
-
-* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt*
-
-* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda*
-
-* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>*
-
-* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen*
-
-* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson*
-
-* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.*
-
-* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar*
-
-* Make .count work for has_many associations with multi line finder sql *Michael Schoen*
-
-* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck*
-
-* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com*
-
-* Don't hardcode 'id' in acts as list. *ror@philippeapril.com*
-
-* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark*
-
-* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp*
-
-* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com*
-
-* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke*
-
-* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.*
-
-* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de*
-
-* Sanitize scoped conditions. *Marcel Molina Jr.*
-
-* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson*
-
-* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke*
-
-* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke*
-
-* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber*
-
-* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron*
-
-* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke*
-
-* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke*
-
-* made .find() work on :through relations. *Tobias Lütke*
-
-* Fix typo in association docs. #3296. *Blair Zajac*
-
-* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke*
-
-## 1.13.2 (December 13th, 2005) ##
-
-* Become part of Rails 1.0
-
-* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper*
-
-* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example:
-
- class Post
- has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author
- end
-
- post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors
- post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors
- post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors
-
-* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson*
-
-* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder*
-
-* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com*
-
-* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org*
-
-* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com*
-
-* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko*
-
-* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com*
-
-* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen*
-
-* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes*
-
-* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil*
-
-* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond*
-
-* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson*
-
-* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen*
-
-* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper*
-
-* Added preliminary support for polymorphic associations *David Heinemeier Hansson*
-
-* Added preliminary support for join models *David Heinemeier Hansson*
-
-* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.*
-
-* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>*
-
-* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>*
-
-* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper*
-
-* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen*
-
-* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com*
-
-* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper*
-
-* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen*
-
-* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda*
-
-* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper*
-
-* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda*
-
-* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.*
-
-* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes*
-
-* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes*
-
-* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>*
-
-* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans*
-
-* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
-
-* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>*
-
-* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
-
-* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com*
-
-* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
-
-* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>*
-
-* Correct documentation for Base.delete_all. #1568 *Newhydra*
-
-* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>*
-
-* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>*
-
-* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper*
-
-* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>*
-
-* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper*
-
-* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper*
-
-* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper*
-
-* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko*
-
-* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>*
-
-* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de*
-
-* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>*
-
-* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com*
-
-* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar*
-
-* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney*
-
-* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper*
-
-* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.*
-
-* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com*
-
-* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper*
-
-* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper*
-
-* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>*
-
-
-## 1.13.0 (November 7th, 2005) ##
-
-* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko*
-
-* Added :include as an option for association declarations [David Heinemeier Hansson]. Example:
-
- has_many :posts, :include => [ :author, :comments ]
-
-* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example:
-
- Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do
- # Find where name = ? and active=true
- Comment.find :all, :conditions => ['name = ?', name]
- # Create comment associated with :post_id
- Comment.create :body => "Hello world"
- end
-
-* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko*
-
-* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example:
-
- Comment.constrain(:creation => { :post_id => 5 }) do
- # Associated with :post_id
- Comment.create :body => "Hello world"
- end
-
- This is rarely used directly, but allows for find_or_create on associations. So you can do:
-
- # If the tag doesn't exist, a new one is created that's associated with the person
- person.tags.find_or_create_by_name("Summer")
-
-* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example:
-
- # No 'Summer' tag exists
- Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
-
- # Now the 'Summer' tag does exist
- Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
-
-* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example:
-
- class Account < ActiveRecord::Base
- has_many :people do
- def find_or_create_by_name(name)
- first_name, *last_name = name.split
- last_name = last_name.join " "
-
- find_or_create_by_first_name_and_last_name(first_name, last_name)
- end
- end
- end
-
- person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
- person.first_name # => "David"
- person.last_name # => "Heinemeier Hansson"
-
- Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation).
-
-* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko*
-
-* Quote column names in generated SQL. #2728 *Ryan Tomayko*
-
-* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper*
-
-* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper*
-
-* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>*
-
-* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson*
-
-* Added migration support for Oracle #2647 *Michael Schoen*
-
-* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>*
-
-* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko*
-
-* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward*
-
-* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward*
-
-* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com*
-
-* Constraints are cloned so they can't be inadvertently modified while they're
- in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>]
-* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com*
-
-* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen*
-
-* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt*
-
-
-## 1.12.2 (October 26th, 2005) ##
-
-* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark*
-
-* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>*
-
-* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes*
-
-* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>*
-
-* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>*
-
-* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>*
-
-
-## 1.12.1 (October 19th, 2005) ##
-
-* Always parenthesize :conditions options so they may be safely combined with STI and constraints.
-
-* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com*
-
-* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
-
-
-## 1.12.0 (October 16th, 2005) ##
-
-* Update/clean up documentation (rdoc)
-
-* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>*
-
-* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson*
-
-* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net*
-
-* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>*
-
-* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.
-
-* Avoid memleak in dev mode when using fcgi
-
-* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>*
-
-* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>*
-
-* Fix errors caused by assigning a has-one or belongs-to property to itself
-
-* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson*
-
-* Update DB2 adapter. #2206. *contact@maik-schmidt.de*
-
-* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com*
-
-* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency.
-
-* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>*
-
-* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code*
-
-* Add test coverage for content_columns. #2432. *coffee2code*
-
-* Speed up for unthreaded environments. #2431. *Stefan Kaes*
-
-* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes*
-
-* Speed up the setting of table_name. #2428. *Stefan Kaes*
-
-* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>*
-
-* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>*
-
-* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick*
-
-* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes*
-
-* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar*
-
-* Added :force option to create_table that'll try to drop the table if it already exists before creating
-
-* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar*
-
-* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>*
-
-* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>*
-
-* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman*
-
-* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>*
-
-* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>*
-
-* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>*
-
-* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>*
-
-* Make update_attribute use the same writer method that update_attributes uses.
- \#2237 [trevor@protocool.com]
-* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.*
-
-* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org*
-
-* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com*
-
-* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior)
-
-* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example:
-
- ActiveRecord::Base.observers = :cacher, :garbage_collector
-
-* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com*
-
-* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck*
-
-* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck*
-
-* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck*
-
-* Fixed migrations for Windows when using more than 10 *David Naseby*
-
-* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber*
-
-* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke*
-
-* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar*
-
-* Fixed that Observers didn't observe sub-classes #627 *Florian Weber*
-
-* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.*
-
-* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae*
-
-* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber*
-
-* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil*
-
-* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com*
-
-* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg*
-
-* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward*
-
-* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code*
-
-* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net*
-
-* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/
-
-* Make sure the schema_info table is created before querying the current version #1903
-
-* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning*
-
-* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine*
-
-* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz*
-
-* Make destroy return self #1913 *Sebastian Kanthak*
-
-* Fix typo in validations documentation #1938 *court3nay*
-
-* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org*
-
-* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky*
-
-* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com*
-
-* Fix create_table so that id column is implicitly added *Rick Olson*
-
-* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798
-
-* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798
-
-* Fixed the handling of camelCase columns names in Oracle #1798
-
-* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798
-
-* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798
-
-* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke*
-
- class Comment < AR:B
- def self.search(q)
- find(:all, :conditions => ["body = ?", q])
- end
- end
-
- class Post < AR:B
- has_many :comments
- end
-
- Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi'
-
- NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as
- by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on
- details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself
- noticed :)
-
-* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson*
-
-* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar*
-
-* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions
-
-* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt*
-
-* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes*
-
-
-## 1.11.1 (11 July, 2005) ##
-
-* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson*
-
-* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com*
-
-* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson*
-
-* Correct reflected table name for singular associations. #1688 *court3nay*
-
-* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net*
-
-* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current
-
-* Added better error message for "packets out of order" #1630 *court3nay*
-
-* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640
-
-
-## 1.11.0 (6 July, 2005) ##
-
-* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar*
-
-* Changed logging of SQL statements to use the DEBUG level instead of INFO
-
-* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator.
-
-* Added callback hooks to association collections #1549 [Florian Weber]. Example:
-
- class Project
- has_and_belongs_to_many :developers, :before_add => :evaluate_velocity
-
- def evaluate_velocity(developer)
- ...
- end
- end
-
- ..raising an exception will cause the object not to be added (or removed, with before_remove).
-
-
-* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry*
-
-* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato*
-
-* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber*
-
-* Speed up ActiveRecord#method_missing for the common case (read_attribute).
-
-* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes*
-
-* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath*
-
-* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at*
-
-* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig*
-
-* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry*
-
-* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry*
-
-* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net*
-
-* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl*
-
-* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be:
-
- Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1'
-
- ...should instead be:
-
- Developer.find(
- :all,
- :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
- :conditions => 'project_id=1'
- )
-
-* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.*
-
-* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon*
-
-* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379
-
-* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid*
-
-* Fixed saving of in-memory association structures to happen as an after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice
-
-* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper*
-
-* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak].
- Example:
-
- david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")]
- david.save
-
- If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new
- project is saved when david.save is called.
-
- Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do:
-
- david.project_ids = [1, 5, 7]
-
-* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com*
-
-* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke*
-
-* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org*
-
-* Corrected @@configurations typo #1410 *david@ruppconsulting.com*
-
-* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com*
-
-* Allow before/after update hooks to work on models using optimistic locking
-
-* Eager loading of dependent has_one associations won't delete the association #1212
-
-* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it.
-
-* Using transactional fixtures now causes the data to be loaded only once.
-
-* Added fixture accessor methods that can be used when instantiated fixtures are disabled.
-
- fixtures :web_sites
-
- def test_something
- assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
- end
-
-* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar*
-
-* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar*
-
-* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309
-
-* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead
-
-* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples:
-
- Conditional validations such as the following are made possible:
- validates_numericality_of :income, :if => :employed?
-
- Conditional validations can also solve the salted login generator problem:
- validates_confirmation_of :password, :if => :new_password?
-
- Using blocks:
- validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 }
-
-* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net*
-
-* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson*
-
-* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper*
-
-* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed.
-
-* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first.
-
-* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example:
-
- # SELECT * FROM topics WHERE title IN ('First', 'Second')
- Topic.find_all_by_title(["First", "Second"])
-
-* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor*
-
-* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor*
-
-* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid*
-
-* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com*
-
-* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example:
-
- development:
- adapter: postgresql
- database: rails_development
- host: localhost
- username: postgres
- password:
- encoding: UTF8
- min_messages: ERROR
-
-* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck*
-
-* Added validates_exclusion_of as a negative of validates_inclusion_of
-
-* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls
-
-
-## 1.10.1 (20th April, 2005) ##
-
-* Fixed frivilous database queries being triggered with eager loading on empty associations and other things
-
-* Fixed order of loading in eager associations
-
-* Fixed stray comma when using eager loading and ordering together from has_many associations #1143
-
-
-## 1.10.0 (19th April, 2005) ##
-
-* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example:
-
- for post in Post.find(:all, :limit => 100)
- puts "Post: " + post.title
- puts "Written by: " + post.author.name
- puts "Last comment on: " + post.comments.first.created_on
- end
-
- This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as:
-
- for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ])
-
- ...and the number of database queries needed is now 1.
-
-* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples:
-
- Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(:first, :order => "created_on DESC", :offset => 5)
- Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
- Person.find(:all, :offset => 10, :limit => 10)
-
-* Added acts_as_nested_set #1000 [wschenk]. Introduction:
-
- This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with
- the added feature that you can select the children and all of it's descendants with
- a single query. A good use case for this is a threaded post system, where you want
- to display every reply to a comment without multiple selects.
-
-* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas*
-
-* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com*
-
-* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com*
-
-* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com*
-
-* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher*
-
-* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle*
-
-* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com*
-
-* Added insert_at(position) to acts_as_list #1083 *DeLynnB*
-
-* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order)
-
-* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com*
-
-* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org*
-
-* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864
-
-* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt*
-
-* Added quoting of column names for fixtures #997 *jcfischer@gmail.com*
-
-* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis*
-
-* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes*
-
-* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org*
-
-* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper*
-
-* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org*
-
-* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes*
-
-* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes*
-
-* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas*
-
-* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias)
-
-
-## 1.9.1 (27th March, 2005) ##
-
-* Fixed that Active Record objects with float attribute could not be cloned #808
-
-* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar*
-
-* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count
-
-* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron*
-
-* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb*
-
-
-## 1.9.0 (22th March, 2005) ##
-
-* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example:
-
- Developer.find_all nil, 'id ASC', 5 # return the first five developers
- Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward
-
- This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged.
-
-* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson*
-
-* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins*
-
-* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org*
-
-* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel*
-
-* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid*
-
-* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com*
-
-* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net*
-
-* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak*
-
-* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak*
-
-* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm*
-
-* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself
-
-* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body)
-
-
-## 1.8.0 (7th March, 2005) ##
-
-* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default)
-
-* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron*
-
-* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation:
-
- * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
- +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
- objects that should be inspected to determine which attributes triggered the errors.
- * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
- You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
-
-* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k*
-
-* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper*
-
-* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example:
-
- class Account < ActiveRecord::Base
- has_one :credit_card, :dependent => true
- end
- class CreditCard < ActiveRecord::Base
- belongs_to :account
- end
-
- account.credit_card # => returns existing credit card, lets say id = 12
- account.credit_card = CreditCard.create("number" => "123")
- account.save # => CC with id = 12 is destroyed
-
-
-* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation:
-
- Validates whether the value of the specified attribute is numeric by trying to convert it to
- a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
- <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true).
-
- class Person < ActiveRecord::Base
- validates_numericality_of :value, :on => :create
- end
-
- Configuration options:
- * <tt>message</tt> - A custom error message (default is: "is not a number")
- * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
- * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
-
-
-* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron*
-
-* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed)
-
-* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com*
-
-
-## 1.7.0 (24th February, 2005) ##
-
-* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck*
-
-* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes:
-
- 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple
- and safe way of passing table-specific sequence information to the adapter.)
- 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to
- resort to some hacks to get data converted to Date or Time in Ruby.
- If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the
- hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time.
- This is nasty - but if you use Duck Typing you'll probably not care very much.
- In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is
- valid - too many databases use DATE for both.
- Timezones and sub-second precision on timestamps are not supported.
- 3. Default values that are functions (such as "SYSDATE") are not supported. This is a
- restriction of the way active record supports default values.
- 4. Referential integrity constraints are not fully supported. Under at least
- some circumstances, active record appears to delete parent and child records out of
- sequence and out of transaction scope. (Or this may just be a problem of test setup.)
-
- The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/
-
-* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke*
-
-* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm*
-
-* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka*
-
-* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar*
-
-* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com*
-
-* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au*
-
-* Fixed that find_by_* would fail when column names had numbers #670 *demetrius*
-
-* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn*
-
- 1. Created a new columns method that is much cleaner.
- 2. Corrected a problem with the select and select_all methods
- that didn't account for the LIMIT clause being passed into raw SQL statements.
- 3. Implemented the string_to_time method in order to create proper instances of the time class.
- 4. Added logic to the simplified_type method that allows the database to specify the scale of float data.
- 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string.
-
-* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow*
-
-* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example:
-
- class Person < ActiveRecord::Base
- validates_each :first_name, :last_name do |record, attr|
- record.errors.add attr, 'starts with z.' if attr[0] == ?z
- end
- end
-
-* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper*
-
-* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example:
-
- class Person < ActiveRecord::Base
- validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID }
- end
-
-* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates*
-
-* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example:
-
- class Project < ActiveRecord::Base
- primary_key "sysid"
- table_name "XYZ_PROJECT"
- inheritance_column { original_inheritance_column + "_id" }
- end
-
-* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu*
-
-
-## 1.6.0 (January 25th, 2005) ##
-
-* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once.
-
-* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336
-
-* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once.
-
-* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example
-
- people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
- Person.update(people.keys, people.values)
-
-* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron*
-
-* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat*
-
-* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius*
-
-* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper*
-
-* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson*
-
-* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson*
-
-* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not
-
-* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription
-
-* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius*
-
-* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron*
-
-
-## 1.5.1 (January 18th, 2005) ##
-
-* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates*
-
-* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle*
-
-
-## 1.5.0 (January 17th, 2005) ##
-
-* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel*
-
-* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example:
-
- class Book < ActiveRecord::Base
- has_many :pages
- belongs_to :library
-
- validates_associated :pages, :library
- end
-
-* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition:
-
- == Unsaved objects and associations
-
- You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
- aware of, mostly involving the saving of associated objects.
-
- === One-to-one associations
-
- * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in
- order to update their primary keys - except if the parent object is unsaved (new_record? == true).
- * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
- is cancelled.
- * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
- * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
- not save the parent either.
-
- === Collections
-
- * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
- (the owner of the collection) is not yet stored in the database.
- * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
- * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
- * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
-
-* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates*
-
-* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates*
-
-* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates*
-
-* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates*
-
-* Fixed binary support for PostgreSQL #444 *alex@byzantine.no*
-
-* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the
- collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If
- it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards,
- it'll take one less SELECT query if you use length.
-
-* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de*
-
-* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson*
-
-* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey*
-
-* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz*
-
-* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper*
-
-* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower*
-
-* Added that Observers can use the observes class method instead of overwriting self.observed_class().
-
- Before:
- class ListSweeper < ActiveRecord::Base
- def self.observed_class() [ List, Item ]
- end
-
- After:
- class ListSweeper < ActiveRecord::Base
- observes List, Item
- end
-
-* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is
-
-* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name
-
-* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag.
-
- Before: topic.update_attribute(:approved, !approved?)
- After : topic.toggle!(:approved)
-
-* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example:
-
- page.views # => 1
- page.increment!(:views) # executes an UPDATE statement
- page.views # => 2
-
- page.increment(:views).increment!(:views)
- page.views # => 4
-
-* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns.
-
-
-## 1.4.0 (January 4th, 2005) ##
-
-* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the
- record increments the lock_version column and the locking facilities ensure that records instantiated twice
- will let the last one saved raise a StaleObjectError if the first was also updated. Example:
-
- p1 = Person.find(1)
- p2 = Person.find(1)
-
- p1.first_name = "Michael"
- p1.save
-
- p2.first_name = "should fail"
- p2.save # Raises a ActiveRecord::StaleObjectError
-
- You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
- or otherwise apply the business logic needed to resolve the conflict.
-
- \#384 *Michael Koziarski*
-
-* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL.
- They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name,
- Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do
- <tt>Person.find_by_user_name(user_name)</tt>.
-
- It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
- <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
- <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do
- <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
-
- While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like
- <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful,
- though, as it's not possible to specify the order in which the objects are returned.
-
-* Added block-style for callbacks #332 [Jeremy Kemper].
-
- Before:
- before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" })
-
- After:
- before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
-* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 *Josh Peek*
-
-* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates
- and times from the database. This is set to :local by default.
-
-* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite.
-
-* Added the possibility of having objects with acts_as_list created before their scope is available or...
-
-* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 *Maik Schmidt*
-
-* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 *DeLynn Barry*
-
-* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 *Jeremy Kemper*
-
-* Added HasManyAssociation#count that works like Base#count #413 *intinig*
-
-* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 *xal*
-
-* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 *Tobias Lütke*
-
-* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it.
- If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 *Jeremy Kemper*
-
-* Fixed broken transactions that were actually only running object-level and not db level transactions *andreas*
-
-* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406
-
-* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391
-
-* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 *Dmitry V. Sabanin*
-
-
-## 1.3.0 (December 23, 2004) ##
-
-* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like:
-
- before:
- require_association 'person'
- class Employee < Person
- end
-
- after:
- class Employee < Person
- end
-
- This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes.
-
-* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341
-
-* Added scope option to validation_uniqueness #349 *Kent Sibilev*
-
-* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type.
- This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100".
-
-* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil *what-a-day*
-
-* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case.
- This only works for auto-incrementing primary keys called "id" for now #359 *Scott Baron*
-
-* Added Base#clear_association_cache to empty all the cached associations #347 *Tobias Lütke*
-
-* Added more informative exceptions in establish_connection #356 *Jeremy Kemper*
-
-* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise).
-
- Before:
- person.attributes = @params["person"]
- person.save
-
- Now:
- person.update_attributes(@params["person"])
-
-* Added Base.destroy and Base.delete to remove records without holding a reference to them first.
-
-* Added that query benchmarking will only happen if its going to be logged anyway #344
-
-* Added higher_item and lower_item as public methods for acts_as_list #342 *Tobias Lütke*
-
-* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 *Jeremy Kemper*
-
-* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used
- the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). *Marten*
-
-* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins *Anna Lissa Cruz*
-
-* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction.
- If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction
- bubble up even when you've dealt with local issues. Closes #231 and #340.
-
-* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 *dpiddy@gmail.com*
-
-* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations.
-
-* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request.
-
-
-
-## 1.2.0 ##
-
-* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable
- object. *what-a-day*
-
- class Person < ActiveRecord::Base
- validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!"
- validates_inclusion_of :age, :in=>0..99
- end
-
-* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example:
-
- class TodoItem < ActiveRecord::Base
- acts_as_list :scope => :todo_list_id
- belongs_to :todo_list
- end
-
-* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in
- categories and the likes. *Tobias Lütke*
-
-* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names
- created_at/created_on or updated_at/updated_on are present. *Tobias Lütke*
-
-* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place *Tobias Lütke*
-
-* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all
-
-* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 *Marten*
-
-* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere *RedTerror*
-
-* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example:
-
- ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'.
- This error is raised because the column 'type' is reserved for storing the class in case of inheritance.
- Please rename this column if you didn't intend it to be used for storing the inheritance class or
- overwrite Company.inheritance_column to use another column for that information.
-
-* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't
- have any magic side effects.
-
-* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 *mjobin*
-
-* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples:
-
- Before:
- errors.add(:name, "must be shorter") if name.size > 10
- errors.on(:name) # => "must be shorter"
- errors.on("name") # => nil
-
- After:
- errors.add(:name, "must be shorter") if name.size > 10
- errors.on(:name) # => "must be shorter"
- errors.on("name") # => "must be shorter"
-
-* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching
- it against the regular expression provided. *Marcel Molina Jr.*
-
- class Person < ActiveRecord::Base
- validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create
- end
-
-* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example:
-
- Validates that the specified attribute matches the length restrictions supplied in either:
-
- - configuration[:minimum]
- - configuration[:maximum]
- - configuration[:is]
- - configuration[:within] (aka. configuration[:in])
-
- Only one option can be used at a time.
-
- class Person < ActiveRecord::Base
- validates_length_of :first_name, :maximum=>30
- validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
- validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
- validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
- validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
- end
-
-* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself.
-
-* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system.
- Useful for making sure that only one user can be named "davidhh".
-
- class Person < ActiveRecord::Base
- validates_uniqueness_of :user_name
- end
-
- When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified
- attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
-
-
-* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
-
- Model:
- class Person < ActiveRecord::Base
- validates_confirmation_of :password
- end
-
- View:
- <%= password_field "person", "password" %>
- <%= password_field "person", "password_confirmation" %>
-
- The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual.
- It exists only as an in-memory variable for validating the password. This check is performed both on create and update.
-
-
-* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
-
- class Person < ActiveRecord::Base
- validates_acceptance_of :terms_of_service
- end
-
- The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update.
-
- NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox.
-
-
-* Added validation macros to make the stackable just like the life cycle callbacks. Examples:
-
- class Person < ActiveRecord::Base
- validate { |record| record.errors.add("name", "too short") unless name.size > 10 }
- validate { |record| record.errors.add("name", "too long") unless name.size < 20 }
- validate_on_create :validate_password
-
- private
- def validate_password
- errors.add("password", "too short") unless password.size > 6
- end
- end
-
-* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples:
-
- Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
- Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
-* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening
- through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer
- columns.
-
-* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient
- *Florian Weber*
-
-* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation:
-
- <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is
- specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM.
-
-* Fixed that methods wrapped in callbacks still return their original result #260 *Jeremy Kemper*
-
-* Fixed the Inflector to handle the movie/movies pair correctly #261 *Scott Baron*
-
-* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example:
-
- Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }])
-
-* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method *Michael Koziarski*
-
- Before:
- find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])]
- find_first([ "firm_id = %s", firm_id ])] # unsafe!
-
- After:
- find_first([ "user_name = ? AND password = ?", user_name, password ])]
- find_first([ "firm_id = ?", firm_id ])]
-
-* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information)
-
-* Fixed fixtures using primary key fields called something else than "id" *dave*
-
-* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 *HariSeldon*
-
-* Added reverse order of deleting fixtures, so referential keys can be maintained #247 *Tim Bates*
-
-* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 *Jeremy Kemper*
-
-* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable
-
-* Fixed problems with primary keys and postgresql sequences (#230) *Tim Bates*
-
-* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development.
- This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments.
-
- NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through
- require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the
- auto-loading associations.
-
-* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like:
-
- david:
- id: 1
- name: David
-
- jamis:
- id: 2
- name: Jamis
-
- <% for digit in 3..10 %>
- dev_<%= digit %>:
- id: <%= digit %>
- name: fixture_<%= digit %>
- <% end %>
-
-* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like:
-
- fixtures/developers/fixtures.yaml
- fixtures/accounts/fixtures.yaml
-
- ...you now need to do:
-
- fixtures/developers.yaml
- fixtures/accounts.yaml
-
-* Changed the fixture format from:
-
- name: david
- data:
- id: 1
- name: David Heinemeier Hansson
- birthday: 1979-10-15
- profession: Systems development
- ---
- name: steve
- data:
- id: 2
- name: Steve Ross Kellock
- birthday: 1974-09-27
- profession: guy with keyboard
-
- ...to:
-
- david:
- id: 1
- name: David Heinemeier Hansson
- birthday: 1979-10-15
- profession: Systems development
-
- steve:
- id: 2
- name: Steve Ross Kellock
- birthday: 1974-09-27
- profession: guy with keyboard
-
- The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten!
-
-* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements.
-
-
-## 1.1.0 (34) ##
-
-* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically
- instantiated in instance variables relating to their names using the following style:
-
- class FixturesTest < Test::Unit::TestCase
- fixtures :developers # you can add more with comma separation
-
- def test_developers
- assert_equal 3, @developers.size # the container for all the fixtures is automatically set
- assert_kind_of Developer, @david # works like @developers["david"].find
- assert_equal "David Heinemeier Hansson", @david.name
- end
- end
-
-* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional
- attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association
- between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back
- approach:
-
- post.categories.push_with_attributes(category, :added_on => Date.today)
- post.categories.first.added_on # => Date.today
-
- NOTE: The categories table doesn't have an added_on column, it's the categories_post join table that does!
-
-* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations *Jeremy Kemper*
-
-* Fixed that database passwords couldn't be all numeric *Jeremy Kemper*
-
-* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly *Jeremy Kemper*
-
-* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all *Sam Stephenson/Jeremy Kemper*
-
-* Added that you can pass overlapping ids to find without getting duplicated records back *Jeremy Kemper*
-
-* Added that Base.benchmark returns the result of the block *Jeremy Kemper*
-
-* Fixed problem with unit tests on Windows with SQLite *paterno*
-
-* Fixed that quotes would break regular non-yaml fixtures *Dmitry Sabanin/daft*
-
-* Fixed fixtures on windows with line endings cause problems under unix / mac *Tobias Lütke*
-
-* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id
-
-* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations
-
-* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records *geech*
-
-* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete *geech*
-
-* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create *geech*
-
-* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works:
-
- [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
-* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called
- before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations.
-
-* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates,
- which is common on associations that also use metadata. Usage: post.categories.uniq
-
-* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one
-
-* Fixed has_and_belongs_to_many to treat associations between classes in modules properly *Florian Weber*
-
-* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist *geech*
-
-* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues *geech*
-
-* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods *geech*
-
-* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash *geech*
-
-* Added that any additional fields added to the join table in a has_and_belongs_to_many association
- will be placed as attributes when pulling records out through has_and_belongs_to_many associations.
- This is helpful when have information about the association itself that you want available on retrival.
-
-* Added better loading exception catching and RubyGems retries to the database adapters *alexeyv*
-
-* Fixed bug with per-model transactions *daniel*
-
-* Fixed Base#transaction so that it returns the result of the last expression in the transaction block *alexeyv*
-
-* Added Fixture#find to find the record corresponding to the fixture id. The record
- class name is guessed by using Inflector#classify (also new) on the fixture directory name.
-
- Before: Document.find(@documents["first"]["id"])
- After : @documents["first"].find
-
-* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly *Andreas Schwarz*
-
-* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM *geech*
-
-* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete
- adapters for a call to the dbm. *Andreas Schwarz*
-
-* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR.
-
-
-## 1.0.0 (35) ##
-
-* Added OO-style associations methods [Florian Weber]. Examples:
-
- Project#milestones_count => Project#milestones.size
- Project#build_to_milestones => Project#milestones.build
- Project#create_for_milestones => Project#milestones.create
- Project#find_in_milestones => Project#milestones.find
- Project#find_all_in_milestones => Project#milestones.find_all
-
-* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated
- serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this:
-
- class User < ActiveRecord::Base
- serialize :settings
- end
-
- This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify
- an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in
- the hierarchy. Example:
-
- class User < ActiveRecord::Base
- serialize :settings, :class_name => "Hash"
- end
-
- user = User.create("settings" => %w( one two three ))
- User.find(user.id).settings # => raises SerializationTypeMismatch
-
-* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class
- you want to have connected to another database than Base. This will automatically also connect decendents of that class
- to the different database [Renald Buter].
-
-* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks
- can raise exceptions knowing that the save will be rolled back. *Suggested by Alexey Verkhovsky*
-
-* Added column name quoting so reserved words, such as "references", can be used as column names *Ryan Platte*
-
-* Added the possibility to chain the return of what happened inside a logged block [geech]:
-
- This now works:
- log { ... }.map { ... }
-
- Instead of doing:
- result = []
- log { result = ... }
- result.map { ... }
-
-* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" *Anna Lissa Cruz*
-
-* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema,
- person.respond_to? "name" will return true.
-
-* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
- Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
-
- Project.benchmark("Creating project") do
- project = Project.create("name" => "stuff")
- project.create_manager("name" => "David")
- project.milestones << Milestone.find_all
- end
-
-* Added logging of invalid SQL statements *Daniel Von Fange*
-
-* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name *Andreas Schwarz*
-
-* Added RubyGems require attempt if sqlite-ruby is not available through regular methods.
-
-* Added compatibility with 2.x series of sqlite-ruby drivers. *Jamis Buck*
-
-* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to
- assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on
- mistaken association assignments. *Reported by Andreas Schwarz*
-
-* Added the option to keep many fixtures in one single YAML document *what-a-day*
-
-* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing
- the type for inheritance hierarchies. *Dave Steinberg*
-
-* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten *Dave Steinberg*
-
-* Added the option to observer more than one class at the time by specifying observed_class as an array
-
-* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them
- on PostgreSQL. *Dave Steinberg*
-
-* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49)
-
-* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port *Andreas Schwarz*
-
-* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue.
-
-* Changed class inheritable attributes to not use eval *Caio Chassot*
-
-* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those *Marcel Molina Jr.*
-
-* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) *Marcel Molina Jr.*
-
-* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed.
-
-* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter *Andreas Schwarz*
-
-* Fixed PostgreSQL defaults are now handled gracefully *Dave Steinberg*
-
-* Fixed increment/decrement_counter are now atomic updates *Andreas Schwarz*
-
-* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis *radsaq/Florian Gross*
-
-* Fixed that cloned records would point attribute references on the parent object *Andreas Schwarz*
-
-* Fixed SQL for type call on inheritance hierarchies *Caio Chassot*
-
-* Fixed bug with typed inheritance *Florian Weber*
-
-* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association
-
-
-## 0.9.5 ##
-
-* Expanded the table_name guessing rules immensely [Florian Green]. Documentation:
-
- Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
- directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
- to guess the table name from even when called on Reply. The guessing rules are as follows:
- * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table.
- * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies",
- so a Category class becomes a categories table.
- * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table.
- * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table.
- * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table.
- * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table.
- * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table.
- * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table.
- * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table.
- * Class name ends in an "s": No additional characters are added or removed.
- * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table.
- * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.
- Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended.
- So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
-
- You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a
- "mice" table. Example:
-
- class Mouse < ActiveRecord::Base
- def self.table_name() "mice" end
- end
-
- This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb.
-
-* Added find_all_in_collection to has_many defined collections. Works like this:
-
- class Firm < ActiveRecord::Base
- has_many :clients
- end
-
- firm.id # => 1
- firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000
-
- *Requested by Dave Thomas*
-
-* Fixed finders for inheritance hierarchies deeper than one level *Florian Weber*
-
-* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this:
-
- class Person < ActiveRecord::Base
- protected
- def validation
- errors.add_on_boundry_breaking "password", 3..20
- end
- end
-
- This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if
- the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings.
-
-* Implemented a clone method that works properly with AR. It returns a clone of the record that
- hasn't been assigned an id yet and is treated as a new record.
-
-* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified *Scott Barron*
-
-* Fixed that bignums are saved properly instead of attempted to be YAMLized *Andreas Schwartz*
-
-* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec *Chad Fowler*
-
-* Fixed a bug with the exclusively_dependent option for has_many
-
-
-## 0.9.4 ##
-
-* Correctly guesses the primary key when the class is inside a module [Dave Steinberg].
-
-* Added [] and []= as alternatives to read_attribute and write_attribute *Dave Steinberg*
-
-* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq].
-
-* The ids passed to find and find_on_conditions are now automatically sanitized.
-
-* Added escaping of plings in YAML content.
-
-* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class.
-
-* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create)
-
-
-## 0.9.3 ##
-
-* Fixed bug with using a different primary key name together with has_and_belongs_to_many *Investigation by Scott*
-
-* Added :exclusively_dependent option to the has_many association macro. The doc reads:
-
- If set to true all the associated object are deleted in one SQL statement without having their
- before_destroy callback run. This should only be used on associations that depend solely on
- this class and don't need to do any clean-up in before_destroy. The upside is that it's much
- faster, especially if there's a counter_cache involved.
-
-* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server
- running on another port than the default.
-
-* Converted the new natural singleton methods that prevented AR objects from being saved by PStore
- (and hence be placed in a Rails session) to a module. *Florian Weber*
-
-* Fixed the use of floats (was broken since 0.9.0+)
-
-* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with
- Action Pack scaffolding.
-
-* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) *radsaq*
-
-
-## 0.9.2 ##
-
-* Added static method for instantly updating a record
-
-* Treat decimal and numeric as Ruby floats *Andreas Schwartz*
-
-* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too)
-
-* Removed debugging output accidently left in (which would screw web applications)
-
-
-## 0.9.1 ##
-
-* Added MIT license
-
-* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model:
-
- class Event < ActiveRecord::Base
- has_one_and_belongs_to_many :sponsors
- end
-
- class Sponsor < ActiveRecord::Base
- has_one_and_belongs_to_many :sponsors
- end
-
- Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class:
-
- roskilde_festival.add_to_sponsors(carlsberg)
- roskilde_festival.remove_from_sponsors(carlsberg)
-
- nike.add_to_events(world_cup)
- nike.remove_from_events(world_cup)
-
- Now you can use regular array-styled methods:
-
- roskilde_festival.sponsors << carlsberg
- roskilde_festival.sponsors.delete(carlsberg)
-
- nike.events << world_cup
- nike.events.delete(world_cup)
-
-* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging
- object by setting the foreign key to null. Consider this model:
-
- class Post < ActiveRecord::Base
- has_many :comments
- end
-
- class Comment < ActiveRecord::Base
- belongs_to :post
- end
-
- You could do something like:
-
- funny_comment.has_post? # => true
- announcement.comments.delete(funny_comment)
- funny_comment.has_post? # => false
-
-
-## 0.9.0 ##
-
-* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications)
- *Implementation idea by Michael Neumann, debugging assistance by Jamis Buck*
-
-* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute.
- This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%.
- Done by doing lazy type conversions and caching column information on the class-level.
-
-* Added callback objects and procs as options for implementing the target for callback macros.
-
-* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider:
-
- class Post < ActiveRecord::Base
- has_many :comments
- end
-
- class Comment < ActiveRecord::Base
- belongs_to :post
- end
-
- Iterating over 100 posts like this:
-
- <% for post in @posts %>
- <%= post.title %> has <%= post.comments_count %> comments
- <% end %>
-
- Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column
- to the posts table and rewrite the comments association macro with:
-
- class Comment < ActiveRecord::Base
- belongs_to :post, :counter_cache => true
- end
-
- Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life
- with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify
- :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another),
- you'll have to manage the counter yourself.
-
-* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model:
-
- class Project < ActiveRecord::Base
- has_one :manager
- end
-
- class Manager < ActiveRecord::Base
- belongs_to :project
- end
-
- Earlier, assignments would work like following regardless of which way the assignment told the best story:
-
- active_record.manager_id = david.id
-
- Now you can do it either from the belonging side:
-
- david.project = active_record
-
- ...or from the having side:
-
- active_record.manager = david
-
- If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the
- project_id attribute on david would be set to the id of active_record, then david would be saved.
-
-* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model:
-
- class Project < ActiveRecord::Base
- has_many :milestones
- end
-
- class Milestone < ActiveRecord::Base
- belongs_to :project
- end
-
- Earlier, assignments would work like following regardless of which way the assignment told the best story:
-
- deadline.project_id = active_record.id
-
- Now you can do it either from the belonging side:
-
- deadline.project = active_record
-
- ...or from the having side:
-
- active_record.milestones << deadline
-
- The milestone is automatically saved with the new foreign key.
-
-* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using
- to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time).
- Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header.
- This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do:
-
- user = User.find(1)
- user.preferences = { "background" => "black", "display" => large }
- user.save
-
- User.find(1).preferences # => { "background" => "black", "display" => large }
-
- Please note that this method should only be used when you don't care about representing the object in proper columns in
- the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through
- aggregations than this new option.
-
-* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash
- directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement
- new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this:
-
- class Song < ActiveRecord::Base
- # Uses an integer of seconds to hold the length of the song
-
- def length=(minutes)
- write_attribute("length", minutes * 60)
- end
-
- def length
- read_attribute("length") / 60
- end
- end
-
- The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly.
- This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think
- you know what you're doing and aren't afraid of future consequences, this is an option.
-
-* Applied a few minor bug fixes reported by Daniel Von Fange.
-
-
-## 0.8.4 ##
-
- _Reflection_
-* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations.
-
-* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects.
-
-* Added Base#attribute_names which returns an array of names for the attributes available on the object.
-
-* Added Base#column_for_attribute(name) which returns the column description object for the named attribute.
-
-
- _Misc_
-* Added multi-parameter assignment:
-
- # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done
- # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
- # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
- # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
- # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
- # s for String, and a for Array.
-
- This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day.
-
-* Fixed bug with custom primary key column name and Base.find on multiple parameters.
-
-* Fixed bug with dependent option on has_one associations if there was no associated object.
-
-
-## 0.8.3 ##
-
- _Transactions_
-* Added transactional protection for destroy (important for the new :dependent option) *Suggested by Carl Youngblood*
-
-* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions)
-
-* Changed transactions so only exceptions will cause a rollback, not returned false.
-
-
- _Mapping_
-* Added support for non-integer primary keys *Aredridel/earlier work by Michael Neumann*
-
- User.find "jdoe"
- Product.find "PDKEY-INT-12"
-
-* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either
- be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key
- of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id".
-
-* Added an overwriteable primary_key method that'll instruct AR to the name of the
- id column *Aredridele/earlier work by Guan Yang*
-
- class Project < ActiveRecord::Base
- def self.primary_key() "project_id" end
- end
-
-* Fixed that Active Records can safely associate inside and out of modules.
-
- class MyApplication::Account < ActiveRecord::Base
- has_many :clients # will look for MyApplication::Client
- has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest
- end
-
-* Fixed that Active Records can safely live inside modules *Aredridel*
-
- class MyApplication::Account < ActiveRecord::Base
- end
-
-
- _Misc_
-* Added freeze call to value object assignments to ensure they remain immutable *Spotted by Gavin Sinclair*
-
-* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is
- observed_class() class method. This is more consistant with things like self.table_name(). Works like this:
-
- class AuditObserver < ActiveRecord::Observer
- def self.observed_class() Account end
- def after_update(account)
- AuditTrail.new(account, "UPDATED")
- end
- end
-
- *Suggested by Gavin Sinclair*
-
-* Create new Active Record objects by setting the attributes through a block. Like this:
-
- person = Person.new do |p|
- p.name = 'Freddy'
- p.age = 19
- end
-
- *Suggested by Gavin Sinclair*
-
-
-## 0.8.2 ##
-
-* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are
- run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback
- method:
-
- class Topic < ActiveRecord::Base
- before_destroy :destroy_author, 'puts "I'm an inline fragment"'
- end
-
- Learn more in link:classes/ActiveRecord/Callbacks.html
-
-* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when
- the holder is destroyed:
-
- class Album < ActiveRecord::Base
- has_many :tracks, :dependent => true
- end
-
- All the associated tracks are destroyed when the album is.
-
-* Added Base.create as a factory that'll create, save, and return a new object in one step.
-
-* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you
- to pass the argument hashes directly from yaml. (Luke)
-
-* Fixed the install.rb to include simple.rb *Spotted by Kevin Bullock*
-
-* Modified block syntax to better follow our code standards outlined in
- http://www.rubyonrails.org/CodingStandards
-
-
-## 0.8.1 ##
-
-* Added object-level transactions *Austin Ziegler*
-
-* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection,
- which is parametized through a config hash with symbol keys instead of a regular parameter list.
- This will allow for database connections to be opened in a more generic fashion. (Luke)
-
- NOTE: This requires all *_connections to be updated! Read more in:
- http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081
-
-* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes
- (t.name is now name). *Spotted by Garrett Rooney*
-
-* Fixed SQLite adapter so dates are returned as Date objects, not Time objects *Spotted by Gavin Sinclair*
-
-* Fixed requirement of date class, so date conversions are succesful regardless of whether you
- manually require date or not.
-
-
-## 0.8.0 ##
+## Rails 3.2.4 (May 31, 2012) ##
-* Added transactions
+* Perf fix: Don't load the records when doing assoc.delete_all.
+ GH #6289. *Jon Leighton*
-* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7])
- as parameter and then return an array of objects instead of just an object
+* Association preloading shouldn't be affected by the current scoping.
+ This could cause infinite recursion and potentially other problems.
+ See GH #5667. *Jon Leighton*
-* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a
- collection, not an association
+* Datetime attributes are forced to be changed. GH #3965
-* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type
- aren't treated as current time *Spotted by Gavin Sinclair*
+* Fix attribute casting. GH #5549
+* Fix #5667. Preloading should ignore scoping.
-## 0.7.6 ##
+* Predicate builder should not recurse for determining where columns.
+ Thanks to Ben Murphy for reporting this! CVE-2012-2661
-* Fixed the install.rb to create the lib/active_record/support directory *Spotted by Gavin Sinclair*
-* Fixed that has_association? would always return true *Daniel Von Fange*
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activerecord/CHANGELOG.md) for previous changes.
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
index 60965590a1..d080e0b0f5 100644
--- a/activerecord/README.rdoc
+++ b/activerecord/README.rdoc
@@ -46,6 +46,18 @@ A short rundown of some of the major features:
{Learn more}[link:classes/ActiveRecord/Associations/ClassMethods.html]
+* Aggregations of value objects.
+
+ class Account < ActiveRecord::Base
+ composed_of :balance, :class_name => "Money",
+ :mapping => %w(balance amount)
+ composed_of :address,
+ :mapping => [%w(address_street street), %w(address_city city)]
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Aggregations/ClassMethods.html]
+
+
* Validation rules that can differ for new or existing objects.
class Account < ActiveRecord::Base
diff --git a/activerecord/RUNNING_UNIT_TESTS b/activerecord/RUNNING_UNIT_TESTS
index 2c310e7ac3..bdd8834dcb 100644
--- a/activerecord/RUNNING_UNIT_TESTS
+++ b/activerecord/RUNNING_UNIT_TESTS
@@ -1,11 +1,10 @@
-== Configure databases
+== Setup
-Copy test/config.example.yml to test/config.yml and edit as needed. Or just run the tests for
-the first time, which will do the copy automatically and use the default (sqlite3).
+If you don't have the environment set make sure to read
-You can build postgres and mysql databases using the postgresql:build_databases and mysql:build_databases rake tasks.
+ http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#testing-active-record.
-== Running the tests
+== Running the Tests
You can run a particular test file from the command line, e.g.
@@ -26,7 +25,7 @@ You can run all the tests for a given database via rake:
The 'rake test' task will run all the tests for mysql, mysql2, sqlite3 and postgresql.
-== Config file
+== Custom Config file
By default, the config file is expected to be at the path test/config.yml. You can specify a
custom location with the ARCONFIG environment variable.
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index dca7f13fd2..53791d96ef 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -24,5 +24,5 @@ Gem::Specification.new do |s|
s.add_dependency('activemodel', version)
s.add_dependency('arel', '~> 3.0.2')
- s.add_dependency('active_record_deprecated_finders', '0.0.1')
+ s.add_dependency('activerecord-deprecated_finders', '0.0.1')
end
diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb
index 31f3e02bb8..cd9825b50c 100644
--- a/activerecord/examples/performance.rb
+++ b/activerecord/examples/performance.rb
@@ -1,7 +1,9 @@
-TIMES = (ENV['N'] || 10000).to_i
-
require File.expand_path('../../../load_paths', __FILE__)
require "active_record"
+require 'benchmark/ips'
+
+TIME = (ENV['BENCHMARK_TIME'] || 20).to_i
+RECORDS = (ENV['BENCHMARK_RECORDS'] || TIME*1000).to_i
conn = { :adapter => 'sqlite3', :database => ':memory:' }
@@ -72,8 +74,8 @@ end
notes = ActiveRecord::Faker::LOREM.join ' '
today = Date.today
-puts 'Inserting 10,000 users and exhibits...'
-10_000.times do
+puts "Inserting #{RECORDS} users and exhibits..."
+RECORDS.times do
user = User.create(
:created_at => today,
:name => ActiveRecord::Faker.name,
@@ -88,9 +90,7 @@ puts 'Inserting 10,000 users and exhibits...'
)
end
-require 'benchmark'
-
-Benchmark.bm(46) do |x|
+Benchmark.ips(TIME) do |x|
ar_obj = Exhibit.find(1)
attrs = { :name => 'sam' }
attrs_first = { :name => 'sam' }
@@ -101,77 +101,72 @@ Benchmark.bm(46) do |x|
:created_at => Date.today
}
- x.report("Model#id (x#{(TIMES * 100).ceil})") do
- (TIMES * 100).ceil.times { ar_obj.id }
+ x.report("Model#id") do
+ ar_obj.id
end
x.report 'Model.new (instantiation)' do
- TIMES.times { Exhibit.new }
+ Exhibit.new
end
x.report 'Model.new (setting attributes)' do
- TIMES.times { Exhibit.new(attrs) }
+ Exhibit.new(attrs)
end
x.report 'Model.first' do
- TIMES.times { Exhibit.first.look }
+ Exhibit.first.look
end
- x.report 'Model.named_scope' do
- TIMES.times { Exhibit.limit(10).with_name.with_notes }
+ x.report("Model.all limit(100)") do
+ Exhibit.look Exhibit.limit(100)
end
- x.report("Model.all limit(100) (x#{(TIMES / 10).ceil})") do
- (TIMES / 10).ceil.times { Exhibit.look Exhibit.limit(100) }
+ x.report "Model.all limit(100) with relationship" do
+ Exhibit.feel Exhibit.limit(100).includes(:user)
end
- x.report "Model.all limit(100) with relationship (x#{(TIMES / 10).ceil})" do
- (TIMES / 10).ceil.times { Exhibit.feel Exhibit.limit(100).includes(:user) }
+ x.report "Model.all limit(10,000)" do
+ Exhibit.look Exhibit.limit(10000)
end
- x.report "Model.all limit(10,000) x(#{(TIMES / 1000).ceil})" do
- (TIMES / 1000).ceil.times { Exhibit.look Exhibit.limit(10000) }
+ x.report 'Model.named_scope' do
+ Exhibit.limit(10).with_name.with_notes
end
x.report 'Model.create' do
- TIMES.times { Exhibit.create(exhibit) }
+ Exhibit.create(exhibit)
end
x.report 'Resource#attributes=' do
- TIMES.times {
- exhibit = Exhibit.new(attrs_first)
- exhibit.attributes = attrs_second
- }
+ e = Exhibit.new(attrs_first)
+ e.attributes = attrs_second
end
x.report 'Resource#update' do
- TIMES.times { Exhibit.first.update_attributes(:name => 'bob') }
+ Exhibit.first.update_attributes(:name => 'bob')
end
x.report 'Resource#destroy' do
- TIMES.times { Exhibit.first.destroy }
+ Exhibit.first.destroy
end
x.report 'Model.transaction' do
- TIMES.times { Exhibit.transaction { Exhibit.new } }
+ Exhibit.transaction { Exhibit.new }
end
x.report 'Model.find(id)' do
- id = Exhibit.first.id
- TIMES.times { Exhibit.find(id) }
+ User.find(1)
end
x.report 'Model.find_by_sql' do
- TIMES.times {
- Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first
- }
+ Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first
end
- x.report "Model.log x(#{TIMES * 10})" do
- (TIMES * 10).times { Exhibit.connection.send(:log, "hello", "world") {} }
+ x.report "Model.log" do
+ Exhibit.connection.send(:log, "hello", "world") {}
end
- x.report "AR.execute(query) (#{TIMES / 2})" do
- (TIMES / 2).times { ActiveRecord::Base.connection.execute("Select * from exhibits where id = #{(rand * 1000 + 1).to_i}") }
+ x.report "AR.execute(query)" do
+ ActiveRecord::Base.connection.execute("Select * from exhibits where id = #{(rand * 1000 + 1).to_i}")
end
end
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index a894d83ea7..1675127ab0 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -22,20 +22,54 @@
#++
require 'active_support'
+require 'active_support/rails'
require 'active_model'
require 'arel'
-require 'active_record_deprecated_finders'
+require 'active_record/deprecated_finders'
require 'active_record/version'
module ActiveRecord
extend ActiveSupport::Autoload
+ autoload :Base
+ autoload :Callbacks
+ autoload :Core
+ autoload :CounterCache
+ autoload :ConnectionHandling
+ autoload :DynamicMatchers
+ autoload :Explain
+ autoload :Inheritance
+ autoload :Integration
+ autoload :Migration
+ autoload :Migrator, 'active_record/migration'
+ autoload :Model
+ autoload :ModelSchema
+ autoload :NestedAttributes
+ autoload :Observer
+ autoload :Persistence
+ autoload :QueryCache
+ autoload :Querying
+ autoload :ReadonlyAttributes
+ autoload :Reflection
+ autoload :Sanitization
+ autoload :Schema
+ autoload :SchemaDumper
+ autoload :SchemaMigration
+ autoload :Scoping
+ autoload :Serialization
+ autoload :Store
+ autoload :Timestamp
+ autoload :Transactions
+ autoload :Translation
+ autoload :Validations
+
eager_autoload do
autoload :ActiveRecordError, 'active_record/errors'
autoload :ConnectionNotEstablished, 'active_record/errors'
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
+ autoload :Aggregations
autoload :Associations
autoload :AttributeMethods
autoload :AttributeAssignment
@@ -51,43 +85,10 @@ module ActiveRecord
autoload :PredicateBuilder
autoload :SpawnMethods
autoload :Batches
- autoload :Explain
autoload :Delegation
end
- autoload :Base
- autoload :Callbacks
- autoload :Core
- autoload :CounterCache
- autoload :ConnectionHandling
- autoload :DynamicMatchers
- autoload :Explain
- autoload :Inheritance
- autoload :Integration
- autoload :Migration
- autoload :Migrator, 'active_record/migration'
- autoload :Model
- autoload :ModelSchema
- autoload :NestedAttributes
- autoload :Observer
- autoload :Persistence
- autoload :QueryCache
- autoload :Querying
- autoload :ReadonlyAttributes
- autoload :Reflection
autoload :Result
- autoload :Sanitization
- autoload :Schema
- autoload :SchemaDumper
- autoload :SchemaMigration
- autoload :Scoping
- autoload :Serialization
- autoload :SessionStore
- autoload :Store
- autoload :Timestamp
- autoload :Transactions
- autoload :Translation
- autoload :Validations
end
module Coders
@@ -148,6 +149,15 @@ module ActiveRecord
autoload :TestCase
autoload :TestFixtures, 'active_record/fixtures'
+
+ def self.eager_load!
+ super
+ ActiveRecord::Locking.eager_load!
+ ActiveRecord::Scoping.eager_load!
+ ActiveRecord::Associations.eager_load!
+ ActiveRecord::AttributeMethods.eager_load!
+ ActiveRecord::ConnectionAdapters.eager_load!
+ end
end
ActiveSupport.on_load(:active_record) do
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
new file mode 100644
index 0000000000..3db8e0716b
--- /dev/null
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -0,0 +1,261 @@
+module ActiveRecord
+ # = Active Record Aggregations
+ module Aggregations # :nodoc:
+ extend ActiveSupport::Concern
+
+ def clear_aggregation_cache #:nodoc:
+ @aggregation_cache.clear if persisted?
+ end
+
+ # Active Record implements aggregation through a macro-like class method called +composed_of+
+ # for representing attributes as value objects. It expresses relationships like "Account [is]
+ # composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
+ # to the macro adds a description of how the value objects are created from the attributes of
+ # the entity object (when the entity is initialized either as a new object or from finding an
+ # existing object) and how it can be turned back into attributes (when the entity is saved to
+ # the database).
+ #
+ # class Customer < ActiveRecord::Base
+ # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
+ # composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
+ # end
+ #
+ # The customer class now has the following methods to manipulate the value objects:
+ # * <tt>Customer#balance, Customer#balance=(money)</tt>
+ # * <tt>Customer#address, Customer#address=(address)</tt>
+ #
+ # These methods will operate with value objects like the ones described below:
+ #
+ # class Money
+ # include Comparable
+ # attr_reader :amount, :currency
+ # EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
+ #
+ # def initialize(amount, currency = "USD")
+ # @amount, @currency = amount, currency
+ # end
+ #
+ # def exchange_to(other_currency)
+ # exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
+ # Money.new(exchanged_amount, other_currency)
+ # end
+ #
+ # def ==(other_money)
+ # amount == other_money.amount && currency == other_money.currency
+ # end
+ #
+ # def <=>(other_money)
+ # if currency == other_money.currency
+ # amount <=> other_money.amount
+ # else
+ # amount <=> other_money.exchange_to(currency).amount
+ # end
+ # end
+ # end
+ #
+ # class Address
+ # attr_reader :street, :city
+ # def initialize(street, city)
+ # @street, @city = street, city
+ # end
+ #
+ # def close_to?(other_address)
+ # city == other_address.city
+ # end
+ #
+ # def ==(other_address)
+ # city == other_address.city && street == other_address.street
+ # end
+ # end
+ #
+ # Now it's possible to access attributes from the database through the value objects instead. If
+ # you choose to name the composition the same as the attribute's name, it will be the only way to
+ # access that attribute. That's the case with our +balance+ attribute. You interact with the value
+ # objects just like you would with any other attribute:
+ #
+ # customer.balance = Money.new(20) # sets the Money value object and the attribute
+ # customer.balance # => Money value object
+ # customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
+ # customer.balance > Money.new(10) # => true
+ # customer.balance == Money.new(20) # => true
+ # customer.balance < Money.new(5) # => false
+ #
+ # Value objects can also be composed of multiple attributes, such as the case of Address. The order
+ # of the mappings will determine the order of the parameters.
+ #
+ # customer.address_street = "Hyancintvej"
+ # customer.address_city = "Copenhagen"
+ # customer.address # => Address.new("Hyancintvej", "Copenhagen")
+ #
+ # customer.address_street = "Vesterbrogade"
+ # customer.address # => Address.new("Hyancintvej", "Copenhagen")
+ # customer.clear_aggregation_cache
+ # customer.address # => Address.new("Vesterbrogade", "Copenhagen")
+ #
+ # customer.address = Address.new("May Street", "Chicago")
+ # customer.address_street # => "May Street"
+ # customer.address_city # => "Chicago"
+ #
+ # == Writing value objects
+ #
+ # Value objects are immutable and interchangeable objects that represent a given value, such as
+ # a Money object representing $5. Two Money objects both representing $5 should be equal (through
+ # methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
+ # unlike entity objects where equality is determined by identity. An entity class such as Customer can
+ # easily have two different objects that both have an address on Hyancintvej. Entity identity is
+ # determined by object or relational unique identifiers (such as primary keys). Normal
+ # ActiveRecord::Base classes are entity objects.
+ #
+ # It's also important to treat the value objects as immutable. Don't allow the Money object to have
+ # its amount changed after creation. Create a new Money object with the new value instead. The
+ # Money#exchange_to method is an example of this. It returns a new value object instead of changing
+ # its own values. Active Record won't persist value objects that have been changed through means
+ # other than the writer method.
+ #
+ # The immutable requirement is enforced by Active Record by freezing any object assigned as a value
+ # object. Attempting to change it afterwards will result in a ActiveSupport::FrozenObjectError.
+ #
+ # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
+ # keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
+ #
+ # == Custom constructors and converters
+ #
+ # By default value objects are initialized by calling the <tt>new</tt> constructor of the value
+ # class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
+ # option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
+ # a custom constructor to be specified.
+ #
+ # When a new value is assigned to the value object, the default assumption is that the new value
+ # is an instance of the value class. Specifying a custom converter allows the new value to be automatically
+ # converted to an instance of value class if necessary.
+ #
+ # For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
+ # should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
+ # for the value class is called +create+ and it expects a CIDR address string as a parameter. New
+ # values can be assigned to the value object using either another NetAddr::CIDR object, a string
+ # or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
+ # these requirements:
+ #
+ # class NetworkResource < ActiveRecord::Base
+ # composed_of :cidr,
+ # :class_name => 'NetAddr::CIDR',
+ # :mapping => [ %w(network_address network), %w(cidr_range bits) ],
+ # :allow_nil => true,
+ # :constructor => Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
+ # :converter => Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
+ # end
+ #
+ # # This calls the :constructor
+ # network_resource = NetworkResource.new(:network_address => '192.168.0.1', :cidr_range => 24)
+ #
+ # # These assignments will both use the :converter
+ # network_resource.cidr = [ '192.168.2.1', 8 ]
+ # network_resource.cidr = '192.168.0.1/24'
+ #
+ # # This assignment won't use the :converter as the value is already an instance of the value class
+ # network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
+ #
+ # # Saving and then reloading will use the :constructor on reload
+ # network_resource.save
+ # network_resource.reload
+ #
+ # == Finding records by a value object
+ #
+ # Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
+ # by specifying an instance of the value object in the conditions hash. The following example
+ # finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
+ #
+ # Customer.where(:balance => Money.new(20, "USD")).all
+ #
+ module ClassMethods
+ # Adds reader and writer methods for manipulating a value object:
+ # <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
+ #
+ # Options are:
+ # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
+ # can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
+ # to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
+ # with this option.
+ # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
+ # object. Each mapping is represented as an array where the first item is the name of the
+ # entity attribute and the second item is the name of the attribute in the value object. The
+ # order in which mappings are defined determines the order in which attributes are sent to the
+ # value class constructor.
+ # * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
+ # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
+ # mapped attributes.
+ # This defaults to +false+.
+ # * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
+ # is called to initialize the value object. The constructor is passed all of the mapped attributes,
+ # in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
+ # to instantiate a <tt>:class_name</tt> object.
+ # The default is <tt>:new</tt>.
+ # * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
+ # or a Proc that is called when a new value is assigned to the value object. The converter is
+ # passed the single value that is used in the assignment and is only called if the new value is
+ # not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
+ # can return nil to skip the assignment.
+ #
+ # Option examples:
+ # composed_of :temperature, :mapping => %w(reading celsius)
+ # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount),
+ # :converter => Proc.new { |balance| balance.to_money }
+ # composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
+ # composed_of :gps_location
+ # composed_of :gps_location, :allow_nil => true
+ # composed_of :ip_address,
+ # :class_name => 'IPAddr',
+ # :mapping => %w(ip to_i),
+ # :constructor => Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
+ # :converter => Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
+ #
+ def composed_of(part_id, options = {})
+ options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
+
+ name = part_id.id2name
+ class_name = options[:class_name] || name.camelize
+ mapping = options[:mapping] || [ name, name ]
+ mapping = [ mapping ] unless mapping.first.is_a?(Array)
+ allow_nil = options[:allow_nil] || false
+ constructor = options[:constructor] || :new
+ converter = options[:converter]
+
+ reader_method(name, class_name, mapping, allow_nil, constructor)
+ writer_method(name, class_name, mapping, allow_nil, converter)
+
+ create_reflection(:composed_of, part_id, nil, options, self)
+ end
+
+ private
+ def reader_method(name, class_name, mapping, allow_nil, constructor)
+ define_method(name) do
+ if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
+ attrs = mapping.collect {|pair| read_attribute(pair.first)}
+ object = constructor.respond_to?(:call) ?
+ constructor.call(*attrs) :
+ class_name.constantize.send(constructor, *attrs)
+ @aggregation_cache[name] = object
+ end
+ @aggregation_cache[name]
+ end
+ end
+
+ def writer_method(name, class_name, mapping, allow_nil, converter)
+ define_method("#{name}=") do |part|
+ klass = class_name.constantize
+ unless part.is_a?(klass) || converter.nil? || part.nil?
+ part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
+ end
+
+ if part.nil? && allow_nil
+ mapping.each { |pair| self[pair.first] = nil }
+ @aggregation_cache[name] = nil
+ else
+ mapping.each { |pair| self[pair.first] = part.send(pair.last) }
+ @aggregation_cache[name] = part.freeze
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index a62fce4756..d6b8552e6e 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -1,9 +1,6 @@
require 'active_support/core_ext/enumerable'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/module/remove_method'
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
@@ -104,6 +101,7 @@ module ActiveRecord
# See ActiveRecord::Associations::ClassMethods for documentation.
module Associations # :nodoc:
+ extend ActiveSupport::Autoload
extend ActiveSupport::Concern
# These classes will be loaded when associations are created.
@@ -133,11 +131,13 @@ module ActiveRecord
autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
end
- autoload :Preloader, 'active_record/associations/preloader'
- autoload :JoinDependency, 'active_record/associations/join_dependency'
- autoload :AssociationScope, 'active_record/associations/association_scope'
- autoload :AliasTracker, 'active_record/associations/alias_tracker'
- autoload :JoinHelper, 'active_record/associations/join_helper'
+ eager_autoload do
+ autoload :Preloader, 'active_record/associations/preloader'
+ autoload :JoinDependency, 'active_record/associations/join_dependency'
+ autoload :AssociationScope, 'active_record/associations/association_scope'
+ autoload :AliasTracker, 'active_record/associations/alias_tracker'
+ autoload :JoinHelper, 'active_record/associations/join_helper'
+ end
# Clears out the association cache.
def clear_association_cache #:nodoc:
@@ -195,26 +195,6 @@ module ActiveRecord
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
# <tt>Project#categories.delete(category1)</tt>
#
- # === Overriding generated methods
- #
- # Association methods are generated in a module that is included into the model class,
- # which allows you to easily override with your own methods and call the original
- # generated method with +super+. For example:
- #
- # class Car < ActiveRecord::Base
- # belongs_to :owner
- # belongs_to :old_owner
- # def owner=(new_owner)
- # self.old_owner = self.owner
- # super
- # end
- # end
- #
- # If your model class is <tt>Project</tt>, the module is
- # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
- # included in the model class immediately after the (anonymous) generated attributes methods
- # module, meaning an association will override the methods for an attribute with the same name.
- #
# === A word of warning
#
# Don't create associations that have the same name as instance methods of
@@ -262,6 +242,26 @@ module ActiveRecord
# others.uniq | X | X | X
# others.reset | X | X | X
#
+ # === Overriding generated methods
+ #
+ # Association methods are generated in a module that is included into the model class,
+ # which allows you to easily override with your own methods and call the original
+ # generated method with +super+. For example:
+ #
+ # class Car < ActiveRecord::Base
+ # belongs_to :owner
+ # belongs_to :old_owner
+ # def owner=(new_owner)
+ # self.old_owner = self.owner
+ # super
+ # end
+ # end
+ #
+ # If your model class is <tt>Project</tt>, the module is
+ # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
+ # included in the model class immediately after the (anonymous) generated attributes methods
+ # module, meaning an association will override the methods for an attribute with the same name.
+ #
# == Cardinality and associations
#
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
@@ -397,7 +397,28 @@ module ActiveRecord
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
# saved when the parent is saved.
#
- # === Association callbacks
+ # == Customizing the query
+ #
+ # Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
+ # to customize them. For example, to add a condition:
+ #
+ # class Blog < ActiveRecord::Base
+ # has_many :published_posts, -> { where published: true }, class_name: 'Post'
+ # end
+ #
+ # Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
+ #
+ # === Accessing the owner object
+ #
+ # Sometimes it is useful to have access to the owner object when building the query. The owner
+ # is passed as a parameter to the block. For example, the following association would find all
+ # events that occur on the user's birthday:
+ #
+ # class User < ActiveRecord::Base
+ # has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
+ # end
+ #
+ # == Association callbacks
#
# Similar to the normal callbacks that hook into the life cycle of an Active Record object,
# you can also define callbacks that get triggered when you add an object to or remove an
@@ -424,7 +445,7 @@ module ActiveRecord
# added to the collection. Same with the +before_remove+ callbacks; if an exception is
# thrown the object doesn't get removed.
#
- # === Association extensions
+ # == Association extensions
#
# The proxy objects that control the access to associations can be extended through anonymous
# modules. This is especially beneficial for adding new finders, creators, and other
@@ -454,20 +475,11 @@ module ActiveRecord
# end
#
# class Account < ActiveRecord::Base
- # has_many :people, :extend => FindOrCreateByNameExtension
+ # has_many :people, -> { extending FindOrCreateByNameExtension }
# end
#
# class Company < ActiveRecord::Base
- # has_many :people, :extend => FindOrCreateByNameExtension
- # end
- #
- # If you need to use multiple named extension modules, you can specify an array of modules
- # with the <tt>:extend</tt> option.
- # In the case of name conflicts between methods in the modules, methods in modules later
- # in the array supercede those earlier in the array.
- #
- # class Account < ActiveRecord::Base
- # has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
+ # has_many :people, -> { extending FindOrCreateByNameExtension }
# end
#
# Some extensions can only be made to work with knowledge of the association's internals.
@@ -485,7 +497,7 @@ module ActiveRecord
# the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
# association extensions.
#
- # === Association Join Models
+ # == Association Join Models
#
# Has Many associations can be configured with the <tt>:through</tt> option to use an
# explicit join model to retrieve the data. This operates similarly to a
@@ -569,7 +581,7 @@ module ActiveRecord
# belongs_to :tag, :inverse_of => :taggings
# end
#
- # === Nested Associations
+ # == Nested Associations
#
# You can actually specify *any* association with the <tt>:through</tt> option, including an
# association which has a <tt>:through</tt> option itself. For example:
@@ -612,7 +624,7 @@ module ActiveRecord
# add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
# intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
#
- # === Polymorphic Associations
+ # == Polymorphic Associations
#
# Polymorphic associations on models are not restricted on what types of models they
# can be associated with. Rather, they specify an interface that a +has_many+ association
@@ -742,7 +754,7 @@ module ActiveRecord
# to include an association which has conditions defined on it:
#
# class Post < ActiveRecord::Base
- # has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]
+ # has_many :approved_comments, -> { where approved: true }, :class_name => 'Comment'
# end
#
# Post.includes(:approved_comments)
@@ -754,14 +766,11 @@ module ActiveRecord
# returning all the associated objects:
#
# class Picture < ActiveRecord::Base
- # has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
+ # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, :class_name => 'Comment'
# end
#
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
#
- # When eager loaded, conditions are interpolated in the context of the model class, not
- # the model instance. Conditions are lazily interpolated before the actual model exists.
- #
# Eager loading is supported with polymorphic associations.
#
# class Address < ActiveRecord::Base
@@ -839,8 +848,8 @@ module ActiveRecord
# module MyApplication
# module Business
# class Firm < ActiveRecord::Base
- # has_many :clients
- # end
+ # has_many :clients
+ # end
#
# class Client < ActiveRecord::Base; end
# end
@@ -938,7 +947,8 @@ module ActiveRecord
#
# The <tt>:dependent</tt> option can have different values which specify how the deletion
# is done. For more information, see the documentation for this option on the different
- # specific association types.
+ # specific association types. When no option is given, the behaviour is to do nothing
+ # with the associated records when destroying a record.
#
# === Delete or destroy?
#
@@ -1077,15 +1087,6 @@ module ActiveRecord
# from the association name. So <tt>has_many :products</tt> will by default be linked
# to the Product class, but if the real class name is SpecialProduct, you'll have to
# specify it with this option.
- # [:conditions]
- # Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from
- # the association are scoped if a hash is used.
- # <tt>has_many :posts, :conditions => {:published => true}</tt> will create published
- # posts with <tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.
- # [:order]
- # Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
- # such as <tt>last_name, first_name DESC</tt>.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
@@ -1093,44 +1094,18 @@ module ActiveRecord
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:dependent]
- # If set to <tt>:destroy</tt> all the associated objects are destroyed
- # alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
- # objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
- # objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. If set to
- # <tt>:restrict</tt> an error will be added to the object, preventing its deletion, if any associated
- # objects are present.
+ # Controls what happens to the associated objects when
+ # their owner is destroyed:
+ #
+ # * <tt>:destroy</tt> causes all the associated objects to also be destroyed
+ # * <tt>:delete_all</tt> causes all the asssociated objects to be deleted directly from the database (so callbacks will not execute)
+ # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
+ # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records
+ # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects
#
# If using with the <tt>:through</tt> option, the association on the join model must be
# a +belongs_to+, and the records which get deleted are the join records, rather than
# the associated records.
- #
- # [:finder_sql]
- # Specify a complete SQL statement to fetch the association. This is a good way to go for complex
- # associations that depend on multiple tables. May be supplied as a string or a proc where interpolation is
- # required. Note: When this option is used, +find_in_collection+
- # is _not_ added.
- # [:counter_sql]
- # Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
- # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
- # replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
- # [:extend]
- # Specify a named module for extending the proxy. See "Association extensions".
- # [:include]
- # Specify second-order associations that should be eager loaded when the collection is loaded.
- # [:group]
- # An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
- # [:having]
- # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt>
- # returns. Uses the <tt>HAVING</tt> SQL-clause.
- # [:limit]
- # An integer determining the limit on the number of rows that should be returned.
- # [:offset]
- # An integer determining the offset from where the rows should be fetched. So at 5,
- # it would skip the first 4 rows.
- # [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
- # you want to do a join but not include the joined columns, for example. Do not forget
- # to include the primary and foreign keys, otherwise it will raise an error.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
@@ -1157,16 +1132,14 @@ module ActiveRecord
# [:source_type]
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
# association is a polymorphic +belongs_to+.
- # [:uniq]
- # If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
- # [:readonly]
- # If true, all the associated objects are readonly through the association.
# [:validate]
# If +false+, don't validate the associated objects when saving the parent object. true by default.
# [:autosave]
# If true, always save the associated objects or destroy them if marked for destruction,
# when saving the parent object. If false, never save or destroy the associated objects.
- # By default, only save associated objects that are new records.
+ # By default, only save associated objects that are new records. This option is implemented as a
+ # before_save callback. Because callbacks are run in the order they are defined, associated objects
+ # may need to be explicitly saved in any user-defined before_save callbacks.
#
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
# [:inverse_of]
@@ -1176,24 +1149,16 @@ module ActiveRecord
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
#
# Option examples:
- # has_many :comments, :order => "posted_on"
- # has_many :comments, :include => :author
- # has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
- # has_many :tracks, :order => "position", :dependent => :destroy
- # has_many :comments, :dependent => :nullify
- # has_many :tags, :as => :taggable
- # has_many :reports, :readonly => true
- # has_many :subscribers, :through => :subscriptions, :source => :user
- # has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new {
- # %Q{
- # SELECT DISTINCT *
- # FROM people p, post_subscriptions ps
- # WHERE ps.post_id = #{id} AND ps.person_id = p.id
- # ORDER BY p.first_name
- # }
- # }
- def has_many(name, options = {}, &extension)
- Builder::HasMany.build(self, name, options, &extension)
+ # has_many :comments, -> { order "posted_on" }
+ # has_many :comments, -> { includes :author }
+ # has_many :people, -> { where("deleted = 0").order("name") }, class_name: "Person"
+ # has_many :tracks, -> { order "position" }, dependent: :destroy
+ # has_many :comments, dependent: :nullify
+ # has_many :tags, as: :taggable
+ # has_many :reports, -> { readonly }
+ # has_many :subscribers, through: :subscriptions, source: :user
+ def has_many(name, scope = nil, options = {}, &extension)
+ Builder::HasMany.build(self, name, scope, options, &extension)
end
# Specifies a one-to-one association with another class. This method should only be used
@@ -1241,34 +1206,23 @@ module ActiveRecord
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
# if the real class name is Person, you'll have to specify it with this option.
- # [:conditions]
- # Specify the conditions that the associated object must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>rank = 5</tt>. Record creation from the association is scoped if a hash
- # is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create
- # an enabled account with <tt>@company.create_account</tt> or <tt>@company.build_account</tt>.
- # [:order]
- # Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
- # such as <tt>last_name, first_name DESC</tt>.
# [:dependent]
- # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
- # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
- # If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+.
- # If set to <tt>:restrict</tt>, an error will be added to the object, preventing its deletion, if an
- # associated object is present.
+ # Controls what happens to the associated object when
+ # its owner is destroyed:
+ #
+ # * <tt>:destroy</tt> causes the associated object to also be destroyed
+ # * <tt>:delete</tt> causes the asssociated object to be deleted directly from the database (so callbacks will not execute)
+ # * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
+ # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
+ # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
# will use "person_id" as the default <tt>:foreign_key</tt>.
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
- # [:include]
- # Specify second-order associations that should be eager loaded when this object is loaded.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
- # [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
- # you want to do a join but not include the joined columns, for example. Do not forget to include the
- # primary and foreign keys, otherwise it will raise an error.
# [:through]
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
# <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
@@ -1282,8 +1236,6 @@ module ActiveRecord
# [:source_type]
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
# association is a polymorphic +belongs_to+.
- # [:readonly]
- # If true, the associated object is readonly through the association.
# [:validate]
# If +false+, don't validate the associated object when saving the parent object. +false+ by default.
# [:autosave]
@@ -1302,14 +1254,14 @@ module ActiveRecord
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
# has_one :credit_card, :dependent => :nullify # updates the associated records foreign
# # key value to NULL rather than destroying it
- # has_one :last_comment, :class_name => "Comment", :order => "posted_on"
- # has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
- # has_one :attachment, :as => :attachable
- # has_one :boss, :readonly => :true
- # has_one :club, :through => :membership
- # has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
- def has_one(name, options = {})
- Builder::HasOne.build(self, name, options)
+ # has_one :last_comment, -> { order 'posted_on' }, :class_name => "Comment"
+ # has_one :project_manager, -> { where role: 'project_manager' }, :class_name => "Person"
+ # has_one :attachment, as: :attachable
+ # has_one :boss, readonly: :true
+ # has_one :club, through: :membership
+ # has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
+ def has_one(name, scope = nil, options = {})
+ Builder::HasOne.build(self, name, scope, options)
end
# Specifies a one-to-one association with another class. This method should only be used
@@ -1354,13 +1306,6 @@ module ActiveRecord
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
# if the real class name is Person, you'll have to specify it with this option.
- # [:conditions]
- # Specify the conditions that the associated object must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>authorized = 1</tt>.
- # [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed
- # if you want to do a join but not include the joined columns, for example. Do not
- # forget to include the primary and foreign keys, otherwise it will raise an error.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
@@ -1393,14 +1338,10 @@ module ActiveRecord
# option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
# using +attr_readonly+.
- # [:include]
- # Specify second-order associations that should be eager loaded when this object is loaded.
# [:polymorphic]
# Specify this association is a polymorphic association by passing +true+.
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
- # [:readonly]
- # If true, the associated object is readonly through the association.
# [:validate]
# If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
# [:autosave]
@@ -1421,18 +1362,18 @@ module ActiveRecord
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
#
# Option examples:
- # belongs_to :firm, :foreign_key => "client_of"
- # belongs_to :person, :primary_key => "name", :foreign_key => "person_name"
- # belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
- # belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
- # :conditions => 'discounts > #{payments_count}'
- # belongs_to :attachable, :polymorphic => true
- # belongs_to :project, :readonly => true
- # belongs_to :post, :counter_cache => true
- # belongs_to :company, :touch => true
- # belongs_to :company, :touch => :employees_last_updated_at
- def belongs_to(name, options = {})
- Builder::BelongsTo.build(self, name, options)
+ # belongs_to :firm, foreign_key: "client_of"
+ # belongs_to :person, primary_key: "name", foreign_key: "person_name"
+ # belongs_to :author, class_name: "Person", foreign_key: "author_id"
+ # belongs_to :valid_coupon, ->(o) { where "discounts > #{o.payments_count}" },
+ # class_name: "Coupon", foreign_key: "coupon_id"
+ # belongs_to :attachable, polymorphic: true
+ # belongs_to :project, readonly: true
+ # belongs_to :post, counter_cache: true
+ # belongs_to :company, touch: true
+ # belongs_to :company, touch: :employees_last_updated_at
+ def belongs_to(name, scope = nil, options = {})
+ Builder::BelongsTo.build(self, name, scope, options)
end
# Specifies a many-to-many relationship with another class. This associates two classes via an
@@ -1544,47 +1485,6 @@ module ActiveRecord
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
- # [:conditions]
- # Specify the conditions that the associated object must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are
- # scoped if a hash is used.
- # <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
- # or <tt>@blog.posts.build</tt>.
- # [:order]
- # Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
- # such as <tt>last_name, first_name DESC</tt>
- # [:uniq]
- # If true, duplicate associated objects will be ignored by accessors and query methods.
- # [:finder_sql]
- # Overwrite the default generated SQL statement used to fetch the association with a manual statement
- # [:counter_sql]
- # Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
- # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
- # replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
- # [:delete_sql]
- # Overwrite the default generated SQL statement used to remove links between the associated
- # classes with a manual statement.
- # [:insert_sql]
- # Overwrite the default generated SQL statement used to add links between the associated classes
- # with a manual statement.
- # [:extend]
- # Anonymous module for extending the proxy, see "Association extensions".
- # [:include]
- # Specify second-order associations that should be eager loaded when the collection is loaded.
- # [:group]
- # An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
- # [:having]
- # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns.
- # Uses the <tt>HAVING</tt> SQL-clause.
- # [:limit]
- # An integer determining the limit on the number of rows that should be returned.
- # [:offset]
- # An integer determining the offset from where the rows should be fetched. So at 5,
- # it would skip the first 4 rows.
- # [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
- # you want to do a join but exclude the joined columns, for example. Do not forget to include the primary
- # and foreign keys, otherwise it will raise an error.
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
@@ -1599,14 +1499,12 @@ module ActiveRecord
#
# Option examples:
# has_and_belongs_to_many :projects
- # has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
- # has_and_belongs_to_many :nations, :class_name => "Country"
- # has_and_belongs_to_many :categories, :join_table => "prods_cats"
- # has_and_belongs_to_many :categories, :readonly => true
- # has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
- # proc { |record| "DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}" }
- def has_and_belongs_to_many(name, options = {}, &extension)
- Builder::HasAndBelongsToMany.build(self, name, options, &extension)
+ # has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
+ # has_and_belongs_to_many :nations, class_name: "Country"
+ # has_and_belongs_to_many :categories, join_table: "prods_cats"
+ # has_and_belongs_to_many :categories, -> { readonly }
+ def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
+ Builder::HasAndBelongsToMany.build(self, name, scope, options, &extension)
end
end
end
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index e75003f261..9f47e7e631 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/object/inclusion'
module ActiveRecord
module Associations
@@ -81,10 +80,15 @@ module ActiveRecord
loaded!
end
- def scoped
+ def scope
target_scope.merge(association_scope)
end
+ def scoped
+ ActiveSupport::Deprecation.warn("#scoped is deprecated. use #scope instead.")
+ scope
+ end
+
# The scope for this association.
#
# Note that the association_scope is merged into the target_scope only when the
@@ -118,7 +122,7 @@ module ActiveRecord
# Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
# through association's scope)
def target_scope
- klass.scoped
+ klass.all
end
# Loads the \target if needed and returns it.
@@ -148,6 +152,21 @@ module ActiveRecord
end
end
+ # We can't dump @reflection since it contains the scope proc
+ def marshal_dump
+ reflection = @reflection
+ @reflection = nil
+
+ ivars = instance_variables.map { |name| [name, instance_variable_get(name)] }
+ [reflection.name, ivars]
+ end
+
+ def marshal_load(data)
+ reflection_name, ivars = data
+ ivars.each { |name, val| instance_variable_set(name, val) }
+ @reflection = @owner.class.reflect_on_association(reflection_name)
+ end
+
private
def find_target?
@@ -157,7 +176,7 @@ module ActiveRecord
def creation_attributes
attributes = {}
- if reflection.macro.in?([:has_one, :has_many]) && !options[:through]
+ if (reflection.macro == :has_one || reflection.macro == :has_many) && !options[:through]
attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
if reflection.options[:as]
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index 89a626693d..1303822868 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -6,7 +6,7 @@ module ActiveRecord
attr_reader :association, :alias_tracker
delegate :klass, :owner, :reflection, :interpolate, :to => :association
- delegate :chain, :conditions, :options, :source_options, :active_record, :to => :reflection
+ delegate :chain, :scope_chain, :options, :source_options, :active_record, :to => :reflection
def initialize(association)
@association = association
@@ -15,20 +15,7 @@ module ActiveRecord
def scope
scope = klass.unscoped
-
- scope.extending!(*Array(options[:extend]))
-
- # It's okay to just apply all these like this. The options will only be present if the
- # association supports that option; this is enforced by the association builder.
- scope.merge!(options.slice(
- :readonly, :references, :order, :limit, :joins, :group, :having, :offset, :select, :uniq))
-
- if options[:include]
- scope.includes! options[:include]
- elsif options[:through]
- scope.includes! source_options[:include]
- end
-
+ scope.merge! eval_scope(klass, reflection.scope) if reflection.scope
add_constraints(scope)
end
@@ -82,8 +69,6 @@ module ActiveRecord
foreign_key = reflection.active_record_primary_key
end
- conditions = self.conditions[i]
-
if reflection == chain.last
bind_val = bind scope, table.table_name, key.to_s, owner[foreign_key]
scope = scope.where(table[key].eq(bind_val))
@@ -93,14 +78,6 @@ module ActiveRecord
bind_val = bind scope, table.table_name, reflection.type.to_s, value
scope = scope.where(table[reflection.type].eq(bind_val))
end
-
- conditions.each do |condition|
- if options[:through] && condition.is_a?(Hash)
- condition = disambiguate_condition(table, condition)
- end
-
- scope = scope.where(interpolate(condition))
- end
else
constraint = table[key].eq(foreign_table[foreign_key])
@@ -110,13 +87,15 @@ module ActiveRecord
end
scope = scope.joins(join(foreign_table, constraint))
+ end
- conditions.each do |condition|
- condition = interpolate(condition)
- condition = disambiguate_condition(table, condition) unless i == 0
+ # Exclude the scope of the association itself, because that
+ # was already merged in the #scope method.
+ (scope_chain[i] - [self.reflection.scope]).each do |scope_chain_item|
+ item = eval_scope(reflection.klass, scope_chain_item)
- scope = scope.where(condition)
- end
+ scope.includes! item.includes_values
+ scope.where_values += item.where_values
end
end
@@ -138,19 +117,11 @@ module ActiveRecord
end
end
- def disambiguate_condition(table, condition)
- if condition.is_a?(Hash)
- Hash[
- condition.map do |k, v|
- if v.is_a?(Hash)
- [k, v]
- else
- [table.table_alias || table.name, { k => v }]
- end
- end
- ]
+ def eval_scope(klass, scope)
+ if scope.is_a?(Relation)
+ scope
else
- condition
+ klass.unscoped.instance_exec(owner, &scope)
end
end
end
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index ddfc6f6c05..75f72c1a46 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -2,6 +2,11 @@ module ActiveRecord
# = Active Record Belongs To Associations
module Associations
class BelongsToAssociation < SingularAssociation #:nodoc:
+
+ def handle_dependency
+ target.send(options[:dependent]) if load_target
+ end
+
def replace(record)
raise_on_type_mismatch(record) if record
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
index 9a6896dd55..1df876bf62 100644
--- a/activerecord/lib/active_record/associations/builder/association.rb
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -1,86 +1,106 @@
module ActiveRecord::Associations::Builder
class Association #:nodoc:
- class_attribute :valid_options
- self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate, :references]
+ class << self
+ attr_accessor :valid_options
+ end
- # Set by subclasses
- class_attribute :macro
+ self.valid_options = [:class_name, :foreign_key, :validate]
- attr_reader :model, :name, :options, :reflection
+ attr_reader :model, :name, :scope, :options, :reflection
- def self.build(model, name, options)
- new(model, name, options).build
+ def self.build(*args, &block)
+ new(*args, &block).build
end
- def initialize(model, name, options)
- @model, @name, @options = model, name, options
+ def initialize(model, name, scope, options)
+ @model = model
+ @name = name
+
+ if scope.is_a?(Hash)
+ @scope = nil
+ @options = scope
+ else
+ @scope = scope
+ @options = options
+ end
+
+ if @scope && @scope.arity == 0
+ prev_scope = @scope
+ @scope = proc { instance_exec(&prev_scope) }
+ end
end
def mixin
@model.generated_feature_methods
end
+ include Module.new { def build; end }
+
def build
validate_options
- reflection = model.create_reflection(self.class.macro, name, options, model)
define_accessors
- reflection
+ configure_dependency if options[:dependent]
+ @reflection = model.create_reflection(macro, name, scope, options, model)
+ super # provides an extension point
+ @reflection
end
- private
+ def macro
+ raise NotImplementedError
+ end
- def validate_options
- options.assert_valid_keys(self.class.valid_options)
- end
+ def valid_options
+ Association.valid_options
+ end
- def define_accessors
- define_readers
- define_writers
- end
+ def validate_options
+ options.assert_valid_keys(valid_options)
+ end
- def define_readers
- name = self.name
- mixin.redefine_method(name) do |*params|
- association(name).reader(*params)
+ def define_accessors
+ define_readers
+ define_writers
+ end
+
+ def define_readers
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}(*args)
+ association(:#{name}).reader(*args)
end
- end
+ CODE
+ end
- def define_writers
- name = self.name
- mixin.redefine_method("#{name}=") do |value|
- association(name).writer(value)
+ def define_writers
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}=(value)
+ association(:#{name}).writer(value)
end
- end
+ CODE
+ end
- def dependent_restrict_raises?
- ActiveRecord::Base.dependent_restrict_raises == true
+ def configure_dependency
+ unless valid_dependent_options.include? options[:dependent]
+ raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{options[:dependent]}"
end
- def dependent_restrict_deprecation_warning
- if dependent_restrict_raises?
- msg = "In the next release, `:dependent => :restrict` will not raise a `DeleteRestrictionError`. "\
- "Instead, it will add an error on the model. To fix this warning, make sure your code " \
- "isn't relying on a `DeleteRestrictionError` and then add " \
- "`config.active_record.dependent_restrict_raises = false` to your application config."
- ActiveSupport::Deprecation.warn msg
- end
+ if options[:dependent] == :restrict
+ ActiveSupport::Deprecation.warn(
+ "The :restrict option is deprecated. Please use :restrict_with_exception instead, which " \
+ "provides the same functionality."
+ )
end
- def define_restrict_dependency_method
- name = self.name
- mixin.redefine_method(dependency_method_name) do
- has_one_macro = association(name).reflection.macro == :has_one
- if has_one_macro ? !send(name).nil? : send(name).exists?
- if dependent_restrict_raises?
- raise ActiveRecord::DeleteRestrictionError.new(name)
- else
- key = has_one_macro ? "one" : "many"
- errors.add(:base, :"restrict_dependent_destroy.#{key}",
- :record => self.class.human_attribute_name(name).downcase)
- return false
- end
- end
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{macro}_dependent_for_#{name}
+ association(:#{name}).handle_dependency
end
- end
+ CODE
+
+ model.before_destroy "#{macro}_dependent_for_#{name}"
+ end
+
+ def valid_dependent_options
+ raise NotImplementedError
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
index 4183c222de..2f2600b7fb 100644
--- a/activerecord/lib/active_record/associations/builder/belongs_to.rb
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -1,10 +1,12 @@
-require 'active_support/core_ext/object/inclusion'
-
module ActiveRecord::Associations::Builder
class BelongsTo < SingularAssociation #:nodoc:
- self.macro = :belongs_to
+ def macro
+ :belongs_to
+ end
- self.valid_options += [:foreign_type, :polymorphic, :touch]
+ def valid_options
+ super + [:foreign_type, :polymorphic, :touch]
+ end
def constructable?
!options[:polymorphic]
@@ -14,74 +16,51 @@ module ActiveRecord::Associations::Builder
reflection = super
add_counter_cache_callbacks(reflection) if options[:counter_cache]
add_touch_callbacks(reflection) if options[:touch]
- configure_dependency
reflection
end
- private
+ def add_counter_cache_callbacks(reflection)
+ cache_column = reflection.counter_cache_column
- def add_counter_cache_callbacks(reflection)
- cache_column = reflection.counter_cache_column
- name = self.name
-
- method_name = "belongs_to_counter_cache_after_create_for_#{name}"
- mixin.redefine_method(method_name) do
- record = send(name)
- record.class.increment_counter(cache_column, record.id) unless record.nil?
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def belongs_to_counter_cache_after_create_for_#{name}
+ record = #{name}
+ record.class.increment_counter(:#{cache_column}, record.id) unless record.nil?
end
- model.after_create(method_name)
- method_name = "belongs_to_counter_cache_before_destroy_for_#{name}"
- mixin.redefine_method(method_name) do
+ def belongs_to_counter_cache_before_destroy_for_#{name}
unless marked_for_destruction?
- record = send(name)
- record.class.decrement_counter(cache_column, record.id) unless record.nil?
+ record = #{name}
+ record.class.decrement_counter(:#{cache_column}, record.id) unless record.nil?
end
end
- model.before_destroy(method_name)
+ CODE
- model.send(:module_eval,
- "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)", __FILE__, __LINE__
- )
- end
+ model.after_create "belongs_to_counter_cache_after_create_for_#{name}"
+ model.before_destroy "belongs_to_counter_cache_before_destroy_for_#{name}"
- def add_touch_callbacks(reflection)
- name = self.name
- method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}"
- touch = options[:touch]
+ klass = reflection.class_name.safe_constantize
+ klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly)
+ end
- mixin.redefine_method(method_name) do
- record = send(name)
+ def add_touch_callbacks(reflection)
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def belongs_to_touch_after_save_or_destroy_for_#{name}
+ record = #{name}
unless record.nil?
- if touch == true
- record.touch
- else
- record.touch(touch)
- end
+ record.touch #{options[:touch].inspect if options[:touch] != true}
end
end
+ CODE
- model.after_save(method_name)
- model.after_touch(method_name)
- model.after_destroy(method_name)
- end
-
- def configure_dependency
- if options[:dependent]
- unless options[:dependent].in?([:destroy, :delete])
- raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{options[:dependent].inspect})"
- end
+ model.after_save "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ model.after_touch "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ model.after_destroy "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ end
- method_name = "belongs_to_dependent_#{options[:dependent]}_for_#{name}"
- model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
- def #{method_name}
- association = #{name}
- association.#{options[:dependent]} if association
- end
- eoruby
- model.after_destroy method_name
- end
- end
+ def valid_dependent_options
+ [:destroy, :delete]
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb
index 768f70b6c9..1b382f7285 100644
--- a/activerecord/lib/active_record/associations/builder/collection_association.rb
+++ b/activerecord/lib/active_record/associations/builder/collection_association.rb
@@ -2,23 +2,19 @@ module ActiveRecord::Associations::Builder
class CollectionAssociation < Association #:nodoc:
CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
- self.valid_options += [
- :table_name, :order, :group, :having, :limit, :offset, :uniq, :finder_sql,
- :counter_sql, :before_add, :after_add, :before_remove, :after_remove
- ]
-
- attr_reader :block_extension
-
- def self.build(model, name, options, &extension)
- new(model, name, options, &extension).build
+ def valid_options
+ super + [:table_name, :finder_sql, :counter_sql, :before_add, :after_add, :before_remove, :after_remove]
end
- def initialize(model, name, options, &extension)
- super(model, name, options)
+ attr_reader :block_extension, :extension_module
+
+ def initialize(*args, &extension)
+ super(*args)
@block_extension = extension
end
def build
+ show_deprecation_warnings
wrap_block_extension
reflection = super
CALLBACKS.each { |callback_name| define_callback(callback_name) }
@@ -29,47 +25,61 @@ module ActiveRecord::Associations::Builder
true
end
- private
+ def show_deprecation_warnings
+ [:finder_sql, :counter_sql].each do |name|
+ if options.include? name
+ ActiveSupport::Deprecation.warn("The :#{name} association option is deprecated. Please find an alternative (such as using scopes).")
+ end
+ end
+ end
+
+ def wrap_block_extension
+ if block_extension
+ @extension_module = mod = Module.new(&block_extension)
+ silence_warnings do
+ model.parent.const_set(extension_module_name, mod)
+ end
- def wrap_block_extension
- options[:extend] = Array(options[:extend])
+ prev_scope = @scope
- if block_extension
- silence_warnings do
- model.parent.const_set(extension_module_name, Module.new(&block_extension))
- end
- options[:extend].push("#{model.parent}::#{extension_module_name}".constantize)
+ if prev_scope
+ @scope = proc { |owner| instance_exec(owner, &prev_scope).extending(mod) }
+ else
+ @scope = proc { extending(mod) }
end
end
+ end
- def extension_module_name
- @extension_module_name ||= "#{model.to_s.demodulize}#{name.to_s.camelize}AssociationExtension"
- end
+ def extension_module_name
+ @extension_module_name ||= "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
+ end
- def define_callback(callback_name)
- full_callback_name = "#{callback_name}_for_#{name}"
+ def define_callback(callback_name)
+ full_callback_name = "#{callback_name}_for_#{name}"
- # TODO : why do i need method_defined? I think its because of the inheritance chain
- model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
- model.send("#{full_callback_name}=", Array(options[callback_name.to_sym]))
- end
+ # TODO : why do i need method_defined? I think its because of the inheritance chain
+ model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
+ model.send("#{full_callback_name}=", Array(options[callback_name.to_sym]))
+ end
- def define_readers
- super
+ def define_readers
+ super
- name = self.name
- mixin.redefine_method("#{name.to_s.singularize}_ids") do
- association(name).ids_reader
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name.to_s.singularize}_ids
+ association(:#{name}).ids_reader
end
- end
+ CODE
+ end
- def define_writers
- super
+ def define_writers
+ super
- name = self.name
- mixin.redefine_method("#{name.to_s.singularize}_ids=") do |ids|
- association(name).ids_writer(ids)
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name.to_s.singularize}_ids=(ids)
+ association(:#{name}).ids_writer(ids)
end
- end
+ CODE
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
index f7656ecd47..bdac02b5bf 100644
--- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
+++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
@@ -1,8 +1,12 @@
module ActiveRecord::Associations::Builder
class HasAndBelongsToMany < CollectionAssociation #:nodoc:
- self.macro = :has_and_belongs_to_many
+ def macro
+ :has_and_belongs_to_many
+ end
- self.valid_options += [:join_table, :association_foreign_key, :delete_sql, :insert_sql]
+ def valid_options
+ super + [:join_table, :association_foreign_key, :delete_sql, :insert_sql]
+ end
def build
reflection = super
@@ -10,18 +14,26 @@ module ActiveRecord::Associations::Builder
reflection
end
- private
+ def show_deprecation_warnings
+ super
- def define_destroy_hook
- name = self.name
- model.send(:include, Module.new {
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def destroy_associations
- association(#{name.to_sym.inspect}).delete_all
- super
- end
- RUBY
- })
+ [:delete_sql, :insert_sql].each do |name|
+ if options.include? name
+ ActiveSupport::Deprecation.warn("The :#{name} association option is deprecated. Please find an alternative (such as using has_many :through).")
+ end
end
+ end
+
+ def define_destroy_hook
+ name = self.name
+ model.send(:include, Module.new {
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def destroy_associations
+ association(:#{name}).delete_all
+ super
+ end
+ RUBY
+ })
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb
index d37d4e9d33..ab8225460a 100644
--- a/activerecord/lib/active_record/associations/builder/has_many.rb
+++ b/activerecord/lib/active_record/associations/builder/has_many.rb
@@ -1,60 +1,15 @@
-require 'active_support/core_ext/object/inclusion'
-
module ActiveRecord::Associations::Builder
class HasMany < CollectionAssociation #:nodoc:
- self.macro = :has_many
-
- self.valid_options += [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of]
-
- def build
- reflection = super
- configure_dependency
- reflection
+ def macro
+ :has_many
end
- private
-
- def configure_dependency
- if options[:dependent]
- unless options[:dependent].in?([:destroy, :delete_all, :nullify, :restrict])
- raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
- ":nullify or :restrict (#{options[:dependent].inspect})"
- end
-
- dependent_restrict_deprecation_warning if options[:dependent] == :restrict
- send("define_#{options[:dependent]}_dependency_method")
- model.before_destroy dependency_method_name
- end
- end
-
- def define_destroy_dependency_method
- name = self.name
- mixin.redefine_method(dependency_method_name) do
- send(name).each do |o|
- # No point in executing the counter update since we're going to destroy the parent anyway
- o.mark_for_destruction
- end
-
- send(name).delete_all
- end
- end
-
- def define_delete_all_dependency_method
- name = self.name
- mixin.redefine_method(dependency_method_name) do
- association(name).delete_all
- end
- end
-
- def define_nullify_dependency_method
- name = self.name
- mixin.redefine_method(dependency_method_name) do
- send(name).delete_all
- end
- end
+ def valid_options
+ super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of]
+ end
- def dependency_method_name
- "has_many_dependent_for_#{name}"
- end
+ def valid_dependent_options
+ [:destroy, :delete_all, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb
index bc8a212bee..0da564f402 100644
--- a/activerecord/lib/active_record/associations/builder/has_one.rb
+++ b/activerecord/lib/active_record/associations/builder/has_one.rb
@@ -1,56 +1,25 @@
-require 'active_support/core_ext/object/inclusion'
-
module ActiveRecord::Associations::Builder
class HasOne < SingularAssociation #:nodoc:
- self.macro = :has_one
-
- self.valid_options += [:order, :as]
+ def macro
+ :has_one
+ end
- class_attribute :through_options
- self.through_options = [:through, :source, :source_type]
+ def valid_options
+ valid = super + [:order, :as]
+ valid += [:through, :source, :source_type] if options[:through]
+ valid
+ end
def constructable?
!options[:through]
end
- def build
- reflection = super
- configure_dependency unless options[:through]
- reflection
+ def configure_dependency
+ super unless options[:through]
end
- private
-
- def validate_options
- valid_options = self.class.valid_options
- valid_options += self.class.through_options if options[:through]
- options.assert_valid_keys(valid_options)
- end
-
- def configure_dependency
- if options[:dependent]
- unless options[:dependent].in?([:destroy, :delete, :nullify, :restrict])
- raise ArgumentError, "The :dependent option expects either :destroy, :delete, " \
- ":nullify or :restrict (#{options[:dependent].inspect})"
- end
-
- dependent_restrict_deprecation_warning if options[:dependent] == :restrict
- send("define_#{options[:dependent]}_dependency_method")
- model.before_destroy dependency_method_name
- end
- end
-
- def define_destroy_dependency_method
- name = self.name
- mixin.redefine_method(dependency_method_name) do
- association(name).delete
- end
- end
- alias :define_delete_dependency_method :define_destroy_dependency_method
- alias :define_nullify_dependency_method :define_destroy_dependency_method
-
- def dependency_method_name
- "has_one_dependent_#{options[:dependent]}_for_#{name}"
- end
+ def valid_dependent_options
+ [:destroy, :delete, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb
index 436b6c1524..6a5830e57f 100644
--- a/activerecord/lib/active_record/associations/builder/singular_association.rb
+++ b/activerecord/lib/active_record/associations/builder/singular_association.rb
@@ -1,6 +1,8 @@
module ActiveRecord::Associations::Builder
class SingularAssociation < Association #:nodoc:
- self.valid_options += [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]
+ def valid_options
+ super + [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]
+ end
def constructable?
true
@@ -11,22 +13,20 @@ module ActiveRecord::Associations::Builder
define_constructors if constructable?
end
- private
-
- def define_constructors
- name = self.name
-
- mixin.redefine_method("build_#{name}") do |*params, &block|
- association(name).build(*params, &block)
+ def define_constructors
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def build_#{name}(*args, &block)
+ association(:#{name}).build(*args, &block)
end
- mixin.redefine_method("create_#{name}") do |*params, &block|
- association(name).create(*params, &block)
+ def create_#{name}(*args, &block)
+ association(:#{name}).create(*args, &block)
end
- mixin.redefine_method("create_#{name}!") do |*params, &block|
- association(name).create!(*params, &block)
+ def create_#{name}!(*args, &block)
+ association(:#{name}).create!(*args, &block)
end
- end
+ CODE
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 2f6ddfeeb3..b15df4f308 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -50,7 +50,7 @@ module ActiveRecord
end
else
column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
- scoped.pluck(column)
+ scope.pluck(column)
end
end
@@ -71,7 +71,7 @@ module ActiveRecord
if block_given?
load_target.select.each { |e| yield e }
else
- scoped.select(select)
+ scope.select(select)
end
end
@@ -82,7 +82,7 @@ module ActiveRecord
if options[:finder_sql]
find_by_scan(*args)
else
- scoped.find(*args)
+ scope.find(*args)
end
end
end
@@ -164,9 +164,9 @@ module ActiveRecord
# Calculate sum using SQL, not Enumerable.
def sum(*args)
if block_given?
- scoped.sum(*args) { |*block_args| yield(*block_args) }
+ scope.sum(*args) { |*block_args| yield(*block_args) }
else
- scoped.sum(*args)
+ scope.sum(*args)
end
end
@@ -183,13 +183,13 @@ module ActiveRecord
reflection.klass.count_by_sql(custom_counter_sql)
else
- if options[:uniq]
+ if association_scope.uniq_value
# This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
column_name ||= reflection.klass.primary_key
count_options[:distinct] = true
end
- value = scoped.count(column_name, count_options)
+ value = scope.count(column_name, count_options)
limit = options[:limit]
offset = options[:offset]
@@ -246,14 +246,14 @@ module ActiveRecord
# +count_records+, which is a method descendants have to provide.
def size
if !find_target? || loaded?
- if options[:uniq]
+ if association_scope.uniq_value
target.uniq.size
else
target.size
end
- elsif !loaded? && options[:group]
+ elsif !loaded? && !association_scope.group_values.empty?
load_target.size
- elsif !loaded? && !options[:uniq] && target.is_a?(Array)
+ elsif !loaded? && !association_scope.uniq_value && target.is_a?(Array)
unsaved_records = target.select { |r| r.new_record? }
unsaved_records.size + count_records
else
@@ -270,12 +270,20 @@ module ActiveRecord
load_target.size
end
- # Returns true if the collection is empty. Equivalent to
- # <tt>collection.size.zero?</tt>. If the collection has not been already
+ # Returns true if the collection is empty.
+ #
+ # If the collection has been loaded or the <tt>:counter_sql</tt> option
+ # is provided, it is equivalent to <tt>collection.size.zero?</tt>. If the
+ # collection has not been loaded, it is equivalent to
+ # <tt>collection.exists?</tt>. If the collection has not already been
# loaded and you are going to fetch the records anyway it is better to
# check <tt>collection.length.zero?</tt>.
def empty?
- size.zero?
+ if loaded? || options[:counter_sql]
+ size.zero?
+ else
+ !scope.exists?
+ end
end
# Returns true if the collections is not empty.
@@ -298,9 +306,9 @@ module ActiveRecord
end
end
- def uniq(collection = load_target)
+ def uniq
seen = {}
- collection.find_all do |record|
+ load_target.find_all do |record|
seen[record.id] = true unless seen.key?(record.id)
end
end
@@ -324,7 +332,7 @@ module ActiveRecord
include_in_memory?(record)
else
load_target if options[:finder_sql]
- loaded? ? target.include?(record) : scoped.exists?(record)
+ loaded? ? target.include?(record) : scope.exists?(record)
end
else
false
@@ -344,7 +352,7 @@ module ActiveRecord
callback(:before_add, record)
yield(record) if block_given?
- if options[:uniq] && index = @target.index(record)
+ if association_scope.uniq_value && index = @target.index(record)
@target[index] = record
else
@target << record
@@ -380,10 +388,9 @@ module ActiveRecord
if options[:finder_sql]
reflection.klass.find_by_sql(custom_finder_sql)
else
- scoped.all
+ scope.to_a
end
- records = options[:uniq] ? uniq(records) : records
records.each { |record| set_inverse_instance(record) }
records
end
@@ -441,7 +448,7 @@ module ActiveRecord
end
def create_scope
- scoped.scope_for_create.stringify_keys
+ scope.scope_for_create.stringify_keys
end
def delete_or_destroy(records, method)
@@ -566,8 +573,8 @@ module ActiveRecord
def first_or_last(type, *args)
args.shift if args.first.is_a?(Hash) && args.first.empty?
- collection = fetch_first_or_last_using_find?(args) ? scoped : load_target
- collection.send(type, *args)
+ collection = fetch_first_or_last_using_find?(args) ? scope : load_target
+ collection.send(type, *args).tap {|it| set_inverse_instance it }
end
end
end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 2fb80fdc4c..ee8b816ef4 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -34,15 +34,25 @@ module ActiveRecord
# is computed directly through SQL and does not trigger by itself the
# instantiation of the actual post records.
class CollectionProxy < Relation
- delegate :target, :load_target, :loaded?, :to => :@association
+ def initialize(association) #:nodoc:
+ @association = association
+ super association.klass, association.klass.arel_table
+ merge! association.scope
+ end
+
+ def target
+ @association.target
+ end
+
+ def load_target
+ @association.load_target
+ end
+
+ def loaded?
+ @association.loaded?
+ end
##
- # :method: select
- #
- # :call-seq:
- # select(select = nil)
- # select(&block)
- #
# Works in two ways.
#
# *First:* Specify a subset of fields to be selected from the result set.
@@ -96,13 +106,11 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook">,
# # #<Pet id: 3, name: "Choo-Choo">
# # ]
+ def select(select = nil, &block)
+ @association.select(select, &block)
+ end
##
- # :method: find
- #
- # :call-seq:
- # find(*args, &block)
- #
# Finds an object in the collection responding to the +id+. Uses the same
# rules as +ActiveRecord::Base.find+. Returns +ActiveRecord::RecordNotFound++
# error if the object can not be found.
@@ -129,13 +137,11 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
+ def find(*args, &block)
+ @association.find(*args, &block)
+ end
##
- # :method: first
- #
- # :call-seq:
- # first(limit = nil)
- #
# Returns the first record, or the first +n+ records, from the collection.
# If the collection is empty, the first form returns +nil+, and the second
# form returns an empty array.
@@ -162,13 +168,11 @@ module ActiveRecord
# another_person_without.pets # => []
# another_person_without.pets.first # => nil
# another_person_without.pets.first(3) # => []
+ def first(*args)
+ @association.first(*args)
+ end
##
- # :method: last
- #
- # :call-seq:
- # last(limit = nil)
- #
# Returns the last record, or the last +n+ records, from the collection.
# If the collection is empty, the first form returns +nil+, and the second
# form returns an empty array.
@@ -195,13 +199,11 @@ module ActiveRecord
# another_person_without.pets # => []
# another_person_without.pets.last # => nil
# another_person_without.pets.last(3) # => []
+ def last(*args)
+ @association.last(*args)
+ end
##
- # :method: build
- #
- # :call-seq:
- # build(attributes = {}, options = {}, &block)
- #
# Returns a new object of the collection type that has been instantiated
# with +attributes+ and linked to this object, but have not yet been saved.
# You can pass an array of attributes hashes, this will return an array
@@ -226,13 +228,11 @@ module ActiveRecord
#
# person.pets.size # => 5 # size of the collection
# person.pets.count # => 0 # count from database
+ def build(attributes = {}, options = {}, &block)
+ @association.build(attributes, options, &block)
+ end
##
- # :method: create
- #
- # :call-seq:
- # create(attributes = {}, options = {}, &block)
- #
# Returns a new object of the collection type that has been instantiated with
# attributes, linked to this object and that has already been saved (if it
# passes the validations).
@@ -259,13 +259,11 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
+ def create(attributes = {}, options = {}, &block)
+ @association.create(attributes, options, &block)
+ end
##
- # :method: create!
- #
- # :call-seq:
- # create!(attributes = {}, options = {}, &block)
- #
# Like +create+, except that if the record is invalid, raises an exception.
#
# class Person
@@ -279,13 +277,11 @@ module ActiveRecord
#
# person.pets.create!(name: nil)
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+ def create!(attributes = {}, options = {}, &block)
+ @association.create!(attributes, options, &block)
+ end
##
- # :method: concat
- #
- # :call-seq:
- # concat(*records)
- #
# Add one or more records to the collection by setting their foreign keys
# to the association's primary key. Since << flattens its argument list and
# inserts each record, +push+ and +concat+ behave identically. Returns +self+
@@ -310,13 +306,11 @@ module ActiveRecord
#
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
# person.pets.size # => 5
+ def concat(*records)
+ @association.concat(*records)
+ end
##
- # :method: replace
- #
- # :call-seq:
- # replace(other_array)
- #
# Replace this collection with +other_array+. This will perform a diff
# and delete/add only records that have changed.
#
@@ -339,14 +333,12 @@ module ActiveRecord
#
# person.pets.replace(["doo", "ggie", "gaga"])
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
+ def replace(other_array)
+ @association.replace(other_array)
+ end
##
- # :method: delete_all
- #
- # :call-seq:
- # delete_all()
- #
- # Deletes all the records from the collection. For +has_many+ asssociations,
+ # Deletes all the records from the collection. For +has_many+ associations,
# the deletion is done according to the strategy specified by the <tt>:dependent</tt>
# option. Returns an array with the deleted records.
#
@@ -434,13 +426,11 @@ module ActiveRecord
#
# Pet.find(1, 2, 3)
# # => ActiveRecord::RecordNotFound
+ def delete_all
+ @association.delete_all
+ end
##
- # :method: destroy_all
- #
- # :call-seq:
- # destroy_all()
- #
# Deletes the records of the collection directly from the database.
# This will _always_ remove the records ignoring the +:dependent+
# option.
@@ -463,15 +453,11 @@ module ActiveRecord
# person.pets # => []
#
# Pet.find(1) # => Couldn't find Pet with id=1
+ def destroy_all
+ @association.destroy_all
+ end
##
- # :method: delete
- #
- # :call-seq:
- # delete(*records)
- # delete(*fixnum_ids)
- # delete(*string_ids)
- #
# Deletes the +records+ supplied and removes them from the collection. For
# +has_many+ associations, the deletion is done according to the strategy
# specified by the <tt>:dependent</tt> option. Returns an array with the
@@ -586,13 +572,11 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
+ def delete(*records)
+ @association.delete(*records)
+ end
##
- # :method: destroy
- #
- # :call-seq:
- # destroy(*records)
- #
# Destroys the +records+ supplied and removes them from the collection.
# This method will _always_ remove record from the database ignoring
# the +:dependent+ option. Returns an array with the removed records.
@@ -661,13 +645,11 @@ module ActiveRecord
# person.pets # => []
#
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
+ def destroy(*records)
+ @association.destroy(*records)
+ end
##
- # :method: uniq
- #
- # :call-seq:
- # uniq()
- #
# Specifies whether the records should be unique or not.
#
# class Person < ActiveRecord::Base
@@ -682,13 +664,11 @@ module ActiveRecord
#
# person.pets.select(:name).uniq
# # => [#<Pet name: "Fancy-Fancy">]
+ def uniq
+ @association.uniq
+ end
##
- # :method: count
- #
- # :call-seq:
- # count()
- #
# Count all records using SQL.
#
# class Person < ActiveRecord::Base
@@ -702,13 +682,11 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
+ def count(column_name = nil, options = {})
+ @association.count(column_name, options)
+ end
##
- # :method: size
- #
- # :call-seq:
- # size()
- #
# Returns the size of the collection. If the collection hasn't been loaded,
# it executes a <tt>SELECT COUNT(*)</tt> query.
#
@@ -729,13 +707,11 @@ module ActiveRecord
# person.pets.size # => 3
# # Because the collection is already loaded, this will behave like
# # collection.size and no SQL count query is executed.
+ def size
+ @association.size
+ end
##
- # :method: length
- #
- # :call-seq:
- # length()
- #
# Returns the size of the collection calling +size+ on the target.
# If the collection has been already loaded, +length+ and +size+ are
# equivalent.
@@ -755,10 +731,11 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
+ def length
+ @association.length
+ end
##
- # :method: empty?
- #
# Returns +true+ if the collection is empty.
#
# class Person < ActiveRecord::Base
@@ -772,14 +749,11 @@ module ActiveRecord
#
# person.pets.count # => 0
# person.pets.empty? # => true
+ def empty?
+ @association.empty?
+ end
##
- # :method: any?
- #
- # :call-seq:
- # any?
- # any?{|item| block}
- #
# Returns +true+ if the collection is not empty.
#
# class Person < ActiveRecord::Base
@@ -809,14 +783,11 @@ module ActiveRecord
# pet.group == 'dogs'
# end
# # => true
+ def any?(&block)
+ @association.any?(&block)
+ end
##
- # :method: many?
- #
- # :call-seq:
- # many?
- # many?{|item| block}
- #
# Returns true if the collection has more than one record.
# Equivalent to <tt>collection.size > 1</tt>.
#
@@ -851,13 +822,11 @@ module ActiveRecord
# pet.group == 'cats'
# end
# # => true
+ def many?(&block)
+ @association.many?(&block)
+ end
##
- # :method: include?
- #
- # :call-seq:
- # include?(record)
- #
# Returns +true+ if the given object is present in the collection.
#
# class Person < ActiveRecord::Base
@@ -868,17 +837,8 @@ module ActiveRecord
#
# person.pets.include?(Pet.find(20)) # => true
# person.pets.include?(Pet.find(21)) # => false
- delegate :select, :find, :first, :last,
- :build, :create, :create!,
- :concat, :replace, :delete_all, :destroy_all, :delete, :destroy, :uniq,
- :sum, :count, :size, :length, :empty?,
- :any?, :many?, :include?,
- :to => :@association
-
- def initialize(association) #:nodoc:
- @association = association
- super association.klass, association.klass.arel_table
- merge! association.scoped
+ def include?(record)
+ @association.include?(record)
end
alias_method :new, :build
@@ -892,21 +852,21 @@ module ActiveRecord
# method, which gets the current scope, which is this object, which
# delegates to @association, and so on.
def scoping
- @association.scoped.scoping { yield }
- end
-
- def spawn
- scoped
+ @association.scope.scoping { yield }
end
- def scoped(options = nil)
+ # Returns a <tt>Relation</tt> object for the records in this association
+ def scope
association = @association
- super.extending! do
+ @association.scope.extending! do
define_method(:proxy_association) { association }
end
end
+ # :nodoc:
+ alias spawn scope
+
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
# contain the same number of elements and if each element is equal
# to the corresponding element in the other array, otherwise returns
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index e631579087..74864d271f 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -7,6 +7,28 @@ module ActiveRecord
# is provided by its child HasManyThroughAssociation.
class HasManyAssociation < CollectionAssociation #:nodoc:
+ def handle_dependency
+ case options[:dependent]
+ when :restrict, :restrict_with_exception
+ raise ActiveRecord::DeleteRestrictionError.new(reflection.name) unless empty?
+
+ when :restrict_with_error
+ unless empty?
+ record = klass.human_attribute_name(reflection.name).downcase
+ owner.errors.add(:base, :"restrict_dependent_destroy.many", record: record)
+ false
+ end
+
+ else
+ if options[:dependent] == :destroy
+ # No point in executing the counter update since we're going to destroy the parent anyway
+ load_target.each(&:mark_for_destruction)
+ end
+
+ delete_all
+ end
+ end
+
def insert_record(record, validate = true, raise = false)
set_owner_attributes(record)
@@ -38,7 +60,7 @@ module ActiveRecord
elsif options[:counter_sql] || options[:finder_sql]
reflection.klass.count_by_sql(custom_counter_sql)
else
- scoped.count
+ scope.count
end
# If there's nothing in the database and @target has no new records
@@ -46,7 +68,7 @@ module ActiveRecord
# documented side-effect of the method that may avoid an extra SELECT.
@target ||= [] and loaded! if count == 0
- [options[:limit], count].compact.min
+ [association_scope.limit_value, count].compact.min
end
def has_cached_counter?(reflection = reflection)
@@ -90,10 +112,10 @@ module ActiveRecord
update_counter(-records.length) unless inverse_updates_counter_cache?
else
if records == :all
- scope = scoped
+ scope = self.scope
else
keys = records.map { |r| r[reflection.association_primary_key] }
- scope = scoped.where(reflection.association_primary_key => keys)
+ scope = self.scope.where(reflection.association_primary_key => keys)
end
if method == :delete_all
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index 2683aaf5da..88ff11f953 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActiveRecord
# = Active Record Has Many Through Association
@@ -126,7 +125,7 @@ module ActiveRecord
# even when we just want to delete everything.
records = load_target if records == :all
- scope = through_association.scoped
+ scope = through_association.scope
scope.where! construct_join_attributes(*records)
case method
@@ -171,7 +170,7 @@ module ActiveRecord
def find_target
return [] unless target_reflection_has_associated_record?
- scoped.all
+ scope.to_a
end
# NOTE - not sure that we can actually cope with inverses here
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index f0d1120c68..06bead41de 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -1,26 +1,45 @@
-require 'active_support/core_ext/object/inclusion'
module ActiveRecord
# = Active Record Belongs To Has One Association
module Associations
class HasOneAssociation < SingularAssociation #:nodoc:
+
+ def handle_dependency
+ case options[:dependent]
+ when :restrict, :restrict_with_exception
+ raise ActiveRecord::DeleteRestrictionError.new(reflection.name) if load_target
+
+ when :restrict_with_error
+ if load_target
+ record = klass.human_attribute_name(reflection.name).downcase
+ owner.errors.add(:base, :"restrict_dependent_destroy.one", record: record)
+ false
+ end
+
+ else
+ delete
+ end
+ end
+
def replace(record, save = true)
raise_on_type_mismatch(record) if record
load_target
- reflection.klass.transaction do
- if target && target != record
- remove_target!(options[:dependent]) unless target.destroyed?
- end
+ # If target and record are nil, or target is equal to record,
+ # we don't need to have transaction.
+ if (target || record) && target != record
+ reflection.klass.transaction do
+ remove_target!(options[:dependent]) if target && !target.destroyed?
- if record
- set_owner_attributes(record)
- set_inverse_instance(record)
+ if record
+ set_owner_attributes(record)
+ set_inverse_instance(record)
- if owner.persisted? && save && !record.save
- nullify_owner_attributes(record)
- set_owner_attributes(target) if target
- raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
+ if owner.persisted? && save && !record.save
+ nullify_owner_attributes(record)
+ set_owner_attributes(target) if target
+ raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
+ end
end
end
end
@@ -36,7 +55,7 @@ module ActiveRecord
when :destroy
target.destroy
when :nullify
- target.update_column(reflection.foreign_key, nil)
+ target.update_columns(reflection.foreign_key => nil)
end
end
end
@@ -52,16 +71,19 @@ module ActiveRecord
end
def remove_target!(method)
- if method.in?([:delete, :destroy])
- target.send(method)
- else
- nullify_owner_attributes(target)
+ case method
+ when :delete
+ target.delete
+ when :destroy
+ target.destroy
+ else
+ nullify_owner_attributes(target)
- if target.persisted? && owner.persisted? && !target.save
- set_owner_attributes(target)
- raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
- "The record failed to save when after its foreign key was set to nil."
- end
+ if target.persisted? && owner.persisted? && !target.save
+ set_owner_attributes(target)
+ raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
+ "The record failed to save after its foreign key was set to nil."
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
index 0d7d28e458..0d3b4dbab1 100644
--- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb
+++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -92,14 +92,21 @@ module ActiveRecord
constraint = build_constraint(reflection, table, key, foreign_table, foreign_key)
- conditions = self.conditions[i].dup
- conditions << { reflection.type => foreign_klass.base_class.name } if reflection.type
+ scope_chain_items = scope_chain[i]
- conditions.each do |condition|
- condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name)
- condition = Arel.sql(condition) unless condition.is_a?(Arel::Node)
+ if reflection.type
+ scope_chain_items += [
+ ActiveRecord::Relation.new(reflection.klass, table)
+ .where(reflection.type => foreign_klass.base_class.name)
+ ]
+ end
+
+ scope_chain_items.each do |item|
+ unless item.is_a?(Relation)
+ item = ActiveRecord::Relation.new(reflection.klass, table).instance_exec(self, &item)
+ end
- constraint = constraint.and(condition)
+ constraint = constraint.and(item.arel.constraints) unless item.arel.constraints.empty?
end
relation.from(join(table, constraint))
@@ -137,18 +144,8 @@ module ActiveRecord
table.table_alias || table.name
end
- def conditions
- @conditions ||= reflection.conditions.reverse
- end
-
- private
-
- def interpolate(conditions)
- if conditions.respond_to?(:to_proc)
- instance_eval(&conditions)
- else
- conditions
- end
+ def scope_chain
+ @scope_chain ||= reflection.scope_chain.reverse
end
end
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
index 54705e4950..ce5bf15f10 100644
--- a/activerecord/lib/active_record/associations/preloader.rb
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -42,7 +42,7 @@ module ActiveRecord
autoload :HasAndBelongsToMany, 'active_record/associations/preloader/has_and_belongs_to_many'
autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
- attr_reader :records, :associations, :options, :model
+ attr_reader :records, :associations, :preload_scope, :model
# Eager loads the named associations for the given Active Record record(s).
#
@@ -78,15 +78,10 @@ module ActiveRecord
# [ :books, :author ]
# { :author => :avatar }
# [ :books, { :author => :avatar } ]
- #
- # +options+ contains options that will be passed to ActiveRecord::Base#find
- # (which is called under the hood for preloading records). But it is passed
- # only one level deep in the +associations+ argument, i.e. it's not passed
- # to the child associations when +associations+ is a Hash.
- def initialize(records, associations, options = {})
- @records = Array.wrap(records).compact.uniq
- @associations = Array.wrap(associations)
- @options = options
+ def initialize(records, associations, preload_scope = nil)
+ @records = Array.wrap(records).compact.uniq
+ @associations = Array.wrap(associations)
+ @preload_scope = preload_scope || Relation.new(nil, nil)
end
def run
@@ -110,7 +105,7 @@ module ActiveRecord
def preload_hash(association)
association.each do |parent, child|
- Preloader.new(records, parent, options).run
+ Preloader.new(records, parent, preload_scope).run
Preloader.new(records.map { |record| record.send(parent) }.flatten, child).run
end
end
@@ -125,7 +120,7 @@ module ActiveRecord
def preload_one(association)
grouped_records(association).each do |reflection, klasses|
klasses.each do |klass, records|
- preloader_for(reflection).new(klass, records, reflection, options).run
+ preloader_for(reflection).new(klass, records, reflection, preload_scope).run
end
end
end
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index b4c3908b10..cbf5e734ea 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -2,16 +2,16 @@ module ActiveRecord
module Associations
class Preloader
class Association #:nodoc:
- attr_reader :owners, :reflection, :preload_options, :model, :klass
-
- def initialize(klass, owners, reflection, preload_options)
- @klass = klass
- @owners = owners
- @reflection = reflection
- @preload_options = preload_options || {}
- @model = owners.first && owners.first.class
- @scoped = nil
- @owners_by_key = nil
+ attr_reader :owners, :reflection, :preload_scope, :model, :klass
+
+ def initialize(klass, owners, reflection, preload_scope)
+ @klass = klass
+ @owners = owners
+ @reflection = reflection
+ @preload_scope = preload_scope
+ @model = owners.first && owners.first.class
+ @scope = nil
+ @owners_by_key = nil
end
def run
@@ -24,12 +24,12 @@ module ActiveRecord
raise NotImplementedError
end
- def scoped
- @scoped ||= build_scope
+ def scope
+ @scope ||= build_scope
end
def records_for(ids)
- scoped.where(association_key.in(ids))
+ scope.where(association_key.in(ids))
end
def table
@@ -92,34 +92,29 @@ module ActiveRecord
records_by_owner
end
+ def reflection_scope
+ @reflection_scope ||= reflection.scope ? klass.unscoped.instance_exec(nil, &reflection.scope) : klass.unscoped
+ end
+
def build_scope
scope = klass.unscoped
scope.default_scoped = true
- scope = scope.where(interpolate(options[:conditions]))
- scope = scope.where(interpolate(preload_options[:conditions]))
+ values = reflection_scope.values
+ preload_values = preload_scope.values
- scope = scope.select(preload_options[:select] || options[:select] || table[Arel.star])
- scope = scope.includes(preload_options[:include] || options[:include])
+ scope.where_values = Array(values[:where]) + Array(preload_values[:where])
+ scope.references_values = Array(values[:references]) + Array(preload_values[:references])
+
+ scope.select! preload_values[:select] || values[:select] || table[Arel.star]
+ scope.includes! preload_values[:includes] || values[:includes]
if options[:as]
- scope = scope.where(
- klass.table_name => {
- reflection.type => model.base_class.sti_name
- }
- )
+ scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name })
end
scope
end
-
- def interpolate(conditions)
- if conditions.respond_to?(:to_proc)
- klass.send(:instance_eval, &conditions)
- else
- conditions
- end
- end
end
end
end
diff --git a/activerecord/lib/active_record/associations/preloader/collection_association.rb b/activerecord/lib/active_record/associations/preloader/collection_association.rb
index c248aeaaf6..e6cd35e7a1 100644
--- a/activerecord/lib/active_record/associations/preloader/collection_association.rb
+++ b/activerecord/lib/active_record/associations/preloader/collection_association.rb
@@ -6,7 +6,7 @@ module ActiveRecord
private
def build_scope
- super.order(preload_options[:order] || options[:order])
+ super.order(preload_scope.values[:order] || reflection_scope.values[:order])
end
def preload
diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
index c6e9ede356..9a662d3f53 100644
--- a/activerecord/lib/active_record/associations/preloader/has_many_through.rb
+++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
@@ -6,7 +6,7 @@ module ActiveRecord
def associated_records_by_owner
super.each do |owner, records|
- records.uniq! if options[:uniq]
+ records.uniq! if reflection_scope.uniq_value
end
end
end
diff --git a/activerecord/lib/active_record/associations/preloader/has_one.rb b/activerecord/lib/active_record/associations/preloader/has_one.rb
index 848448bb48..24728e9f01 100644
--- a/activerecord/lib/active_record/associations/preloader/has_one.rb
+++ b/activerecord/lib/active_record/associations/preloader/has_one.rb
@@ -14,7 +14,7 @@ module ActiveRecord
private
def build_scope
- super.order(preload_options[:order] || options[:order])
+ super.order(preload_scope.values[:order] || reflection_scope.values[:order])
end
end
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
index ad6374d09a..1c1ba11c44 100644
--- a/activerecord/lib/active_record/associations/preloader/through_association.rb
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -14,10 +14,7 @@ module ActiveRecord
def associated_records_by_owner
through_records = through_records_by_owner
- ActiveRecord::Associations::Preloader.new(
- through_records.values.flatten,
- source_reflection.name, options
- ).run
+ Preloader.new(through_records.values.flatten, source_reflection.name, reflection_scope).run
through_records.each do |owner, records|
records.map! { |r| r.send(source_reflection.name) }.flatten!
@@ -28,10 +25,7 @@ module ActiveRecord
private
def through_records_by_owner
- ActiveRecord::Associations::Preloader.new(
- owners, through_reflection.name,
- through_options
- ).run
+ Preloader.new(owners, through_reflection.name, through_scope).run
Hash[owners.map do |owner|
through_records = Array.wrap(owner.send(through_reflection.name))
@@ -45,21 +39,22 @@ module ActiveRecord
end]
end
- def through_options
- through_options = {}
+ def through_scope
+ through_scope = through_reflection.klass.unscoped
if options[:source_type]
- through_options[:conditions] = { reflection.foreign_type => options[:source_type] }
+ through_scope.where! reflection.foreign_type => options[:source_type]
else
- if options[:conditions]
- through_options[:include] = options[:include] || options[:source]
- through_options[:conditions] = options[:conditions]
+ unless reflection_scope.where_values.empty?
+ through_scope.includes_values = reflection_scope.values[:includes] || options[:source]
+ through_scope.where_values = reflection_scope.values[:where]
end
- through_options[:order] = options[:order]
+ through_scope.order! reflection_scope.values[:order]
+ through_scope.references! reflection_scope.values[:references]
end
- through_options
+ through_scope
end
end
end
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
index a1a921bcb4..b84cb4922d 100644
--- a/activerecord/lib/active_record/associations/singular_association.rb
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -35,11 +35,11 @@ module ActiveRecord
private
def create_scope
- scoped.scope_for_create.stringify_keys.except(klass.primary_key)
+ scope.scope_for_create.stringify_keys.except(klass.primary_key)
end
def find_target
- scoped.first.tap { |record| set_inverse_instance(record) }
+ scope.first.tap { |record| set_inverse_instance(record) }
end
# Implemented by subclasses
diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb
index be890e5767..b9e014735b 100644
--- a/activerecord/lib/active_record/associations/through_association.rb
+++ b/activerecord/lib/active_record/associations/through_association.rb
@@ -15,7 +15,7 @@ module ActiveRecord
scope = super
chain[1..-1].each do |reflection|
scope = scope.merge(
- reflection.klass.scoped.with_default_scope.
+ reflection.klass.all.with_default_scope.
except(:select, :create_with, :includes, :preload, :joins, :eager_load)
)
end
diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb
index 5b41f72e52..d9989274c8 100644
--- a/activerecord/lib/active_record/attribute_assignment.rb
+++ b/activerecord/lib/active_record/attribute_assignment.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
@@ -85,11 +84,11 @@ module ActiveRecord
def assign_attributes(new_attributes, options = {})
return if new_attributes.blank?
- attributes = new_attributes.stringify_keys
- multi_parameter_attributes = []
+ attributes = new_attributes.stringify_keys
+ multi_parameter_attributes = []
nested_parameter_attributes = []
- previous_options = @mass_assignment_options
- @mass_assignment_options = options
+ previous_options = @mass_assignment_options
+ @mass_assignment_options = options
unless options[:without_protection]
attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role)
@@ -98,23 +97,15 @@ module ActiveRecord
attributes.each do |k, v|
if k.include?("(")
multi_parameter_attributes << [ k, v ]
- elsif respond_to?("#{k}=")
- if v.is_a?(Hash)
- nested_parameter_attributes << [ k, v ]
- else
- send("#{k}=", v)
- end
+ elsif v.is_a?(Hash)
+ nested_parameter_attributes << [ k, v ]
else
- raise(UnknownAttributeError, "unknown attribute: #{k}")
+ _assign_attribute(k, v)
end
end
- # assign any deferred nested attributes after the base attributes have been set
- nested_parameter_attributes.each do |k,v|
- send("#{k}=", v)
- end
-
- assign_multiparameter_attributes(multi_parameter_attributes)
+ assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
+ assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
ensure
@mass_assignment_options = previous_options
end
@@ -131,8 +122,23 @@ module ActiveRecord
private
+ def _assign_attribute(k, v)
+ public_send("#{k}=", v)
+ rescue NoMethodError
+ if respond_to?("#{k}=")
+ raise
+ else
+ raise UnknownAttributeError, "unknown attribute: #{k}"
+ end
+ end
+
+ # Assign any deferred nested attributes after the base attributes have been set.
+ def assign_nested_parameter_attributes(pairs)
+ pairs.each { |k, v| _assign_attribute(k, v) }
+ end
+
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
- # by calling new on the column type or aggregation type object with these parameters.
+ # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum,
@@ -144,19 +150,11 @@ module ActiveRecord
)
end
- def instantiate_time_object(name, values)
- if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name))
- Time.zone.local(*values)
- else
- Time.time_with_datetime_fallback(self.class.default_timezone, *values)
- end
- end
-
def execute_callstack_for_multiparameter_attributes(callstack)
errors = []
callstack.each do |name, values_with_empty_parameters|
begin
- send(name + "=", read_value_from_parameter(name, values_with_empty_parameters))
+ send("#{name}=", MultiparameterAttribute.new(self, name, values_with_empty_parameters).read_value)
rescue => ex
errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name)
end
@@ -167,74 +165,12 @@ module ActiveRecord
end
end
- def read_value_from_parameter(name, values_hash_from_param)
- klass = column_for_attribute(name).klass
- if values_hash_from_param.values.all?{|v|v.nil?}
- nil
- elsif klass == Time
- read_time_parameter_value(name, values_hash_from_param)
- elsif klass == Date
- read_date_parameter_value(name, values_hash_from_param)
- else
- read_other_parameter_value(klass, name, values_hash_from_param)
- end
- end
-
- def read_time_parameter_value(name, values_hash_from_param)
- # If column is a :time (and not :date or :timestamp) there is no need to validate if
- # there are year/month/day fields
- if column_for_attribute(name).type == :time
- # if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
- {1 => 1970, 2 => 1, 3 => 1}.each do |key,value|
- values_hash_from_param[key] ||= value
- end
- else
- # else column is a timestamp, so if Date bits were not provided, error
- if missing_parameter = [1,2,3].detect{ |position| !values_hash_from_param.has_key?(position) }
- raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter}i)")
- end
-
- # If Date bits were provided but blank, then return nil
- return nil if (1..3).any? { |position| values_hash_from_param[position].blank? }
- end
-
- max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param, 6)
- set_values = (1..max_position).collect{ |position| values_hash_from_param[position] }
- # If Time bits are not there, then default to 0
- (3..5).each { |i| set_values[i] = set_values[i].blank? ? 0 : set_values[i] }
- instantiate_time_object(name, set_values)
- end
-
- def read_date_parameter_value(name, values_hash_from_param)
- return nil if (1..3).any? {|position| values_hash_from_param[position].blank?}
- set_values = [values_hash_from_param[1], values_hash_from_param[2], values_hash_from_param[3]]
- begin
- Date.new(*set_values)
- rescue ArgumentError # if Date.new raises an exception on an invalid date
- instantiate_time_object(name, set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
- end
- end
-
- def read_other_parameter_value(klass, name, values_hash_from_param)
- max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param)
- values = (1..max_position).collect do |position|
- raise "Missing Parameter" if !values_hash_from_param.has_key?(position)
- values_hash_from_param[position]
- end
- klass.new(*values)
- end
-
- def extract_max_param_for_multiparameter_attributes(values_hash_from_param, upper_cap = 100)
- [values_hash_from_param.keys.max,upper_cap].min
- end
-
def extract_callstack_for_multiparameter_attributes(pairs)
attributes = { }
- pairs.each do |pair|
- multiparameter_name, value = pair
+ pairs.each do |(multiparameter_name, value)|
attribute_name = multiparameter_name.split("(").first
- attributes[attribute_name] = {} unless attributes.include?(attribute_name)
+ attributes[attribute_name] ||= {}
parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
@@ -251,5 +187,100 @@ module ActiveRecord
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
end
+ class MultiparameterAttribute #:nodoc:
+ attr_reader :object, :name, :values, :column
+
+ def initialize(object, name, values)
+ @object = object
+ @name = name
+ @values = values
+ end
+
+ def read_value
+ return if values.values.compact.empty?
+
+ @column = object.class.reflect_on_aggregation(name.to_sym) || object.column_for_attribute(name)
+ klass = column.klass
+
+ if klass == Time
+ read_time
+ elsif klass == Date
+ read_date
+ else
+ read_other(klass)
+ end
+ end
+
+ private
+
+ def instantiate_time_object(set_values)
+ if object.class.send(:create_time_zone_conversion_attribute?, name, column)
+ Time.zone.local(*set_values)
+ else
+ Time.time_with_datetime_fallback(object.class.default_timezone, *set_values)
+ end
+ end
+
+ def read_time
+ # If column is a :time (and not :date or :timestamp) there is no need to validate if
+ # there are year/month/day fields
+ if column.type == :time
+ # if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
+ { 1 => 1970, 2 => 1, 3 => 1 }.each do |key,value|
+ values[key] ||= value
+ end
+ else
+ # else column is a timestamp, so if Date bits were not provided, error
+ validate_missing_parameters!([1,2,3])
+
+ # If Date bits were provided but blank, then return nil
+ return if blank_date_parameter?
+ end
+
+ max_position = extract_max_param(6)
+ set_values = values.values_at(*(1..max_position))
+ # If Time bits are not there, then default to 0
+ (3..5).each { |i| set_values[i] = set_values[i].presence || 0 }
+ instantiate_time_object(set_values)
+ end
+
+ def read_date
+ return if blank_date_parameter?
+ set_values = values.values_at(1,2,3)
+ begin
+ Date.new(*set_values)
+ rescue ArgumentError # if Date.new raises an exception on an invalid date
+ instantiate_time_object(set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
+ end
+ end
+
+ def read_other(klass)
+ max_position = extract_max_param
+ positions = (1..max_position)
+ validate_missing_parameters!(positions)
+
+ set_values = values.values_at(*positions)
+ klass.new(*set_values)
+ end
+
+ # Checks whether some blank date parameter exists. Note that this is different
+ # than the validate_missing_parameters! method, since it just checks for blank
+ # positions instead of missing ones, and does not raise in case one blank position
+ # exists. The caller is responsible to handle the case of this returning true.
+ def blank_date_parameter?
+ (1..3).any? { |position| values[position].blank? }
+ end
+
+ # If some position is not provided, it errors out a missing parameter exception.
+ def validate_missing_parameters!(positions)
+ if missing_parameter = positions.detect { |position| !values.key?(position) }
+ raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter})")
+ end
+ end
+
+ def extract_max_param(upper_cap = 100)
+ [values.keys.max, upper_cap].min
+ end
+ end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index f36df4a444..ced15bc330 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/enumerable'
-require 'active_support/deprecation'
module ActiveRecord
# = Active Record Attribute Methods
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
index a24b4b7839..60e5b0e2bb 100644
--- a/activerecord/lib/active_record/attribute_methods/dirty.rb
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/attribute_accessors'
module ActiveRecord
@@ -98,7 +96,7 @@ module ActiveRecord
def changes_from_zero_to_string?(old, value)
# For columns with old 0 and value non-empty string
- old == 0 && value.present? && value != '0'
+ old == 0 && value.is_a?(String) && value.present? && value != '0'
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/query.rb b/activerecord/lib/active_record/attribute_methods/query.rb
index 1e841dc8e0..a8b23abb7c 100644
--- a/activerecord/lib/active_record/attribute_methods/query.rb
+++ b/activerecord/lib/active_record/attribute_methods/query.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActiveRecord
module AttributeMethods
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index a7af086e43..1a4cb25dd7 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -8,7 +8,6 @@ module ActiveRecord
extend ActiveSupport::Concern
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
- ActiveRecord::Model.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
included do
config_attribute :attribute_types_cached_by_default
@@ -46,7 +45,7 @@ module ActiveRecord
def define_method_attribute(attr_name)
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
def __temp__
- read_attribute('#{attr_name}') { |n| missing_attribute(n, caller) }
+ read_attribute(:'#{attr_name}') { |n| missing_attribute(n, caller) }
end
alias_method '#{attr_name}', :__temp__
undef_method :__temp__
@@ -64,14 +63,22 @@ module ActiveRecord
end
end
+ ActiveRecord::Model.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
+
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
def read_attribute(attr_name)
+ return unless attr_name
+ name_sym = attr_name.to_sym
+
# If it's cached, just return it
- @attributes_cache.fetch(attr_name.to_s) { |name|
+ # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/3552829.
+ @attributes_cache[name_sym] || @attributes_cache.fetch(name_sym) {
+ name = attr_name.to_s
+
column = @columns_hash.fetch(name) {
return @attributes.fetch(name) {
- if name == 'id' && self.class.primary_key != name
+ if name_sym == :id && self.class.primary_key != name
read_attribute(self.class.primary_key)
end
}
@@ -82,7 +89,7 @@ module ActiveRecord
}
if self.class.cache_attribute?(name)
- @attributes_cache[name] = column.type_cast(value)
+ @attributes_cache[name_sym] = column.type_cast(value)
else
column.type_cast value
end
diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb
index 49ab3ab808..bdda5bc009 100644
--- a/activerecord/lib/active_record/attribute_methods/serialization.rb
+++ b/activerecord/lib/active_record/attribute_methods/serialization.rb
@@ -6,10 +6,46 @@ module ActiveRecord
included do
# Returns a hash of all the attributes that have been specified for serialization as
# keys and their class restriction as values.
- class_attribute :serialized_attributes, instance_writer: false
+ class_attribute :serialized_attributes, instance_accessor: false
self.serialized_attributes = {}
end
+ module ClassMethods
+ # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
+ # then specify the name of that attribute using this method and it will be handled automatically.
+ # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
+ # class on retrieval or SerializationTypeMismatch will be raised.
+ #
+ # ==== Parameters
+ #
+ # * +attr_name+ - The field name that should be serialized.
+ # * +class_name+ - Optional, class name that the object type should be equal to.
+ #
+ # ==== Example
+ # # Serialize a preferences attribute
+ # class User < ActiveRecord::Base
+ # serialize :preferences
+ # end
+ def serialize(attr_name, class_name = Object)
+ include Behavior
+
+ coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
+ class_name
+ else
+ Coders::YAMLColumn.new(class_name)
+ end
+
+ # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
+ # has its own hash of own serialized attributes
+ self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
+ end
+ end
+
+ def serialized_attributes
+ ActiveSupport::Deprecation.warn("Instance level serialized_attributes method is deprecated, please use class level method.")
+ defined?(@serialized_attributes) ? @serialized_attributes : self.class.serialized_attributes
+ end
+
class Type # :nodoc:
def initialize(column)
@column = column
@@ -44,71 +80,50 @@ module ActiveRecord
end
end
- module ClassMethods
- # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
- # then specify the name of that attribute using this method and it will be handled automatically.
- # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
- # class on retrieval or SerializationTypeMismatch will be raised.
- #
- # ==== Parameters
- #
- # * +attr_name+ - The field name that should be serialized.
- # * +class_name+ - Optional, class name that the object type should be equal to.
- #
- # ==== Example
- # # Serialize a preferences attribute
- # class User < ActiveRecord::Base
- # serialize :preferences
- # end
- def serialize(attr_name, class_name = Object)
- coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
- class_name
- else
- Coders::YAMLColumn.new(class_name)
- end
+ # This is only added to the model when serialize is called, which
+ # ensures we do not make things slower when serialization is not used.
+ module Behavior #:nodoc:
+ extend ActiveSupport::Concern
- # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
- # has its own hash of own serialized attributes
- self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
- end
-
- def initialize_attributes(attributes, options = {}) #:nodoc:
- serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
- super(attributes, options)
+ module ClassMethods
+ def initialize_attributes(attributes, options = {})
+ serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
+ super(attributes, options)
- serialized_attributes.each do |key, coder|
- if attributes.key?(key)
- attributes[key] = Attribute.new(coder, attributes[key], serialized)
+ serialized_attributes.each do |key, coder|
+ if attributes.key?(key)
+ attributes[key] = Attribute.new(coder, attributes[key], serialized)
+ end
end
+
+ attributes
end
- attributes
- end
+ private
- private
+ def attribute_cast_code(attr_name)
+ if serialized_attributes.include?(attr_name)
+ "v.unserialized_value"
+ else
+ super
+ end
+ end
+ end
- def attribute_cast_code(attr_name)
- if serialized_attributes.include?(attr_name)
- "v.unserialized_value"
+ def type_cast_attribute_for_write(column, value)
+ if column && coder = self.class.serialized_attributes[column.name]
+ Attribute.new(coder, value, :unserialized)
else
super
end
end
- end
-
- def type_cast_attribute_for_write(column, value)
- if column && coder = self.class.serialized_attributes[column.name]
- Attribute.new(coder, value, :unserialized)
- else
- super
- end
- end
- def read_attribute_before_type_cast(attr_name)
- if serialized_attributes.include?(attr_name)
- super.unserialized_value
- else
- super
+ def read_attribute_before_type_cast(attr_name)
+ if self.class.serialized_attributes.include?(attr_name)
+ super.unserialized_value
+ else
+ super
+ end
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index e300c9721f..9647d03be4 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/inclusion'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
@@ -61,11 +59,14 @@ module ActiveRecord
unless time.acts_like?(:time)
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end
- time = time.in_time_zone rescue nil if time
- changed = read_attribute(:#{attr_name}) != time
- write_attribute(:#{attr_name}, original_time)
- #{attr_name}_will_change! if changed
- @attributes_cache["#{attr_name}"] = time
+ zoned_time = time && time.in_time_zone rescue nil
+ rounded_time = round_usec(zoned_time)
+ rounded_value = round_usec(read_attribute("#{attr_name}"))
+ if (rounded_value != rounded_time) || (!rounded_value && original_time)
+ write_attribute("#{attr_name}", original_time)
+ #{attr_name}_will_change!
+ @attributes_cache[:"#{attr_name}"] = zoned_time
+ end
end
EOV
generated_attribute_methods.module_eval(method_body, __FILE__, line)
@@ -81,6 +82,12 @@ module ActiveRecord
[:datetime, :timestamp].include?(column.type)
end
end
+
+ private
+ def round_usec(value)
+ return unless value
+ value.change(:usec => 0)
+ end
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb
index 50435921b1..5a39cb0125 100644
--- a/activerecord/lib/active_record/attribute_methods/write.rb
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -25,13 +25,13 @@ module ActiveRecord
def write_attribute(attr_name, value)
attr_name = attr_name.to_s
attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
- @attributes_cache.delete(attr_name)
+ @attributes_cache.delete(attr_name.to_sym)
column = column_for_attribute(attr_name)
# If we're dealing with a binary column, write the data to the cache
# so we don't attempt to typecast multiple times.
if column && column.binary?
- @attributes_cache[attr_name] = value
+ @attributes_cache[attr_name.to_sym] = value
end
if column || @attributes.has_key?(attr_name)
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index d545e7799d..290f57659d 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -127,23 +127,17 @@ module ActiveRecord
module AutosaveAssociation
extend ActiveSupport::Concern
- ASSOCIATION_TYPES = %w{ HasOne HasMany BelongsTo HasAndBelongsToMany }
-
module AssociationBuilderExtension #:nodoc:
- def self.included(base)
- base.valid_options << :autosave
- end
-
def build
- reflection = super
model.send(:add_autosave_association_callbacks, reflection)
- reflection
+ super
end
end
included do
- ASSOCIATION_TYPES.each do |type|
- Associations::Builder.const_get(type).send(:include, AssociationBuilderExtension)
+ Associations::Builder::Association.class_eval do
+ self.valid_options << :autosave
+ include AssociationBuilderExtension
end
end
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 189985b671..a4705b24ca 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -4,7 +4,6 @@ require 'active_support/benchmarkable'
require 'active_support/dependencies'
require 'active_support/descendants_tracker'
require 'active_support/time'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/class/delegating_attributes'
require 'active_support/core_ext/array/extract_options'
@@ -13,11 +12,8 @@ require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/string/behavior'
require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/object/duplicable'
-require 'active_support/core_ext/object/blank'
-require 'active_support/deprecation'
require 'arel'
require 'active_record/errors'
require 'active_record/log_subscriber'
@@ -329,4 +325,4 @@ module ActiveRecord #:nodoc:
end
end
-ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Model::DeprecationProxy)
+ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Model::DeprecationProxy.new)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index 347d794fa3..7a3d9bfd3e 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -496,40 +496,40 @@ module ActiveRecord
# ActiveRecord::Base.connection_handler. Active Record models use this to
# determine that connection pool that they should use.
class ConnectionHandler
- def initialize(pools = Hash.new { |h,k| h[k] = {} })
- @connection_pools = pools
- @class_to_pool = Hash.new { |h,k| h[k] = {} }
+ def initialize
+ @owner_to_pool = Hash.new { |h,k| h[k] = {} }
+ @class_to_pool = Hash.new { |h,k| h[k] = {} }
end
def connection_pools
- @connection_pools[Process.pid]
+ owner_to_pool.values.compact
end
- def establish_connection(name, spec)
- set_pool_for_spec spec, ConnectionAdapters::ConnectionPool.new(spec)
- set_class_to_pool name, connection_pools[spec]
+ def establish_connection(owner, spec)
+ @class_to_pool.clear
+ owner_to_pool[owner] = ConnectionAdapters::ConnectionPool.new(spec)
end
# Returns true if there are any active connections among the connection
# pools that the ConnectionHandler is managing.
def active_connections?
- connection_pools.values.any? { |pool| pool.active_connection? }
+ connection_pools.any?(&:active_connection?)
end
# Returns any connections in use by the current thread back to the pool,
# and also returns connections to the pool cached by threads that are no
# longer alive.
def clear_active_connections!
- connection_pools.each_value {|pool| pool.release_connection }
+ connection_pools.each(&:release_connection)
end
# Clears the cache which maps classes.
def clear_reloadable_connections!
- connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
+ connection_pools.each(&:clear_reloadable_connections!)
end
def clear_all_connections!
- connection_pools.each_value {|pool| pool.disconnect! }
+ connection_pools.each(&:disconnect!)
end
# Locate the connection of the nearest super class. This can be an
@@ -552,56 +552,62 @@ module ActiveRecord
# connection and the defined connection (if they exist). The result
# can be used as an argument for establish_connection, for easily
# re-establishing the connection.
- def remove_connection(klass)
- pool = class_to_pool.delete(klass.name)
- return nil unless pool
-
- connection_pools.delete pool.spec
- pool.automatic_reconnect = false
- pool.disconnect!
- pool.spec.config
+ def remove_connection(owner)
+ if pool = owner_to_pool.delete(owner)
+ @class_to_pool.clear
+ pool.automatic_reconnect = false
+ pool.disconnect!
+ pool.spec.config
+ end
end
+ # Retrieving the connection pool happens a lot so we cache it in @class_to_pool.
+ # This makes retrieving the connection pool O(1) once the process is warm.
+ # When a connection is established or removed, we invalidate the cache.
+ #
+ # Ideally we would use #fetch here, as class_to_pool[klass] may sometimes be nil.
+ # However, benchmarking (https://gist.github.com/3552829) showed that #fetch is
+ # significantly slower than #[]. So in the nil case, no caching will take place,
+ # but that's ok since the nil case is not the common one that we wish to optimise
+ # for.
def retrieve_connection_pool(klass)
- if !(klass < Model::Tag)
- get_pool_for_class('ActiveRecord::Model') # default connection
- else
- pool = get_pool_for_class(klass.name)
- pool || retrieve_connection_pool(klass.superclass)
+ class_to_pool[klass] ||= begin
+ until pool = pool_for(klass)
+ klass = klass.superclass
+ break unless klass < Model::Tag
+ end
+
+ class_to_pool[klass] = pool || pool_for(ActiveRecord::Model)
end
end
private
- def class_to_pool
- @class_to_pool[Process.pid]
- end
-
- def set_pool_for_spec(spec, pool)
- @connection_pools[Process.pid][spec] = pool
+ def owner_to_pool
+ @owner_to_pool[Process.pid]
end
- def set_class_to_pool(name, pool)
- @class_to_pool[Process.pid][name] = pool
- pool
+ def class_to_pool
+ @class_to_pool[Process.pid]
end
- def get_pool_for_class(klass)
- @class_to_pool[Process.pid].fetch(klass) {
- c_to_p = @class_to_pool.values.find { |class_to_pool|
- class_to_pool[klass]
- }
-
- if c_to_p
- pool = c_to_p[klass]
- pool = ConnectionAdapters::ConnectionPool.new pool.spec
- set_pool_for_spec pool.spec, pool
- set_class_to_pool klass, pool
+ def pool_for(owner)
+ owner_to_pool.fetch(owner) {
+ if ancestor_pool = pool_from_any_process_for(owner)
+ # A connection was established in an ancestor process that must have
+ # subsequently forked. We can't reuse the connection, but we can copy
+ # the specification and establish a new connection with it.
+ establish_connection owner, ancestor_pool.spec
else
- set_class_to_pool klass, nil
+ owner_to_pool[owner] = nil
end
}
end
+
+ def pool_from_any_process_for(owner)
+ owner_to_pool = @owner_to_pool.values.find { |v| v[owner] }
+ owner_to_pool && owner_to_pool[owner]
+ end
end
class ConnectionManagement
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index b0b51f540c..4e1f0e1d62 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -1,6 +1,12 @@
module ActiveRecord
module ConnectionAdapters # :nodoc:
module DatabaseStatements
+ def initialize
+ super
+ @_current_transaction_records = []
+ @transaction_joinable = nil
+ end
+
# Converts an arel AST to SQL
def to_sql(arel, binds = [])
if arel.respond_to?(:ast)
@@ -167,31 +173,23 @@ module ActiveRecord
def transaction(options = {})
options.assert_valid_keys :requires_new, :joinable
- last_transaction_joinable = defined?(@transaction_joinable) ? @transaction_joinable : nil
- if options.has_key?(:joinable)
- @transaction_joinable = options[:joinable]
- else
- @transaction_joinable = true
- end
- requires_new = options[:requires_new] || !last_transaction_joinable
-
- transaction_open = false
- @_current_transaction_records ||= []
+ last_transaction_joinable = @transaction_joinable
+ @transaction_joinable = options.fetch(:joinable, true)
+ requires_new = options[:requires_new] || !last_transaction_joinable
+ transaction_open = false
begin
- if block_given?
- if requires_new || open_transactions == 0
- if open_transactions == 0
- begin_db_transaction
- elsif requires_new
- create_savepoint
- end
- increment_open_transactions
- transaction_open = true
- @_current_transaction_records.push([])
+ if requires_new || open_transactions == 0
+ if open_transactions == 0
+ begin_db_transaction
+ elsif requires_new
+ create_savepoint
end
- yield
+ increment_open_transactions
+ transaction_open = true
+ @_current_transaction_records.push([])
end
+ yield
rescue Exception => database_transaction_rollback
if transaction_open && !outside_transaction?
transaction_open = false
@@ -225,7 +223,7 @@ module ActiveRecord
@_current_transaction_records.last.concat(save_point_records)
end
end
- rescue Exception => database_transaction_rollback
+ rescue Exception
if open_transactions == 0
rollback_db_transaction
rollback_transaction_records(true)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
index a6e16da730..be6fda95b4 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
@@ -65,6 +65,7 @@ module ActiveRecord
end
private
+
def cache_sql(sql, binds)
result =
if @query_cache[sql].key?(binds)
@@ -85,11 +86,7 @@ module ActiveRecord
end
def locked?(arel)
- if arel.respond_to?(:locked)
- arel.locked
- else
- false
- end
+ arel.respond_to?(:locked) && arel.locked
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index ef17dfbbc5..dca355aa93 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'date'
require 'set'
require 'bigdecimal'
@@ -271,7 +270,7 @@ module ActiveRecord
# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
# <tt>:updated_at</tt> to the table.
def timestamps(*args)
- options = { :null => false }.merge(args.extract_options!)
+ options = args.extract_options!
column(:created_at, :datetime, options)
column(:updated_at, :datetime, options)
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index 65c7ef0153..86d6266af9 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -1,4 +1,3 @@
-require 'active_support/deprecation/reporting'
require 'active_record/migration/join_table'
module ActiveRecord
@@ -57,7 +56,6 @@ module ActiveRecord
# Checks to see if a column exists in a given table.
#
- # === Examples
# # Check a column exists
# column_exists?(:suppliers, :name)
#
@@ -65,7 +63,10 @@ module ActiveRecord
# column_exists?(:suppliers, :name, :string)
#
# # Check a column exists with a specific definition
- # column_exists?(:suppliers, :name, :string, :limit => 100)
+ # column_exists?(:suppliers, :name, :string, limit: 100)
+ # column_exists?(:suppliers, :name, :string, default: 'default')
+ # column_exists?(:suppliers, :name, :string, null: false)
+ # column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)
def column_exists?(table_name, column_name, type = nil, options = {})
columns(table_name).any?{ |c| c.name == column_name.to_s &&
(!type || c.type == type) &&
@@ -202,11 +203,14 @@ module ActiveRecord
join_table_name = find_join_table_name(table_1, table_2, options)
column_options = options.delete(:column_options) || {}
- column_options.reverse_merge!({:null => false})
+ column_options.reverse_merge!(null: false)
- create_table(join_table_name, options.merge!(:id => false)) do |td|
- td.integer :"#{table_1.to_s.singularize}_id", column_options
- td.integer :"#{table_2.to_s.singularize}_id", column_options
+ t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
+
+ create_table(join_table_name, options.merge!(id: false)) do |td|
+ td.integer t1_column, column_options
+ td.integer t2_column, column_options
+ yield td if block_given?
end
end
@@ -485,7 +489,7 @@ module ActiveRecord
def dump_schema_information #:nodoc:
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
- ActiveRecord::SchemaMigration.order('version').all.map { |sm|
+ ActiveRecord::SchemaMigration.order('version').map { |sm|
"INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
}.join "\n\n"
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 28a9821913..b3f9187429 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -2,7 +2,6 @@ require 'date'
require 'bigdecimal'
require 'bigdecimal/util'
require 'active_support/core_ext/benchmark'
-require 'active_support/deprecation'
require 'active_record/connection_adapters/schema_cache'
require 'monitor'
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
index df4a9d5afc..1126fe7fce 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'arel/visitors/bind_visitor'
module ActiveRecord
@@ -318,7 +317,7 @@ module ActiveRecord
select_all(sql, 'SCHEMA').map { |table|
table.delete('Table_type')
sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}"
- exec_without_stmt(sql, 'SCHEMA').first['Create Table'] + ";\n\n"
+ exec_query(sql, 'SCHEMA').first['Create Table'] + ";\n\n"
}.join
end
diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb
index 01bd3ae26c..1445bb3b2f 100644
--- a/activerecord/lib/active_record/connection_adapters/column.rb
+++ b/activerecord/lib/active_record/connection_adapters/column.rb
@@ -1,5 +1,4 @@
require 'set'
-require 'active_support/deprecation'
module ActiveRecord
# :stopdoc:
@@ -209,7 +208,7 @@ module ActiveRecord
# '0.123456' -> 123456
# '1.123456' -> 123456
def microseconds(time)
- ((time[:sec_fraction].to_f % 1) * 1_000_000).to_i
+ time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
end
def new_date(year, mon, mday)
@@ -234,7 +233,7 @@ module ActiveRecord
# Doesn't handle time zones.
def fast_string_to_time(string)
if string =~ Format::ISO_DATETIME
- microsec = ($7.to_f * 1_000_000).to_i
+ microsec = ($7.to_r * 1_000_000).to_i
new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index 0b6734b010..6bf7af081f 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -215,7 +215,7 @@ module ActiveRecord
def select_rows(sql, name = nil)
@connection.query_with_result = true
- rows = exec_without_stmt(sql, name).rows
+ rows = exec_query(sql, name).rows
@connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
rows
end
@@ -279,31 +279,164 @@ module ActiveRecord
end
def exec_query(sql, name = 'SQL', binds = [])
- log(sql, name, binds) do
- exec_stmt(sql, name, binds) do |cols, stmt|
- ActiveRecord::Result.new(cols, stmt.to_a) if cols
- end
+ # If the configuration sets prepared_statements:false, binds will
+ # always be empty, since the bind variables will have been already
+ # substituted and removed from binds by BindVisitor, so this will
+ # effectively disable prepared statement usage completely.
+ if binds.empty?
+ result_set, affected_rows = exec_without_stmt(sql, name)
+ else
+ result_set, affected_rows = exec_stmt(sql, name, binds)
end
+
+ yield affected_rows if block_given?
+
+ result_set
end
def last_inserted_id(result)
@connection.insert_id
end
+ module Fields
+ class Type
+ def type; end
+
+ def type_cast_for_write(value)
+ value
+ end
+ end
+
+ class Identity < Type
+ def type_cast(value); value; end
+ end
+
+ class Integer < Type
+ def type_cast(value)
+ return if value.nil?
+
+ value.to_i rescue value ? 1 : 0
+ end
+ end
+
+ class Date < Type
+ def type; :date; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is mysql
+ # specific
+ ConnectionAdapters::Column.value_to_date value
+ end
+ end
+
+ class DateTime < Type
+ def type; :datetime; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is mysql
+ # specific
+ ConnectionAdapters::Column.string_to_time value
+ end
+ end
+
+ class Time < Type
+ def type; :time; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is mysql
+ # specific
+ ConnectionAdapters::Column.string_to_dummy_time value
+ end
+ end
+
+ class Float < Type
+ def type; :float; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ value.to_f
+ end
+ end
+
+ class Decimal < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_decimal value
+ end
+ end
+
+ class Boolean < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_boolean value
+ end
+ end
+
+ TYPES = {}
+
+ # Register an MySQL +type_id+ with a typcasting object in
+ # +type+.
+ def self.register_type(type_id, type)
+ TYPES[type_id] = type
+ end
+
+ def self.alias_type(new, old)
+ TYPES[new] = TYPES[old]
+ end
+
+ register_type Mysql::Field::TYPE_TINY, Fields::Boolean.new
+ register_type Mysql::Field::TYPE_LONG, Fields::Integer.new
+ alias_type Mysql::Field::TYPE_LONGLONG, Mysql::Field::TYPE_LONG
+ alias_type Mysql::Field::TYPE_NEWDECIMAL, Mysql::Field::TYPE_LONG
+
+ register_type Mysql::Field::TYPE_VAR_STRING, Fields::Identity.new
+ register_type Mysql::Field::TYPE_BLOB, Fields::Identity.new
+ register_type Mysql::Field::TYPE_DATE, Fields::Date.new
+ register_type Mysql::Field::TYPE_DATETIME, Fields::DateTime.new
+ register_type Mysql::Field::TYPE_TIME, Fields::Time.new
+ register_type Mysql::Field::TYPE_FLOAT, Fields::Float.new
+
+ Mysql::Field.constants.grep(/TYPE/).map { |class_name|
+ Mysql::Field.const_get class_name
+ }.reject { |const| TYPES.key? const }.each do |const|
+ register_type const, Fields::Identity.new
+ end
+ end
+
def exec_without_stmt(sql, name = 'SQL') # :nodoc:
# Some queries, like SHOW CREATE TABLE don't work through the prepared
# statement API. For those queries, we need to use this method. :'(
log(sql, name) do
result = @connection.query(sql)
- cols = []
- rows = []
+ affected_rows = @connection.affected_rows
if result
- cols = result.fetch_fields.map { |field| field.name }
- rows = result.to_a
+ types = {}
+ result.fetch_fields.each { |field|
+ if field.decimals > 0
+ types[field.name] = Fields::Decimal.new
+ else
+ types[field.name] = Fields::TYPES.fetch(field.type) {
+ Fields::Identity.new
+ }
+ end
+ }
+ result_set = ActiveRecord::Result.new(types.keys, result.to_a, types)
result.free
+ else
+ result_set = ActiveRecord::Result.new([], [])
end
- ActiveRecord::Result.new(cols, rows)
+
+ [result_set, affected_rows]
end
end
@@ -321,16 +454,18 @@ module ActiveRecord
alias :create :insert_sql
def exec_delete(sql, name, binds)
- log(sql, name, binds) do
- exec_stmt(sql, name, binds) do |cols, stmt|
- stmt.affected_rows
- end
+ affected_rows = 0
+
+ exec_query(sql, name, binds) do |n|
+ affected_rows = n
end
+
+ affected_rows
end
alias :exec_update :exec_delete
def begin_db_transaction #:nodoc:
- exec_without_stmt "BEGIN"
+ exec_query "BEGIN"
rescue Mysql::Error
# Transactions aren't supported
end
@@ -339,41 +474,44 @@ module ActiveRecord
def exec_stmt(sql, name, binds)
cache = {}
- if binds.empty?
- stmt = @connection.prepare(sql)
- else
- cache = @statements[sql] ||= {
- :stmt => @connection.prepare(sql)
- }
- stmt = cache[:stmt]
- end
+ log(sql, name, binds) do
+ if binds.empty?
+ stmt = @connection.prepare(sql)
+ else
+ cache = @statements[sql] ||= {
+ :stmt => @connection.prepare(sql)
+ }
+ stmt = cache[:stmt]
+ end
- begin
- stmt.execute(*binds.map { |col, val| type_cast(val, col) })
- rescue Mysql::Error => e
- # Older versions of MySQL leave the prepared statement in a bad
- # place when an error occurs. To support older mysql versions, we
- # need to close the statement and delete the statement from the
- # cache.
- stmt.close
- @statements.delete sql
- raise e
- end
+ begin
+ stmt.execute(*binds.map { |col, val| type_cast(val, col) })
+ rescue Mysql::Error => e
+ # Older versions of MySQL leave the prepared statement in a bad
+ # place when an error occurs. To support older mysql versions, we
+ # need to close the statement and delete the statement from the
+ # cache.
+ stmt.close
+ @statements.delete sql
+ raise e
+ end
- cols = nil
- if metadata = stmt.result_metadata
- cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
- field.name
- }
- end
+ cols = nil
+ if metadata = stmt.result_metadata
+ cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
+ field.name
+ }
+ end
- result = yield [cols, stmt]
+ result_set = ActiveRecord::Result.new(cols, stmt.to_a) if cols
+ affected_rows = stmt.affected_rows
- stmt.result_metadata.free if cols
- stmt.free_result
- stmt.close if binds.empty?
+ stmt.result_metadata.free if cols
+ stmt.free_result
+ stmt.close if binds.empty?
- result
+ [result_set, affected_rows]
+ end
end
def connect
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 7b263fd62d..40cd65cce9 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -1,5 +1,4 @@
require 'active_record/connection_adapters/abstract_adapter'
-require 'active_support/core_ext/object/blank'
require 'active_record/connection_adapters/statement_pool'
require 'active_record/connection_adapters/postgresql/oid'
require 'arel/visitors/bind_visitor'
@@ -474,6 +473,7 @@ module ActiveRecord
def reconnect!
clear_cache!
@connection.reset
+ @open_transactions = 0
configure_connection
end
@@ -803,13 +803,6 @@ module ActiveRecord
Arel::Nodes::BindParam.new "$#{index + 1}"
end
- class Result < ActiveRecord::Result
- def initialize(columns, rows, column_types)
- super(columns, rows)
- @column_types = column_types
- end
- end
-
def exec_query(sql, name = 'SQL', binds = [])
log(sql, name, binds) do
result = binds.empty? ? exec_no_cache(sql, binds) :
@@ -825,7 +818,7 @@ module ActiveRecord
}
end
- ret = Result.new(result.fields, result.values, types)
+ ret = ActiveRecord::Result.new(result.fields, result.values, types)
result.clear
return ret
end
@@ -1227,12 +1220,19 @@ module ActiveRecord
end
# Renames a table.
+ # Also renames a table's primary key sequence if the sequence name matches the
+ # Active Record default.
#
# Example:
# rename_table('octopuses', 'octopi')
def rename_table(name, new_name)
clear_cache!
execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
+ pk, seq = pk_and_sequence_for(new_name)
+ if seq == "#{name}_#{pk}_seq"
+ new_seq = "#{new_name}_#{pk}_seq"
+ execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
+ end
end
# Adds a new column to the named table.
@@ -1374,7 +1374,7 @@ module ActiveRecord
UNIQUE_VIOLATION = "23505"
def translate_exception(exception, message)
- case exception.result.error_field(PGresult::PG_DIAG_SQLSTATE)
+ case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
when UNIQUE_VIOLATION
RecordNotUnique.new(message, exception)
when FOREIGN_KEY_VIOLATION
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 57aa47ab61..4fe0013f0f 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -380,9 +380,9 @@ module ActiveRecord
case field["dflt_value"]
when /^null$/i
field["dflt_value"] = nil
- when /^'(.*)'$/
+ when /^'(.*)'$/m
field["dflt_value"] = $1.gsub("''", "'")
- when /^"(.*)"$/
+ when /^"(.*)"$/m
field["dflt_value"] = $1.gsub('""', '"')
end
diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb
index bda41df80f..3531be05bf 100644
--- a/activerecord/lib/active_record/connection_handling.rb
+++ b/activerecord/lib/active_record/connection_handling.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/module/delegation'
module ActiveRecord
module ConnectionHandling
@@ -45,7 +44,7 @@ module ActiveRecord
end
remove_connection
- connection_handler.establish_connection name, spec
+ connection_handler.establish_connection self, spec
end
# Returns the connection currently associated with the class. This can
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 90f156456e..aad21b8e37 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -1,7 +1,5 @@
-require 'active_support/concern'
require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/core_ext/object/deep_dup'
-require 'active_support/core_ext/module/delegation'
+require 'active_support/core_ext/object/duplicable'
require 'thread'
module ActiveRecord
@@ -84,15 +82,6 @@ module ActiveRecord
# The connection handler
config_attribute :connection_handler
- ##
- # :singleton-method:
- # Specifies whether or not has_many or has_one association option
- # :dependent => :restrict raises an exception. If set to true, the
- # ActiveRecord::DeleteRestrictionError exception will be raised
- # along with a DEPRECATION WARNING. If set to false, an error would
- # be added to the model instead.
- config_attribute :dependent_restrict_raises
-
%w(logger configurations default_timezone schema_format timestamped_migrations).each do |name|
config_attribute name, global: true
end
@@ -184,7 +173,10 @@ module ActiveRecord
# # Instantiates a single new object bypassing mass-assignment security
# User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
def initialize(attributes = nil, options = {})
- @attributes = self.class.initialize_attributes(self.class.column_defaults.deep_dup)
+ defaults = self.class.column_defaults.dup
+ defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
+
+ @attributes = self.class.initialize_attributes(defaults)
@columns_hash = self.class.column_types.dup
init_internals
@@ -196,7 +188,7 @@ module ActiveRecord
assign_attributes(attributes, options) if attributes
yield self if block_given?
- run_callbacks :initialize if _initialize_callbacks.any?
+ run_callbacks :initialize unless _initialize_callbacks.empty?
end
# Initialize an empty model object from +coder+. +coder+ must contain
@@ -266,6 +258,7 @@ module ActiveRecord
@changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
end
+ @aggregation_cache = {}
@association_cache = {}
@attributes_cache = {}
@@ -380,7 +373,7 @@ module ActiveRecord
#
# So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
#
- # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/
+ # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
def to_ary # :nodoc:
nil
end
@@ -390,6 +383,7 @@ module ActiveRecord
@attributes[pk] = nil unless @attributes.key?(pk)
+ @aggregation_cache = {}
@association_cache = {}
@attributes_cache = {}
@previously_changed = {}
@@ -399,6 +393,7 @@ module ActiveRecord
@marked_for_destruction = false
@new_record = true
@mass_assignment_options = nil
+ @_start_transaction_state = {}
end
end
end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index b27a19f89a..c877079b25 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -25,7 +25,7 @@ module ActiveRecord
foreign_key = has_many_association.foreign_key.to_s
child_class = has_many_association.klass
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
- reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key }
+ reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
counter_name = reflection.counter_cache_column
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb
index a37cde77ee..3bac31c6aa 100644
--- a/activerecord/lib/active_record/dynamic_matchers.rb
+++ b/activerecord/lib/active_record/dynamic_matchers.rb
@@ -1,8 +1,8 @@
module ActiveRecord
module DynamicMatchers #:nodoc:
# This code in this file seems to have a lot of indirection, but the indirection
- # is there to provide extension points for the active_record_deprecated_finders
- # gem. When we stop supporting active_record_deprecated_finders (from Rails 5),
+ # is there to provide extension points for the activerecord-deprecated_finders
+ # gem. When we stop supporting activerecord-deprecated_finders (from Rails 5),
# then we can remove the indirection.
def respond_to?(name, include_private = false)
@@ -57,7 +57,7 @@ module ActiveRecord
end
def valid?
- attribute_names.all? { |name| model.columns_hash[name] }
+ attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) }
end
def define
@@ -74,17 +74,17 @@ module ActiveRecord
end
module Finder
- # Extended in active_record_deprecated_finders
+ # Extended in activerecord-deprecated_finders
def body
result
end
- # Extended in active_record_deprecated_finders
+ # Extended in activerecord-deprecated_finders
def result
"#{finder}(#{attributes_hash})"
end
- # Extended in active_record_deprecated_finders
+ # Extended in activerecord-deprecated_finders
def signature
attribute_names.join(', ')
end
diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb
index 7ade385c70..9e0390bed1 100644
--- a/activerecord/lib/active_record/explain.rb
+++ b/activerecord/lib/active_record/explain.rb
@@ -1,5 +1,4 @@
require 'active_support/lazy_load_hooks'
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 96d24b72b3..b1db5f6f9f 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -2,7 +2,6 @@ require 'erb'
require 'yaml'
require 'zlib'
require 'active_support/dependencies'
-require 'active_support/core_ext/object/blank'
require 'active_record/fixtures/file'
require 'active_record/errors'
@@ -880,7 +879,7 @@ module ActiveRecord
end
def enlist_fixture_connections
- ActiveRecord::Base.connection_handler.connection_pools.values.map(&:connection)
+ ActiveRecord::Base.connection_handler.connection_pools.map(&:connection)
end
private
diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb
index 770083ac13..04fff99a6e 100644
--- a/activerecord/lib/active_record/inheritance.rb
+++ b/activerecord/lib/active_record/inheritance.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
@@ -41,14 +40,26 @@ module ActiveRecord
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
end
- # Returns the base AR subclass that this class descends from. If A
- # extends AR::Base, A.base_class will return A. If B descends from A
+ # Returns the class descending directly from ActiveRecord::Base (or
+ # that includes ActiveRecord::Model), or an abstract class, if any, in
+ # the inheritance hierarchy.
+ #
+ # If A extends AR::Base, A.base_class will return A. If B descends from A
# through some arbitrarily deep hierarchy, B.base_class will return A.
#
# If B < A and C < B and if A is an abstract_class then both B.base_class
# and C.base_class would return B as the answer since A is an abstract_class.
def base_class
- class_of_active_record_descendant(self)
+ unless self < Model::Tag
+ raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
+ end
+
+ sup = active_record_super
+ if sup == Base || sup == Model || sup.abstract_class?
+ self
+ else
+ sup.base_class
+ end
end
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
@@ -96,21 +107,6 @@ module ActiveRecord
protected
- # Returns the class descending directly from ActiveRecord::Base or an
- # abstract class, if any, in the inheritance hierarchy.
- def class_of_active_record_descendant(klass)
- unless klass < Model::Tag
- raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
- end
-
- sup = klass.active_record_super
- if [Base, Model].include?(klass) || [Base, Model].include?(sup) || sup.abstract_class?
- klass
- else
- class_of_active_record_descendant(sup)
- end
- end
-
# Returns the class type of the record using the current module as a prefix. So descendants of
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
def compute_type(type_name)
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 4ce42feb74..e96ed00f9c 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -86,7 +86,7 @@ module ActiveRecord
stmt = relation.where(
relation.table[self.class.primary_key].eq(id).and(
- relation.table[lock_col].eq(quote_value(previous_lock_value))
+ relation.table[lock_col].eq(self.class.quote_value(previous_lock_value))
)
).arel.compile_update(arel_attributes_with_values_for_update(attribute_names))
@@ -168,16 +168,16 @@ module ActiveRecord
super
end
- # If the locking column has no default value set,
- # start the lock version at zero. Note we can't use
- # <tt>locking_enabled?</tt> at this point as
- # <tt>@attributes</tt> may not have been initialized yet.
- def initialize_attributes(attributes, options = {}) #:nodoc:
- if attributes.key?(locking_column) && lock_optimistically
- attributes[locking_column] ||= 0
- end
+ def column_defaults
+ @column_defaults ||= begin
+ defaults = super
+
+ if defaults.key?(locking_column) && lock_optimistically
+ defaults[locking_column] ||= 0
+ end
- attributes
+ defaults
+ end
end
end
end
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index d58176bc62..c1d57855a9 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -1,6 +1,4 @@
-require "active_support/core_ext/module/delegation"
require "active_support/core_ext/class/attribute_accessors"
-require 'active_support/deprecation'
require 'set'
module ActiveRecord
@@ -52,7 +50,7 @@ module ActiveRecord
#
# class AddSsl < ActiveRecord::Migration
# def up
- # add_column :accounts, :ssl_enabled, :boolean, :default => 1
+ # add_column :accounts, :ssl_enabled, :boolean, :default => true
# end
#
# def down
@@ -238,7 +236,7 @@ module ActiveRecord
# add_column :people, :salary, :integer
# Person.reset_column_information
# Person.all.each do |p|
- # p.update_column :salary, SalaryCalculator.compute(p)
+ # p.update_attribute :salary, SalaryCalculator.compute(p)
# end
# end
# end
@@ -258,7 +256,7 @@ module ActiveRecord
# ...
# say_with_time "Updating salaries..." do
# Person.all.each do |p|
- # p.update_column :salary, SalaryCalculator.compute(p)
+ # p.update_attribute :salary, SalaryCalculator.compute(p)
# end
# end
# ...
diff --git a/activerecord/lib/active_record/migration/join_table.rb b/activerecord/lib/active_record/migration/join_table.rb
index 01a580781b..e880ae97bb 100644
--- a/activerecord/lib/active_record/migration/join_table.rb
+++ b/activerecord/lib/active_record/migration/join_table.rb
@@ -4,13 +4,11 @@ module ActiveRecord
private
def find_join_table_name(table_1, table_2, options = {})
- options.delete(:table_name) { join_table_name(table_1, table_2) }
+ options.delete(:table_name) || join_table_name(table_1, table_2)
end
def join_table_name(table_1, table_2)
- tables_names = [table_1, table_2].map(&:to_s).sort
-
- tables_names.join("_").to_sym
+ [table_1, table_2].sort.join("_").to_sym
end
end
end
diff --git a/activerecord/lib/active_record/model.rb b/activerecord/lib/active_record/model.rb
index 0015e3a567..57553c29eb 100644
--- a/activerecord/lib/active_record/model.rb
+++ b/activerecord/lib/active_record/model.rb
@@ -1,6 +1,3 @@
-require 'active_support/deprecation'
-require 'active_support/concern'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/attribute_accessors'
module ActiveRecord
@@ -74,9 +71,9 @@ module ActiveRecord
include Inheritance
include Scoping
include Sanitization
- include Integration
include AttributeAssignment
include ActiveModel::Conversion
+ include Integration
include Validations
include CounterCache
include Locking::Optimistic
@@ -89,6 +86,7 @@ module ActiveRecord
include ActiveModel::SecurePassword
include AutosaveAssociation
include NestedAttributes
+ include Aggregations
include Transactions
include Reflection
include Serialization
@@ -111,26 +109,39 @@ module ActiveRecord
end
end
- module DeprecationProxy #:nodoc:
- class << self
- instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$|^instance_eval$/ }
-
- def method_missing(name, *args, &block)
- if Model.respond_to?(name)
- Model.send(name, *args, &block)
- else
- ActiveSupport::Deprecation.warn(
- "The object passed to the active_record load hook was previously ActiveRecord::Base " \
- "(a Class). Now it is ActiveRecord::Model (a Module). You have called `#{name}' which " \
- "is only defined on ActiveRecord::Base. Please change your code so that it works with " \
- "a module rather than a class. (Model is included in Base, so anything added to Model " \
- "will be available on Base as well.)"
- )
- Base.send(name, *args, &block)
- end
+ class DeprecationProxy < BasicObject #:nodoc:
+ def initialize(model = Model, base = Base)
+ @model = model
+ @base = base
+ end
+
+ def method_missing(name, *args, &block)
+ if @model.respond_to?(name, true)
+ @model.send(name, *args, &block)
+ else
+ ::ActiveSupport::Deprecation.warn(
+ "The object passed to the active_record load hook was previously ActiveRecord::Base " \
+ "(a Class). Now it is ActiveRecord::Model (a Module). You have called `#{name}' which " \
+ "is only defined on ActiveRecord::Base. Please change your code so that it works with " \
+ "a module rather than a class. (Model is included in Base, so anything added to Model " \
+ "will be available on Base as well.)"
+ )
+ @base.send(name, *args, &block)
end
+ end
- alias send method_missing
+ alias send method_missing
+
+ def extend(*mods)
+ ::ActiveSupport::Deprecation.warn(
+ "The object passed to the active_record load hook was previously ActiveRecord::Base " \
+ "(a Class). Now it is ActiveRecord::Model (a Module). You have called `extend' which " \
+ "would add singleton methods to Model. This is presumably not what you want, since the " \
+ "methods would not be inherited down to Base. Rather than using extend, please use " \
+ "ActiveSupport::Concern + include, which will ensure that your class methods are " \
+ "inherited."
+ )
+ @base.extend(*mods)
end
end
end
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index e6b76ddc4c..99de16cd33 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
@@ -144,16 +143,12 @@ module ActiveRecord
# Computes the table name, (re)sets it internally, and returns it.
def reset_table_name #:nodoc:
- if abstract_class?
- self.table_name = if active_record_super == Base || active_record_super.abstract_class?
- nil
- else
- active_record_super.table_name
- end
+ self.table_name = if abstract_class?
+ active_record_super == Base ? nil : active_record_super.table_name
elsif active_record_super.abstract_class?
- self.table_name = active_record_super.table_name || compute_table_name
+ active_record_super.table_name || compute_table_name
else
- self.table_name = compute_table_name
+ compute_table_name
end
end
@@ -230,7 +225,7 @@ module ActiveRecord
def decorate_columns(columns_hash) # :nodoc:
return if columns_hash.empty?
- serialized_attributes.keys.each do |key|
+ serialized_attributes.each_key do |key|
columns_hash[key] = AttributeMethods::Serialization::Type.new(columns_hash[key])
end
@@ -264,13 +259,12 @@ module ActiveRecord
# and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
# is available.
def column_methods_hash #:nodoc:
- @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
+ @dynamic_methods_hash ||= column_names.each_with_object(Hash.new(false)) do |attr, methods|
attr_name = attr.to_s
methods[attr.to_sym] = attr_name
methods["#{attr}=".to_sym] = attr_name
methods["#{attr}?".to_sym] = attr_name
methods["#{attr}_before_type_cast".to_sym] = attr_name
- methods
end
end
@@ -317,13 +311,19 @@ module ActiveRecord
@relation = nil
end
+ # This is a hook for use by modules that need to do extra stuff to
+ # attributes when they are initialized. (e.g. attribute
+ # serialization)
+ def initialize_attributes(attributes, options = {}) #:nodoc:
+ attributes
+ end
+
private
# Guesses the table name, but does not decorate it with prefix and suffix information.
def undecorated_table_name(class_name = base_class.name)
table_name = class_name.to_s.demodulize.underscore
- table_name = table_name.pluralize if pluralize_table_names
- table_name
+ pluralize_table_names ? table_name.pluralize : table_name
end
# Computes and returns a table name according to default conventions.
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 7febb5539f..f91e41b535 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -1,8 +1,6 @@
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/try'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
@@ -247,7 +245,8 @@ module ActiveRecord
# any value for _destroy.
# [:limit]
# Allows you to specify the maximum number of the associated records that
- # can be processed with the nested attributes. If the size of the
+ # can be processed with the nested attributes. Limit also can be specified as a
+ # Proc or a Symbol pointing to a method that should return number. If the size of the
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
# exception is raised. If omitted, any number associations can be processed.
# Note that the :limit option is only applicable to one-to-many associations.
@@ -390,8 +389,17 @@ module ActiveRecord
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
end
- if options[:limit] && attributes_collection.size > options[:limit]
- raise TooManyRecords, "Maximum #{options[:limit]} records are allowed. Got #{attributes_collection.size} records instead."
+ limit = case options[:limit]
+ when Symbol
+ send(options[:limit])
+ when Proc
+ options[:limit].call
+ else
+ options[:limit]
+ end
+
+ if limit && attributes_collection.size > limit
+ raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
end
if attributes_collection.is_a? Hash
@@ -409,7 +417,7 @@ module ActiveRecord
association.target
else
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
- attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
+ attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
end
attributes_collection.each do |attributes|
diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb
index aca8291d75..4c1c91e3df 100644
--- a/activerecord/lib/active_record/null_relation.rb
+++ b/activerecord/lib/active_record/null_relation.rb
@@ -1,8 +1,7 @@
# -*- coding: utf-8 -*-
module ActiveRecord
- # = Active Record Null Relation
- module NullRelation
+ module NullRelation # :nodoc:
def exec_queries
@records = []
end
diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb
index fdf17c003c..6b2f6f98a5 100644
--- a/activerecord/lib/active_record/observer.rb
+++ b/activerecord/lib/active_record/observer.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
# = Active Record Observer
@@ -74,6 +73,12 @@ module ActiveRecord
#
# Observers will not be invoked unless you define these in your application configuration.
#
+ # If you are using Active Record outside Rails, activate the observers explicitly in a configuration or
+ # environment file:
+ #
+ # ActiveRecord::Base.add_observer CommentObserver.instance
+ # ActiveRecord::Base.add_observer SignupObserver.instance
+ #
# == Loading
#
# Observers register themselves in the model class they observe, since it is the class that
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index a23597be28..7bd65c180d 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -1,5 +1,3 @@
-require 'active_support/concern'
-
module ActiveRecord
# = Active Record Persistence
module Persistence
@@ -163,24 +161,23 @@ module ActiveRecord
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
became.instance_variable_set("@errors", errors)
- became.type = klass.name unless self.class.descends_from_active_record?
+ became.public_send("#{klass.inheritance_column}=", klass.name) unless self.class.descends_from_active_record?
became
end
- # Updates a single attribute of an object, without calling save.
+ # Updates a single attribute and saves the record.
+ # This is especially useful for boolean flags on existing records. Also note that
#
# * Validation is skipped.
- # * Callbacks are skipped.
- # * updated_at/updated_on column is not updated if that column is available.
+ # * Callbacks are invoked.
+ # * updated_at/updated_on column is updated if that column is available.
+ # * Updates all the attributes that are dirty in this object.
#
- # Raises an +ActiveRecordError+ when called on new objects, or when the +name+
- # attribute is marked as readonly.
- def update_column(name, value)
+ def update_attribute(name, value)
name = name.to_s
verify_readonly_attribute(name)
- raise ActiveRecordError, "can not update on a new record object" unless persisted?
- raw_write_attribute(name, value)
- self.class.where(self.class.primary_key => id).update_all(name => value) == 1
+ send("#{name}=", value)
+ save(:validate => false)
end
# Updates the attributes of the model from the passed-in hash and saves the
@@ -211,6 +208,40 @@ module ActiveRecord
end
end
+ # Updates a single attribute of an object, without calling save.
+ #
+ # * Validation is skipped.
+ # * Callbacks are skipped.
+ # * updated_at/updated_on column is not updated if that column is available.
+ #
+ # Raises an +ActiveRecordError+ when called on new objects, or when the +name+
+ # attribute is marked as readonly.
+ def update_column(name, value)
+ update_columns(name => value)
+ end
+
+ # Updates the attributes from the passed-in hash, without calling save.
+ #
+ # * Validation is skipped.
+ # * Callbacks are skipped.
+ # * updated_at/updated_on column is not updated if that column is available.
+ #
+ # Raises an +ActiveRecordError+ when called on new objects, or when at least
+ # one of the attributes is marked as readonly.
+ def update_columns(attributes)
+ raise ActiveRecordError, "can not update on a new record object" unless persisted?
+
+ attributes.each_key do |key|
+ verify_readonly_attribute(key.to_s)
+ end
+
+ attributes.each do |k,v|
+ raw_write_attribute(k,v)
+ end
+
+ self.class.where(self.class.primary_key => id).update_all(attributes) == 1
+ end
+
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
# The increment is performed directly on the underlying attribute, no setter is invoked.
# Only makes sense for number-based attributes. Returns +self+.
@@ -225,7 +256,7 @@ module ActiveRecord
# Saving is not subjected to validation checks. Returns +true+ if the
# record could be saved.
def increment!(attribute, by = 1)
- increment(attribute, by).update_column(attribute, self[attribute])
+ increment(attribute, by).update_attribute(attribute, self[attribute])
end
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
@@ -242,7 +273,7 @@ module ActiveRecord
# Saving is not subjected to validation checks. Returns +true+ if the
# record could be saved.
def decrement!(attribute, by = 1)
- decrement(attribute, by).update_column(attribute, self[attribute])
+ decrement(attribute, by).update_attribute(attribute, self[attribute])
end
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
@@ -259,7 +290,7 @@ module ActiveRecord
# Saving is not subjected to validation checks. Returns +true+ if the
# record could be saved.
def toggle!(attribute)
- toggle(attribute).update_column(attribute, self[attribute])
+ toggle(attribute).update_attribute(attribute, self[attribute])
end
# Reloads the attributes of this object from the database.
@@ -267,6 +298,7 @@ module ActiveRecord
# may do e.g. record.reload(:lock => true) to reload the same record with
# an exclusive row lock.
def reload(options = nil)
+ clear_aggregation_cache
clear_association_cache
fresh_object =
diff --git a/activerecord/lib/active_record/query_cache.rb b/activerecord/lib/active_record/query_cache.rb
index 9701898415..2bd8ecda20 100644
--- a/activerecord/lib/active_record/query_cache.rb
+++ b/activerecord/lib/active_record/query_cache.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActiveRecord
# = Active Record Query Cache
@@ -34,16 +33,22 @@ module ActiveRecord
response = @app.call(env)
response[2] = Rack::BodyProxy.new(response[2]) do
- ActiveRecord::Base.connection_id = connection_id
- ActiveRecord::Base.connection.clear_query_cache
- ActiveRecord::Base.connection.disable_query_cache! unless enabled
+ restore_query_cache_settings(connection_id, enabled)
end
response
rescue Exception => e
+ restore_query_cache_settings(connection_id, enabled)
+ raise e
+ end
+
+ private
+
+ def restore_query_cache_settings(connection_id, enabled)
+ ActiveRecord::Base.connection_id = connection_id
ActiveRecord::Base.connection.clear_query_cache
ActiveRecord::Base.connection.disable_query_cache! unless enabled
- raise e
end
+
end
end
diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb
index 4d8283bcff..13e09eda53 100644
--- a/activerecord/lib/active_record/querying.rb
+++ b/activerecord/lib/active_record/querying.rb
@@ -1,17 +1,15 @@
-require 'active_support/core_ext/module/delegation'
-require 'active_support/deprecation'
module ActiveRecord
module Querying
- delegate :find, :take, :take!, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped
- delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped
- delegate :find_by, :find_by!, :to => :scoped
- delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
- delegate :find_each, :find_in_batches, :to => :scoped
+ delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :to => :all
+ delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :all
+ delegate :find_by, :find_by!, :to => :all
+ delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :all
+ delegate :find_each, :find_in_batches, :to => :all
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
:where, :preload, :eager_load, :includes, :from, :lock, :readonly,
- :having, :create_with, :uniq, :references, :none, :to => :scoped
- delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :ids, :to => :scoped
+ :having, :create_with, :uniq, :references, :none, :to => :all
+ delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :ids, :to => :all
# Executes a custom SQL query against your database and returns all the results. The results will
# be returned as an array with columns requested encapsulated as attributes of the model you call
@@ -62,8 +60,10 @@ module ActiveRecord
#
# Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
def count_by_sql(sql)
- sql = sanitize_conditions(sql)
- connection.select_value(sql, "#{name} Count").to_i
+ logging_query_plan do
+ sql = sanitize_conditions(sql)
+ connection.select_value(sql, "#{name} Count").to_i
+ end
end
end
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 9432a70c41..ecf8547e67 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -29,6 +29,11 @@ module ActiveRecord
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
)
+
+ config.active_record.use_schema_cache_dump = true
+
+ config.eager_load_namespaces << ActiveRecord
+
rake_tasks do
require "active_record/base"
load "active_record/railties/databases.rake"
@@ -66,6 +71,25 @@ module ActiveRecord
end
end
+ initializer "active_record.check_schema_cache_dump" do |app|
+ if config.active_record.delete(:use_schema_cache_dump)
+ config.after_initialize do |app|
+ ActiveSupport.on_load(:active_record) do
+ filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
+
+ if File.file?(filename)
+ cache = Marshal.load File.binread filename
+ if cache.version == ActiveRecord::Migrator.current_version
+ ActiveRecord::Model.connection.schema_cache = cache
+ else
+ warn "schema_cache.dump is expired. Current version is #{ActiveRecord::Migrator.current_version}, but cache version is #{cache.version}."
+ end
+ end
+ end
+ end
+ end
+ end
+
initializer "active_record.set_configs" do |app|
ActiveSupport.on_load(:active_record) do
app.config.active_record.each do |k,v|
@@ -117,21 +141,6 @@ module ActiveRecord
end
end
- ActiveSupport.on_load(:active_record) do
- if app.config.use_schema_cache_dump
- filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
-
- if File.file?(filename)
- cache = Marshal.load File.binread filename
- if cache.version == ActiveRecord::Migrator.current_version
- ActiveRecord::Model.connection.schema_cache = cache
- else
- warn "schema_cache.dump is expired. Current version is #{ActiveRecord::Migrator.current_version}, but cache version is #{cache.version}."
- end
- end
- end
- end
-
end
end
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 78ecb1cdc5..ae24542521 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -1,8 +1,7 @@
-require 'active_support/core_ext/object/inclusion'
require 'active_record'
db_namespace = namespace :db do
- task :load_config => :rails_env do
+ task :load_config do
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a
@@ -20,7 +19,7 @@ db_namespace = namespace :db do
end
desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
- task :create => :load_config do
+ task :create => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.create_current
end
@@ -31,7 +30,7 @@ db_namespace = namespace :db do
end
desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
- task :drop => :load_config do
+ task :drop => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.drop_current
end
@@ -89,7 +88,7 @@ db_namespace = namespace :db do
desc 'Display status of migrations'
task :status => [:environment, :load_config] do
- config = ActiveRecord::Base.configurations[Rails.env || 'development']
+ config = ActiveRecord::Base.configurations[Rails.env]
ActiveRecord::Base.establish_connection(config)
unless ActiveRecord::Base.connection.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
puts 'Schema migrations table does not exist yet.'
@@ -242,7 +241,7 @@ db_namespace = namespace :db do
end
end
- task :load_if_ruby => 'db:create' do
+ task :load_if_ruby => [:environment, 'db:create'] do
db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
end
@@ -327,7 +326,7 @@ db_namespace = namespace :db do
end
end
- task :load_if_sql => 'db:create' do
+ task :load_if_sql => [:environment, 'db:create'] do
db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
end
end
@@ -409,21 +408,6 @@ db_namespace = namespace :db do
end
end
end
-
- namespace :sessions do
- # desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
- task :create => [:environment, :load_config] do
- raise 'Task unavailable to this database (no migration support)' unless ActiveRecord::Base.connection.supports_migrations?
- Rails.application.load_generators
- require 'rails/generators/rails/session_migration/session_migration_generator'
- Rails::Generators::SessionMigrationGenerator.start [ ENV['MIGRATION'] || 'add_sessions_table' ]
- end
-
- # desc "Clear the sessions table"
- task :clear => [:environment, :load_config] do
- ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::SessionStore::Session.table_name}"
- end
- end
end
namespace :railties do
@@ -448,7 +432,7 @@ namespace :railties do
puts "Copied migration #{migration.basename} from #{name}"
end
- ActiveRecord::Migration.copy( ActiveRecord::Migrator.migrations_paths.first, railties,
+ ActiveRecord::Migration.copy(ActiveRecord::Migrator.migrations_paths.first, railties,
:on_skip => on_skip, :on_copy => on_copy)
end
end
diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb
index 960b78dc38..b3c20c4aff 100644
--- a/activerecord/lib/active_record/readonly_attributes.rb
+++ b/activerecord/lib/active_record/readonly_attributes.rb
@@ -1,12 +1,10 @@
-require 'active_support/concern'
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
module ReadonlyAttributes
extend ActiveSupport::Concern
included do
- class_attribute :_attr_readonly, instance_writer: false
+ class_attribute :_attr_readonly, instance_accessor: false
self._attr_readonly = []
end
@@ -22,5 +20,10 @@ module ActiveRecord
self._attr_readonly
end
end
+
+ def _attr_readonly
+ ActiveSupport::Deprecation.warn("Instance level _attr_readonly method is deprecated, please use class level method.")
+ defined?(@_attr_readonly) ? @_attr_readonly : self.class._attr_readonly
+ end
end
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 0d9534acd6..cf949a893f 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/inclusion'
module ActiveRecord
# = Active Record Reflection
@@ -17,17 +15,36 @@ module ActiveRecord
# and creates input fields for all of the attributes depending on their type
# and displays the associations to other objects.
#
- # MacroReflection class has info for the AssociationReflection
- # class.
+ # MacroReflection class has info for AggregateReflection and AssociationReflection
+ # classes.
module ClassMethods
- def create_reflection(macro, name, options, active_record)
- klass = options[:through] ? ThroughReflection : AssociationReflection
- reflection = klass.new(macro, name, options, active_record)
+ def create_reflection(macro, name, scope, options, active_record)
+ case macro
+ when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
+ klass = options[:through] ? ThroughReflection : AssociationReflection
+ reflection = klass.new(macro, name, scope, options, active_record)
+ when :composed_of
+ reflection = AggregateReflection.new(macro, name, scope, options, active_record)
+ end
self.reflections = self.reflections.merge(name => reflection)
reflection
end
+ # Returns an array of AggregateReflection objects for all the aggregations in the class.
+ def reflect_on_all_aggregations
+ reflections.values.grep(AggregateReflection)
+ end
+
+ # Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
+ #
+ # Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
+ #
+ def reflect_on_aggregation(aggregation)
+ reflection = reflections[aggregation]
+ reflection if reflection.is_a?(AggregateReflection)
+ end
+
# Returns an array of AssociationReflection objects for all the
# associations in the class. If you only want to reflect on a certain
# association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
@@ -59,20 +76,26 @@ module ActiveRecord
end
end
- # Abstract base class for AssociationReflection. Objects of AssociationReflection are returned by the Reflection::ClassMethods.
+ # Abstract base class for AggregateReflection and AssociationReflection. Objects of
+ # AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
class MacroReflection
# Returns the name of the macro.
#
+ # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>:balance</tt>
# <tt>has_many :clients</tt> returns <tt>:clients</tt>
attr_reader :name
# Returns the macro type.
#
+ # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>:composed_of</tt>
# <tt>has_many :clients</tt> returns <tt>:has_many</tt>
attr_reader :macro
+ attr_reader :scope
+
# Returns the hash of options used for the macro.
#
+ # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>{ :class_name => "Money" }</tt>
# <tt>has_many :clients</tt> returns +{}+
attr_reader :options
@@ -80,9 +103,10 @@ module ActiveRecord
attr_reader :plural_name # :nodoc:
- def initialize(macro, name, options, active_record)
+ def initialize(macro, name, scope, options, active_record)
@macro = macro
@name = name
+ @scope = scope
@options = options
@active_record = active_record
@plural_name = active_record.pluralize_table_names ?
@@ -91,6 +115,7 @@ module ActiveRecord
# Returns the class for the macro.
#
+ # <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money class
# <tt>has_many :clients</tt> returns the Client class
def klass
@klass ||= class_name.constantize
@@ -98,6 +123,7 @@ module ActiveRecord
# Returns the class name for the macro.
#
+ # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
def class_name
@class_name ||= (options[:class_name] || derive_class_name).to_s
@@ -113,16 +139,22 @@ module ActiveRecord
active_record == other_aggregation.active_record
end
- def sanitized_conditions #:nodoc:
- @sanitized_conditions ||= klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
- end
-
private
def derive_class_name
name.to_s.camelize
end
end
+
+ # Holds all the meta-data about an aggregation as it was specified in the
+ # Active Record class.
+ class AggregateReflection < MacroReflection #:nodoc:
+ def mapping
+ mapping = options[:mapping] || [name, name]
+ mapping.first.is_a?(Array) ? mapping : [mapping]
+ end
+ end
+
# Holds all the meta-data about an association as it was specified in the
# Active Record class.
class AssociationReflection < MacroReflection #:nodoc:
@@ -142,7 +174,7 @@ module ActiveRecord
@klass ||= active_record.send(:compute_type, class_name)
end
- def initialize(macro, name, options, active_record)
+ def initialize(*args)
super
@collection = [:has_many, :has_and_belongs_to_many].include?(macro)
end
@@ -244,11 +276,10 @@ module ActiveRecord
false
end
- # An array of arrays of conditions. Each item in the outside array corresponds to a reflection
- # in the #chain. The inside arrays are simply conditions (and each condition may itself be
- # a hash, array, arel predicate, etc...)
- def conditions
- [[options[:conditions]].compact]
+ # An array of arrays of scopes. Each item in the outside array corresponds to a reflection
+ # in the #chain.
+ def scope_chain
+ scope ? [[scope]] : [[]]
end
alias :source_macro :macro
@@ -416,28 +447,25 @@ module ActiveRecord
# has_many :tags
# end
#
- # There may be conditions on Person.comment_tags, Article.comment_tags and/or Comment.tags,
+ # There may be scopes on Person.comment_tags, Article.comment_tags and/or Comment.tags,
# but only Comment.tags will be represented in the #chain. So this method creates an array
- # of conditions corresponding to the chain. Each item in the #conditions array corresponds
- # to an item in the #chain, and is itself an array of conditions from an arbitrary number
- # of relevant reflections, plus any :source_type or polymorphic :as constraints.
- def conditions
- @conditions ||= begin
- conditions = source_reflection.conditions.map { |c| c.dup }
+ # of scopes corresponding to the chain.
+ def scope_chain
+ @scope_chain ||= begin
+ scope_chain = source_reflection.scope_chain.map(&:dup)
- # Add to it the conditions from this reflection if necessary.
- conditions.first << options[:conditions] if options[:conditions]
+ # Add to it the scope from this reflection (if any)
+ scope_chain.first << scope if scope
- through_conditions = through_reflection.conditions
+ through_scope_chain = through_reflection.scope_chain
if options[:source_type]
- through_conditions.first << { foreign_type => options[:source_type] }
+ through_scope_chain.first <<
+ through_reflection.klass.where(foreign_type => options[:source_type])
end
# Recursively fill out the rest of the array from the through reflection
- conditions += through_conditions
-
- conditions
+ scope_chain + through_scope_chain
end
end
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index a39328b89b..2d0457636e 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
-require 'active_support/core_ext/object/blank'
-require 'active_support/deprecation'
module ActiveRecord
# = Active Record Relation
@@ -20,6 +18,7 @@ module ActiveRecord
attr_reader :table, :klass, :loaded
attr_accessor :default_scoped
+ alias :model :klass
alias :loaded? :loaded
alias :default_scoped? :default_scoped
@@ -75,6 +74,18 @@ module ActiveRecord
binds)
end
+ # Initializes new record from relation while maintaining the current
+ # scope.
+ #
+ # Expects arguments in the same format as +Base.new+.
+ #
+ # users = User.where(name: 'DHH')
+ # user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
+ #
+ # You can also pass a block to new with the new record as argument:
+ #
+ # user = users.new { |user| user.name = 'Oscar' }
+ # user.name # => Oscar
def new(*args, &block)
scoping { @klass.new(*args, &block) }
end
@@ -87,17 +98,38 @@ module ActiveRecord
alias build new
+ # Tries to create a new record with the same scoped attributes
+ # defined in the relation. Returns the initialized object if validation fails.
+ #
+ # Expects arguments in the same format as +Base.create+.
+ #
+ # ==== Examples
+ # users = User.where(name: 'Oscar')
+ # users.create # #<User id: 3, name: "oscar", ...>
+ #
+ # users.create(name: 'fxn')
+ # users.create # #<User id: 4, name: "fxn", ...>
+ #
+ # users.create { |user| user.name = 'tenderlove' }
+ # # #<User id: 5, name: "tenderlove", ...>
+ #
+ # users.create(name: nil) # validation on name
+ # # #<User id: nil, name: nil, ...>
def create(*args, &block)
scoping { @klass.create(*args, &block) }
end
+ # Similar to #create, but calls +create!+ on the base class. Raises
+ # an exception if a validation error occurs.
+ #
+ # Expects arguments in the same format as <tt>Base.create!</tt>.
def create!(*args, &block)
scoping { @klass.create!(*args, &block) }
end
# Tries to load the first record; if it fails, then <tt>create</tt> is called with the same arguments as this method.
#
- # Expects arguments in the same format as <tt>Base.create</tt>.
+ # Expects arguments in the same format as +Base.create+.
#
# ==== Examples
# # Find the first user named Penélope or create a new one.
@@ -145,52 +177,17 @@ module ActiveRecord
# are needed by the next ones when eager loading is going on.
#
# Please see further details in the
- # {Active Record Query Interface guide}[http://edgeguides.rubyonrails.org/active_record_querying.html#running-explain].
+ # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
def explain
_, queries = collecting_queries_for_explain { exec_queries }
exec_explain(queries)
end
+ # Converts relation objects to Array.
def to_a
- # We monitor here the entire execution rather than individual SELECTs
- # because from the point of view of the user fetching the records of a
- # relation is a single unit of work. You want to know if this call takes
- # too long, not if the individual queries take too long.
- #
- # It could be the case that none of the queries involved surpass the
- # threshold, and at the same time the sum of them all does. The user
- # should get a query plan logged in that case.
- logging_query_plan do
- exec_queries
- end
- end
-
- def exec_queries
- return @records if loaded?
-
- default_scoped = with_default_scope
-
- if default_scoped.equal?(self)
- @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values)
-
- preload = preload_values
- preload += includes_values unless eager_loading?
- preload.each do |associations|
- ActiveRecord::Associations::Preloader.new(@records, associations).run
- end
-
- # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
- # are JOINS and no explicit SELECT.
- readonly = readonly_value.nil? ? @implicit_readonly : readonly_value
- @records.each { |record| record.readonly! } if readonly
- else
- @records = default_scoped.to_a
- end
-
- @loaded = true
+ load
@records
end
- private :exec_queries
def as_json(options = nil) #:nodoc:
to_a.as_json(options)
@@ -209,6 +206,7 @@ module ActiveRecord
c.respond_to?(:zero?) ? c.zero? : c.empty?
end
+ # Returns true if there are any records.
def any?
if block_given?
to_a.any? { |*block_args| yield(*block_args) }
@@ -217,6 +215,7 @@ module ActiveRecord
end
end
+ # Returns true if there is more than one record.
def many?
if block_given?
to_a.many? { |*block_args| yield(*block_args) }
@@ -227,8 +226,6 @@ module ActiveRecord
# Scope all queries to the current scope.
#
- # ==== Example
- #
# Comment.where(:post_id => 1).scoping do
# Comment.first # SELECT * FROM comments WHERE post_id = 1
# end
@@ -250,21 +247,20 @@ module ActiveRecord
# ==== Parameters
#
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
- # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
- # See conditions in the intro.
- # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
#
# ==== Examples
#
# # Update all customers with the given attributes
- # Customer.update_all :wants_email => true
+ # Customer.update_all wants_email: true
#
# # Update all books with 'Rails' in their title
- # Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
+ # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
#
# # Update all books that match conditions, but limit it to 5 ordered by date
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
def update_all(updates)
+ raise ArgumentError, "Empty list of attributes to change" if updates.blank?
+
stmt = Arel::UpdateManager.new(arel.engine)
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
@@ -293,7 +289,7 @@ module ActiveRecord
# ==== Examples
#
# # Updates one record
- # Person.update(15, :user_name => 'Samuel', :group => 'expert')
+ # Person.update(15, user_name: 'Samuel', group: 'expert')
#
# # Updates multiple records
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
@@ -333,7 +329,7 @@ module ActiveRecord
# ==== Examples
#
# Person.destroy_all("last_login < '2004-04-04'")
- # Person.destroy_all(:status => "inactive")
+ # Person.destroy_all(status: "inactive")
# Person.where(:age => 0..18).destroy_all
def destroy_all(conditions = nil)
if conditions
@@ -435,10 +431,32 @@ module ActiveRecord
where(primary_key => id_or_array).delete_all
end
+ # Causes the records to be loaded from the database if they have not
+ # been loaded already. You can use this if for some reason you need
+ # to explicitly load some records before actually using them. The
+ # return value is the relation itself, not the records.
+ #
+ # Post.where(published: true).load # => #<ActiveRecord::Relation>
+ def load
+ unless loaded?
+ # We monitor here the entire execution rather than individual SELECTs
+ # because from the point of view of the user fetching the records of a
+ # relation is a single unit of work. You want to know if this call takes
+ # too long, not if the individual queries take too long.
+ #
+ # It could be the case that none of the queries involved surpass the
+ # threshold, and at the same time the sum of them all does. The user
+ # should get a query plan logged in that case.
+ logging_query_plan { exec_queries }
+ end
+
+ self
+ end
+
+ # Forces reloading of relation.
def reload
reset
- to_a # force reload
- self
+ load
end
def reset
@@ -448,10 +466,18 @@ module ActiveRecord
self
end
+ # Returns sql statement for the relation.
+ #
+ # Users.where(name: 'Oscar').to_sql
+ # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
def to_sql
@to_sql ||= klass.connection.to_sql(arel, bind_values.dup)
end
+ # Returns a hash of where conditions
+ #
+ # Users.where(name: 'Oscar').where_values_hash
+ # # => {:name=>"oscar"}
def where_values_hash
equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
node.left.relation.name == table_name
@@ -469,6 +495,7 @@ module ActiveRecord
@scope_for_create ||= where_values_hash.merge(create_with_value)
end
+ # Returns true if relation needs eager loading.
def eager_loading?
@should_eager_load ||=
eager_load_values.any? ||
@@ -483,6 +510,7 @@ module ActiveRecord
includes_values & joins_values
end
+ # Compares two relations for equality.
def ==(other)
case other
when Relation
@@ -506,6 +534,7 @@ module ActiveRecord
end
end
+ # Returns true if relation is blank.
def blank?
to_a.blank?
end
@@ -515,10 +544,7 @@ module ActiveRecord
end
def inspect
- limit = [limit_value, 11].compact.min
- entries = loaded? ? to_a.take(limit) : limit(limit)
-
- entries.map!(&:inspect)
+ entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
entries[10] = '...' if entries.size == 11
"#<#{self.class.name} [#{entries.join(', ')}]>"
@@ -526,6 +552,30 @@ module ActiveRecord
private
+ def exec_queries
+ default_scoped = with_default_scope
+
+ if default_scoped.equal?(self)
+ @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values)
+
+ preload = preload_values
+ preload += includes_values unless eager_loading?
+ preload.each do |associations|
+ ActiveRecord::Associations::Preloader.new(@records, associations).run
+ end
+
+ # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
+ # are JOINS and no explicit SELECT.
+ readonly = readonly_value.nil? ? @implicit_readonly : readonly_value
+ @records.each { |record| record.readonly! } if readonly
+ else
+ @records = default_scoped.to_a
+ end
+
+ @loaded = true
+ @records
+ end
+
def references_eager_loaded_tables?
joined_tables = arel.join_sources.map do |join|
if join.is_a?(Arel::Nodes::StringJoin)
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index fb4388d4b2..4d14506965 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActiveRecord
module Batches
@@ -9,8 +8,8 @@ module ActiveRecord
# In that case, batch processing methods allow you to work
# with the records in batches, thereby greatly reducing memory consumption.
#
- # The <tt>find_each</tt> method uses <tt>find_in_batches</tt> with a batch size of 1000 (or as
- # specified by the <tt>:batch_size</tt> option).
+ # The #find_each method uses #find_in_batches with a batch size of 1000 (or as
+ # specified by the +:batch_size+ option).
#
# Person.all.find_each do |person|
# person.do_awesome_stuff
@@ -20,7 +19,7 @@ module ActiveRecord
# person.party_all_night!
# end
#
- # You can also pass the <tt>:start</tt> option to specify
+ # You can also pass the +:start+ option to specify
# an offset to control the starting point.
def find_each(options = {})
find_in_batches(options) do |records|
@@ -29,14 +28,14 @@ module ActiveRecord
end
# Yields each batch of records that was found by the find +options+ as
- # an array. The size of each batch is set by the <tt>:batch_size</tt>
+ # an array. The size of each batch is set by the +:batch_size+
# option; the default is 1000.
#
# You can control the starting point for the batch processing by
- # supplying the <tt>:start</tt> option. This is especially useful if you
+ # supplying the +:start+ option. This is especially useful if you
# want multiple workers dealing with the same processing queue. You can
# make worker 1 handle all the records between id 0 and 10,000 and
- # worker 2 handle from 10,000 and beyond (by setting the <tt>:start</tt>
+ # worker 2 handle from 10,000 and beyond (by setting the +:start+
# option on that worker).
#
# It's not possible to set the order. That is automatically set to
@@ -67,7 +66,7 @@ module ActiveRecord
batch_size = options.delete(:batch_size) || 1000
relation = relation.reorder(batch_order).limit(batch_size)
- records = relation.where(table[primary_key].gteq(start)).all
+ records = relation.where(table[primary_key].gteq(start)).to_a
while records.any?
records_size = records.size
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index e40b958b54..d93e7c8997 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
module ActiveRecord
diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb
index 64dda4f35a..ab8b36c8ab 100644
--- a/activerecord/lib/active_record/relation/delegation.rb
+++ b/activerecord/lib/active_record/relation/delegation.rb
@@ -1,7 +1,6 @@
-require 'active_support/core_ext/module/delegation'
module ActiveRecord
- module Delegation
+ module Delegation # :nodoc:
# Set up common delegations for performance (avoids method_missing)
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :to => :to_a
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 974cd326ef..84aaa39fed 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/indifferent_access'
module ActiveRecord
@@ -133,19 +132,6 @@ module ActiveRecord
last or raise RecordNotFound
end
- # Runs the query on the database and returns records with the used query
- # methods.
- #
- # Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
- # Person.where(["category IN (?)", categories]).limit(50).all
- # Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
- # Person.offset(10).limit(10).all
- # Person.includes([:account, :friends]).all
- # Person.group("category").all
- def all
- to_a
- end
-
# Returns +true+ if a record exists in the table that matches the +id+ or
# conditions given, or +false+ otherwise. The argument can take six forms:
#
@@ -285,7 +271,7 @@ module ActiveRecord
end
def find_some(ids)
- result = where(table[primary_key].in(ids)).all
+ result = where(table[primary_key].in(ids)).to_a
expected_size =
if limit_value && ids.size > limit_value
@@ -324,7 +310,7 @@ module ActiveRecord
@records.first
else
@first ||=
- if order_values.empty? && primary_key
+ if with_default_scope.order_values.empty? && primary_key
order(arel_table[primary_key].asc).limit(1).to_a.first
else
limit(1).to_a.first
diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb
index 36f98c6480..e5b50673da 100644
--- a/activerecord/lib/active_record/relation/merger.rb
+++ b/activerecord/lib/active_record/relation/merger.rb
@@ -1,9 +1,8 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
module ActiveRecord
class Relation
- class HashMerger
+ class HashMerger # :nodoc:
attr_reader :relation, :hash
def initialize(relation, hash)
@@ -28,7 +27,7 @@ module ActiveRecord
end
end
- class Merger
+ class Merger # :nodoc:
attr_reader :relation, :values
def initialize(relation, other)
@@ -98,15 +97,13 @@ module ActiveRecord
merged_wheres = relation.where_values + values[:where]
unless relation.where_values.empty?
- # Remove duplicates, last one wins.
- seen = Hash.new { |h,table| h[table] = {} }
+ # Remove equalities with duplicated left-hand. Last one wins.
+ seen = {}
merged_wheres = merged_wheres.reverse.reject { |w|
nuke = false
if w.respond_to?(:operator) && w.operator == :==
- name = w.left.name
- table = w.left.relation.name
- nuke = seen[table][name]
- seen[table][name] = true
+ nuke = seen[w.left]
+ seen[w.left] = true
end
nuke
}.reverse
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 6f49548aab..f6bacf4822 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/object/blank'
module ActiveRecord
module QueryMethods
@@ -35,16 +34,39 @@ module ActiveRecord
CODE
end
- def create_with_value
+ def create_with_value # :nodoc:
@values[:create_with] || {}
end
alias extensions extending_values
+ # Specify relationships to be included in the result set. For
+ # example:
+ #
+ # users = User.includes(:address)
+ # users.each do |user|
+ # user.address.city
+ # end
+ #
+ # allows you to access the +address+ attribute of the +User+ model without
+ # firing an additional query. This will often result in a
+ # performance improvement over a simple +join+.
+ #
+ # === conditions
+ #
+ # If you want to add conditions to your included models you'll have
+ # to explicitly reference them. For example:
+ #
+ # User.includes(:posts).where('posts.name = ?', 'example')
+ #
+ # Will throw an error, but this will work:
+ #
+ # User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
def includes(*args)
args.empty? ? self : spawn.includes!(*args)
end
+ # Like #includes, but modifies the relation in place.
def includes!(*args)
args.reject! {|a| a.blank? }
@@ -52,19 +74,31 @@ module ActiveRecord
self
end
+ # Forces eager loading by performing a LEFT OUTER JOIN on +args+:
+ #
+ # User.eager_load(:posts)
+ # => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
+ # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
+ # "users"."id"
def eager_load(*args)
args.blank? ? self : spawn.eager_load!(*args)
end
+ # Like #eager_load, but modifies relation in place.
def eager_load!(*args)
self.eager_load_values += args
self
end
+ # Allows preloading of +args+, in the same way that +includes+ does:
+ #
+ # User.preload(:posts)
+ # => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
def preload(*args)
args.blank? ? self : spawn.preload!(*args)
end
+ # Like #preload, but modifies relation in place.
def preload!(*args)
self.preload_values += args
self
@@ -82,6 +116,7 @@ module ActiveRecord
args.blank? ? self : spawn.references!(*args)
end
+ # Like #references, but modifies relation in place.
def references!(*args)
args.flatten!
@@ -93,7 +128,7 @@ module ActiveRecord
#
# First: takes a block so it can be used just like Array#select.
#
- # Model.scoped.select { |m| m.field == value }
+ # Model.all.select { |m| m.field == value }
#
# This will build an array of objects from the database for the scope,
# converting them into an array and iterating through them using Array#select.
@@ -101,8 +136,8 @@ module ActiveRecord
# Second: Modifies the SELECT statement for the query so that only certain
# fields are retrieved:
#
- # >> Model.select(:field)
- # => [#<Model field:value>]
+ # Model.select(:field)
+ # # => [#<Model field:value>]
#
# Although in the above example it looks as though this method returns an
# array, it actually returns a relation object and can have other query
@@ -110,31 +145,46 @@ module ActiveRecord
#
# The argument to the method can also be an array of fields.
#
- # >> Model.select([:field, :other_field, :and_one_more])
- # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
+ # Model.select(:field, :other_field, :and_one_more)
+ # # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
#
# Accessing attributes of an object that do not have fields retrieved by a select
# will throw <tt>ActiveModel::MissingAttributeError</tt>:
#
- # >> Model.select(:field).first.other_field
- # => ActiveModel::MissingAttributeError: missing attribute: other_field
- def select(value = Proc.new)
+ # Model.select(:field).first.other_field
+ # # => ActiveModel::MissingAttributeError: missing attribute: other_field
+ def select(*fields)
if block_given?
- to_a.select { |*block_args| value.call(*block_args) }
+ to_a.select { |*block_args| yield(*block_args) }
else
- spawn.select!(value)
+ raise ArgumentError, 'Call this with at least one field' if fields.empty?
+ spawn.select!(*fields)
end
end
- def select!(value)
- self.select_values += Array.wrap(value)
+ # Like #select, but modifies relation in place.
+ def select!(*fields)
+ self.select_values += fields.flatten
self
end
+ # Allows to specify a group attribute:
+ #
+ # User.group(:name)
+ # => SELECT "users".* FROM "users" GROUP BY name
+ #
+ # Returns an array with distinct records based on the +group+ attribute:
+ #
+ # User.select([:id, :name])
+ # => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
+ #
+ # User.group(:name)
+ # => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
def group(*args)
args.blank? ? self : spawn.group!(*args)
end
+ # Like #group, but modifies relation in place.
def group!(*args)
args.flatten!
@@ -142,10 +192,21 @@ module ActiveRecord
self
end
+ # Allows to specify an order attribute:
+ #
+ # User.order('name')
+ # => SELECT "users".* FROM "users" ORDER BY name
+ #
+ # User.order('name DESC')
+ # => SELECT "users".* FROM "users" ORDER BY name DESC
+ #
+ # User.order('name DESC, email')
+ # => SELECT "users".* FROM "users" ORDER BY name DESC, email
def order(*args)
args.blank? ? self : spawn.order!(*args)
end
+ # Like #order, but modifies relation in place.
def order!(*args)
args.flatten!
@@ -153,7 +214,7 @@ module ActiveRecord
references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
references!(references) if references.any?
- self.order_values += args
+ self.order_values = args + self.order_values
self
end
@@ -165,11 +226,12 @@ module ActiveRecord
#
# User.order('email DESC').reorder('id ASC').order('name ASC')
#
- # generates a query with 'ORDER BY id ASC, name ASC'.
+ # generates a query with 'ORDER BY name ASC, id ASC'.
def reorder(*args)
args.blank? ? self : spawn.reorder!(*args)
end
+ # Like #reorder, but modifies relation in place.
def reorder!(*args)
args.flatten!
@@ -178,10 +240,15 @@ module ActiveRecord
self
end
+ # Performs a joins on +args+:
+ #
+ # User.joins(:posts)
+ # => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
def joins(*args)
args.compact.blank? ? self : spawn.joins!(*args)
end
+ # Like #joins, but modifies relation in place.
def joins!(*args)
args.flatten!
@@ -301,10 +368,15 @@ module ActiveRecord
self
end
+ # Allows to specify a HAVING clause. Note that you can't use HAVING
+ # without also specifying a GROUP clause.
+ #
+ # Order.having('SUM(price) > 30').group('user_id')
def having(opts, *rest)
opts.blank? ? self : spawn.having!(opts, *rest)
end
+ # Like #having, but modifies relation in place.
def having!(opts, *rest)
references!(PredicateBuilder.references(opts)) if Hash === opts
@@ -321,6 +393,7 @@ module ActiveRecord
spawn.limit!(value)
end
+ # Like #limit, but modifies relation in place.
def limit!(value)
self.limit_value = value
self
@@ -337,15 +410,19 @@ module ActiveRecord
spawn.offset!(value)
end
+ # Like #offset, but modifies relation in place.
def offset!(value)
self.offset_value = value
self
end
+ # Specifies locking settings (default to +true+). For more information
+ # on locking, please see +ActiveRecord::Locking+.
def lock(locks = true)
spawn.lock!(locks)
end
+ # Like #lock, but modifies relation in place.
def lock!(locks = true)
case locks
when String, TrueClass, NilClass
@@ -358,11 +435,11 @@ module ActiveRecord
end
# Returns a chainable relation with zero records, specifically an
- # instance of the NullRelation class.
+ # instance of the <tt>ActiveRecord::NullRelation</tt> class.
#
- # The returned NullRelation inherits from Relation and implements the
- # Null Object pattern so it is an object with defined null behavior:
- # it always returns an empty array of records and does not query the database.
+ # The returned <tt>ActiveRecord::NullRelation</tt> inherits from Relation and implements the
+ # Null Object pattern. It is an object with defined null behavior and always returns an empty
+ # array of records without quering the database.
#
# Any subsequent condition chained to the returned relation will continue
# generating an empty relation and will not fire any query to the database.
@@ -387,22 +464,47 @@ module ActiveRecord
# end
#
def none
- scoped.extending(NullRelation)
+ extending(NullRelation)
end
+ # Sets readonly attributes for the returned relation. If value is
+ # true (default), attempting to update a record will result in an error.
+ #
+ # users = User.readonly
+ # users.first.save
+ # => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
def readonly(value = true)
spawn.readonly!(value)
end
+ # Like #readonly, but modifies relation in place.
def readonly!(value = true)
self.readonly_value = value
self
end
+ # Sets attributes to be used when creating new records from a
+ # relation object.
+ #
+ # users = User.where(name: 'Oscar')
+ # users.new.name # => 'Oscar'
+ #
+ # users = users.create_with(name: 'DHH')
+ # users.new.name # => 'DHH'
+ #
+ # You can pass +nil+ to +create_with+ to reset attributes:
+ #
+ # users = users.create_with(nil)
+ # users.new.name # => 'Oscar'
def create_with(value)
spawn.create_with!(value)
end
+ # Like #create_with but modifies the relation in place. Raises
+ # +ImmutableRelation+ if the relation has already been loaded.
+ #
+ # users = User.all.create_with!(name: 'Oscar')
+ # users.new.name # => 'Oscar'
def create_with!(value)
self.create_with_value = value ? create_with_value.merge(value) : {}
self
@@ -425,6 +527,7 @@ module ActiveRecord
spawn.from!(value, subquery_name)
end
+ # Like #from, but modifies relation in place.
def from!(value, subquery_name = nil)
self.from_value = [value, subquery_name]
self
@@ -444,6 +547,7 @@ module ActiveRecord
spawn.uniq!(value)
end
+ # Like #uniq, but modifies relation in place.
def uniq!(value = true)
self.uniq_value = value
self
@@ -462,16 +566,16 @@ module ActiveRecord
# end
# end
#
- # scope = Model.scoped.extending(Pagination)
+ # scope = Model.all.extending(Pagination)
# scope.page(params[:page])
#
# You can also pass a list of modules:
#
- # scope = Model.scoped.extending(Pagination, SomethingElse)
+ # scope = Model.all.extending(Pagination, SomethingElse)
#
# === Using a block
#
- # scope = Model.scoped.extending do
+ # scope = Model.all.extending do
# def page(number)
# # pagination code goes here
# end
@@ -480,7 +584,7 @@ module ActiveRecord
#
# You can also use a block and a module list:
#
- # scope = Model.scoped.extending(Pagination) do
+ # scope = Model.all.extending(Pagination) do
# def per_page(number)
# # pagination code goes here
# end
@@ -493,10 +597,11 @@ module ActiveRecord
end
end
+ # Like #extending, but modifies relation in place.
def extending!(*modules, &block)
modules << Module.new(&block) if block_given?
- self.extending_values = modules.flatten
+ self.extending_values += modules.flatten
extend(*extending_values) if extending_values.any?
self
@@ -509,17 +614,20 @@ module ActiveRecord
spawn.reverse_order!
end
+ # Like #reverse_order, but modifies relation in place.
def reverse_order!
self.reverse_order_value = !reverse_order_value
self
end
+ # Returns the Arel object associated with the relation.
def arel
@arel ||= with_default_scope.build_arel
end
+ # Like #arel, but ignores the default scope of the model.
def build_arel
- arel = table.from table
+ arel = Arel::SelectManager.new(table.engine, table)
build_joins(arel, joins_values) unless joins_values.empty?
@@ -581,7 +689,8 @@ module ActiveRecord
when String, Array
[@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
when Hash
- PredicateBuilder.build_from_hash(table.engine, opts, table)
+ attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
+ PredicateBuilder.build_from_hash(table.engine, attributes, table)
else
[opts]
end
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
index 80d087a9ea..5394c1b28b 100644
--- a/activerecord/lib/active_record/relation/spawn_methods.rb
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/slice'
require 'active_record/relation/merger'
@@ -24,6 +23,13 @@ module ActiveRecord
# # Returns the intersection of all published posts with the 5 most recently created posts.
# # (This is just an example. You'd probably want to do this with a single query!)
#
+ # Procs will be evaluated by merge:
+ #
+ # Post.where(published: true).merge(-> { joins(:comments) })
+ # # => Post.where(published: true).joins(:comments)
+ #
+ # This is mainly intended for sharing common conditions between multiple associations.
+ #
def merge(other)
if other.is_a?(Array)
to_a & other
@@ -34,9 +40,14 @@ module ActiveRecord
end
end
+ # Like #merge, but applies changes in place.
def merge!(other)
- klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
- klass.new(self, other).merge
+ if !other.is_a?(Relation) && other.respond_to?(:to_proc)
+ instance_exec(&other)
+ else
+ klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
+ klass.new(self, other).merge
+ end
end
# Removes from the query the condition(s) specified in +skips+.
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb
index fd276ccf5d..2414a4bbd7 100644
--- a/activerecord/lib/active_record/result.rb
+++ b/activerecord/lib/active_record/result.rb
@@ -10,11 +10,11 @@ module ActiveRecord
attr_reader :columns, :rows, :column_types
- def initialize(columns, rows)
+ def initialize(columns, rows, column_types = {})
@columns = columns
@rows = rows
@hash_rows = nil
- @column_types = {}
+ @column_types = column_types
end
def each
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb
index 46f6c283e3..690409d62c 100644
--- a/activerecord/lib/active_record/sanitization.rb
+++ b/activerecord/lib/active_record/sanitization.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
module ActiveRecord
module Sanitization
@@ -43,6 +42,36 @@ module ActiveRecord
end
end
+ # Accepts a hash of SQL conditions and replaces those attributes
+ # that correspond to a +composed_of+ relationship with their expanded
+ # aggregate attribute values.
+ # Given:
+ # class Person < ActiveRecord::Base
+ # composed_of :address, :class_name => "Address",
+ # :mapping => [%w(address_street street), %w(address_city city)]
+ # end
+ # Then:
+ # { :address => Address.new("813 abc st.", "chicago") }
+ # # => { :address_street => "813 abc st.", :address_city => "chicago" }
+ def expand_hash_conditions_for_aggregates(attrs)
+ expanded_attrs = {}
+ attrs.each do |attr, value|
+ if aggregation = reflect_on_aggregation(attr.to_sym)
+ mapping = aggregation.mapping
+ mapping.each do |field_attr, aggregate_attr|
+ if mapping.size == 1 && !value.respond_to?(aggregate_attr)
+ expanded_attrs[field_attr] = value
+ else
+ expanded_attrs[field_attr] = value.send(aggregate_attr)
+ end
+ end
+ else
+ expanded_attrs[attr] = value
+ end
+ end
+ expanded_attrs
+ end
+
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
# { :name => "foo'bar", :group_id => 4 }
# # => "name='foo''bar' and group_id= 4"
@@ -58,6 +87,8 @@ module ActiveRecord
# { :address => Address.new("123 abc st.", "chicago") }
# # => "address_street='123 abc st.' and address_city='chicago'"
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
+ attrs = expand_hash_conditions_for_aggregates(attrs)
+
table = Arel::Table.new(table_name).alias(default_table_name)
PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b|
connection.visitor.accept b
@@ -148,15 +179,8 @@ module ActiveRecord
end
# TODO: Deprecate this
- def quoted_id #:nodoc:
- quote_value(id, column_for_attribute(self.class.primary_key))
- end
-
- private
-
- # Quote strings appropriately for SQL statements.
- def quote_value(value, column = nil)
- self.class.connection.quote(value, column)
+ def quoted_id
+ self.class.quote_value(id, column_for_attribute(self.class.primary_key))
end
end
end
diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb
index 599e68379a..a540bc0a3b 100644
--- a/activerecord/lib/active_record/schema.rb
+++ b/activerecord/lib/active_record/schema.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActiveRecord
# = Active Record Schema
diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb
index 236ec563d2..ca22154c84 100644
--- a/activerecord/lib/active_record/schema_migration.rb
+++ b/activerecord/lib/active_record/schema_migration.rb
@@ -7,7 +7,11 @@ module ActiveRecord
attr_accessible :version
def self.table_name
- Base.table_name_prefix + 'schema_migrations' + Base.table_name_suffix
+ "#{Base.table_name_prefix}schema_migrations#{Base.table_name_suffix}"
+ end
+
+ def self.index_name
+ "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}"
end
def self.create_table
@@ -15,14 +19,13 @@ module ActiveRecord
connection.create_table(table_name, :id => false) do |t|
t.column :version, :string, :null => false
end
- connection.add_index table_name, :version, :unique => true,
- :name => "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}"
+ connection.add_index table_name, :version, :unique => true, :name => index_name
end
end
def self.drop_table
if connection.table_exists?(table_name)
- connection.remove_index table_name, :name => "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}"
+ connection.remove_index table_name, :name => index_name
connection.drop_table(table_name)
end
end
diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb
index 66a486ae0a..0c3fd1bd29 100644
--- a/activerecord/lib/active_record/scoping.rb
+++ b/activerecord/lib/active_record/scoping.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
module ActiveRecord
module Scoping
diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb
index af51c803a7..a2a85d4b96 100644
--- a/activerecord/lib/active_record/scoping/default.rb
+++ b/activerecord/lib/active_record/scoping/default.rb
@@ -1,5 +1,3 @@
-require 'active_support/concern'
-require 'active_support/deprecation'
module ActiveRecord
module Scoping
@@ -31,14 +29,14 @@ module ActiveRecord
# Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
# }
#
- # It is recommended that you use the block form of unscoped because chaining
- # unscoped with <tt>scope</tt> does not work. Assuming that
+ # It is recommended that you use the block form of unscoped because
+ # chaining unscoped with <tt>scope</tt> does not work. Assuming that
# <tt>published</tt> is a <tt>scope</tt>, the following two statements
- # are equal: the default_scope is applied on both.
+ # are equal: the <tt>default_scope</tt> is applied on both.
#
# Post.unscoped.published
# Post.published
- def unscoped #:nodoc:
+ def unscoped
block_given? ? relation.scoping { yield } : relation
end
diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb
index 2af476c1ba..75f31229b5 100644
--- a/activerecord/lib/active_record/scoping/named.rb
+++ b/activerecord/lib/active_record/scoping/named.rb
@@ -1,9 +1,6 @@
require 'active_support/core_ext/array'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/class/attribute'
-require 'active_support/deprecation'
module ActiveRecord
# = Active Record Named \Scopes
@@ -12,33 +9,26 @@ module ActiveRecord
extend ActiveSupport::Concern
module ClassMethods
- # Returns an anonymous \scope.
+ # Returns an <tt>ActiveRecord::Relation</tt> scope object.
#
- # posts = Post.scoped
+ # posts = Post.all
# posts.size # Fires "select count(*) from posts" and returns the count
# posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
#
- # fruits = Fruit.scoped
+ # fruits = Fruit.all
# fruits = fruits.where(:color => 'red') if options[:red_only]
# fruits = fruits.limit(10) if limited?
#
- # Anonymous \scopes tend to be useful when procedurally generating complex
- # queries, where passing intermediate values (\scopes) around as first-class
- # objects is convenient.
- #
# You can define a \scope that applies to all finders using
# ActiveRecord::Base.default_scope.
- def scoped(options = nil)
+ def all
if current_scope
- scope = current_scope.clone
+ current_scope.clone
else
scope = relation
scope.default_scoped = true
scope
end
-
- scope.merge!(options) if options
- scope
end
##
@@ -189,7 +179,7 @@ module ActiveRecord
singleton_class.send(:define_method, name) do |*args|
options = body.respond_to?(:call) ? unscoped { body.call(*args) } : body
- relation = scoped.merge(options)
+ relation = all.merge(options)
extension ? relation.extending(extension) : relation
end
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
deleted file mode 100644
index 5a256b040b..0000000000
--- a/activerecord/lib/active_record/session_store.rb
+++ /dev/null
@@ -1,363 +0,0 @@
-module ActiveRecord
- # = Active Record Session Store
- #
- # A session store backed by an Active Record class. A default class is
- # provided, but any object duck-typing to an Active Record Session class
- # with text +session_id+ and +data+ attributes is sufficient.
- #
- # The default assumes a +sessions+ tables with columns:
- # +id+ (numeric primary key),
- # +session_id+ (text, or longtext if your session data exceeds 65K), and
- # +data+ (text or longtext; careful if your session data exceeds 65KB).
- #
- # The +session_id+ column should always be indexed for speedy lookups.
- # Session data is marshaled to the +data+ column in Base64 format.
- # If the data you write is larger than the column's size limit,
- # ActionController::SessionOverflowError will be raised.
- #
- # You may configure the table name, primary key, and data column.
- # For example, at the end of <tt>config/application.rb</tt>:
- #
- # ActiveRecord::SessionStore::Session.table_name = 'legacy_session_table'
- # ActiveRecord::SessionStore::Session.primary_key = 'session_id'
- # ActiveRecord::SessionStore::Session.data_column_name = 'legacy_session_data'
- #
- # Note that setting the primary key to the +session_id+ frees you from
- # having a separate +id+ column if you don't want it. However, you must
- # set <tt>session.model.id = session.session_id</tt> by hand! A before filter
- # on ApplicationController is a good place.
- #
- # Since the default class is a simple Active Record, you get timestamps
- # for free if you add +created_at+ and +updated_at+ datetime columns to
- # the +sessions+ table, making periodic session expiration a snap.
- #
- # You may provide your own session class implementation, whether a
- # feature-packed Active Record or a bare-metal high-performance SQL
- # store, by setting
- #
- # ActiveRecord::SessionStore.session_class = MySessionClass
- #
- # You must implement these methods:
- #
- # self.find_by_session_id(session_id)
- # initialize(hash_of_session_id_and_data, options_hash = {})
- # attr_reader :session_id
- # attr_accessor :data
- # save
- # destroy
- #
- # The example SqlBypass class is a generic SQL session store. You may
- # use it as a basis for high-performance database-specific stores.
- class SessionStore < ActionDispatch::Session::AbstractStore
- module ClassMethods # :nodoc:
- def marshal(data)
- ::Base64.encode64(Marshal.dump(data)) if data
- end
-
- def unmarshal(data)
- Marshal.load(::Base64.decode64(data)) if data
- end
-
- def drop_table!
- connection.schema_cache.clear_table_cache!(table_name)
- connection.drop_table table_name
- end
-
- def create_table!
- connection.schema_cache.clear_table_cache!(table_name)
- connection.create_table(table_name) do |t|
- t.string session_id_column, :limit => 255
- t.text data_column_name
- end
- connection.add_index table_name, session_id_column, :unique => true
- end
- end
-
- # The default Active Record class.
- class Session < ActiveRecord::Base
- extend ClassMethods
-
- ##
- # :singleton-method:
- # Customizable data column name. Defaults to 'data'.
- cattr_accessor :data_column_name
- self.data_column_name = 'data'
-
- attr_accessible :session_id, :data, :marshaled_data
-
- before_save :marshal_data!
- before_save :raise_on_session_data_overflow!
-
- class << self
- def data_column_size_limit
- @data_column_size_limit ||= columns_hash[data_column_name].limit
- end
-
- # Hook to set up sessid compatibility.
- def find_by_session_id(session_id)
- setup_sessid_compatibility!
- find_by_session_id(session_id)
- end
-
- private
- def session_id_column
- 'session_id'
- end
-
- # Compatibility with tables using sessid instead of session_id.
- def setup_sessid_compatibility!
- # Reset column info since it may be stale.
- reset_column_information
- if columns_hash['sessid']
- def self.find_by_session_id(*args)
- find_by_sessid(*args)
- end
-
- define_method(:session_id) { sessid }
- define_method(:session_id=) { |session_id| self.sessid = session_id }
- else
- class << self; remove_possible_method :find_by_session_id; end
-
- def self.find_by_session_id(session_id)
- where(session_id: session_id).first
- end
- end
- end
- end
-
- def initialize(attributes = nil, options = {})
- @data = nil
- super
- end
-
- # Lazy-unmarshal session state.
- def data
- @data ||= self.class.unmarshal(read_attribute(@@data_column_name)) || {}
- end
-
- attr_writer :data
-
- # Has the session been loaded yet?
- def loaded?
- @data
- end
-
- private
- def marshal_data!
- return false unless loaded?
- write_attribute(@@data_column_name, self.class.marshal(data))
- end
-
- # Ensures that the data about to be stored in the database is not
- # larger than the data storage column. Raises
- # ActionController::SessionOverflowError.
- def raise_on_session_data_overflow!
- return false unless loaded?
- limit = self.class.data_column_size_limit
- if limit and read_attribute(@@data_column_name).size > limit
- raise ActionController::SessionOverflowError
- end
- end
- end
-
- # A barebones session store which duck-types with the default session
- # store but bypasses Active Record and issues SQL directly. This is
- # an example session model class meant as a basis for your own classes.
- #
- # The database connection, table name, and session id and data columns
- # are configurable class attributes. Marshaling and unmarshaling
- # are implemented as class methods that you may override. By default,
- # marshaling data is
- #
- # ::Base64.encode64(Marshal.dump(data))
- #
- # and unmarshaling data is
- #
- # Marshal.load(::Base64.decode64(data))
- #
- # This marshaling behavior is intended to store the widest range of
- # binary session data in a +text+ column. For higher performance,
- # store in a +blob+ column instead and forgo the Base64 encoding.
- class SqlBypass
- extend ClassMethods
-
- ##
- # :singleton-method:
- # The table name defaults to 'sessions'.
- cattr_accessor :table_name
- @@table_name = 'sessions'
-
- ##
- # :singleton-method:
- # The session id field defaults to 'session_id'.
- cattr_accessor :session_id_column
- @@session_id_column = 'session_id'
-
- ##
- # :singleton-method:
- # The data field defaults to 'data'.
- cattr_accessor :data_column
- @@data_column = 'data'
-
- class << self
- alias :data_column_name :data_column
-
- # Use the ActiveRecord::Base.connection by default.
- attr_writer :connection
-
- # Use the ActiveRecord::Base.connection_pool by default.
- attr_writer :connection_pool
-
- def connection
- @connection ||= ActiveRecord::Base.connection
- end
-
- def connection_pool
- @connection_pool ||= ActiveRecord::Base.connection_pool
- end
-
- # Look up a session by id and unmarshal its data if found.
- def find_by_session_id(session_id)
- if record = connection.select_one("SELECT * FROM #{@@table_name} WHERE #{@@session_id_column}=#{connection.quote(session_id.to_s)}")
- new(:session_id => session_id, :marshaled_data => record['data'])
- end
- end
- end
-
- delegate :connection, :connection=, :connection_pool, :connection_pool=, :to => self
-
- attr_reader :session_id, :new_record
- alias :new_record? :new_record
-
- attr_writer :data
-
- # Look for normal and marshaled data, self.find_by_session_id's way of
- # telling us to postpone unmarshaling until the data is requested.
- # We need to handle a normal data attribute in case of a new record.
- def initialize(attributes)
- @session_id = attributes[:session_id]
- @data = attributes[:data]
- @marshaled_data = attributes[:marshaled_data]
- @new_record = @marshaled_data.nil?
- end
-
- # Returns true if the record is persisted, i.e. it's not a new record
- def persisted?
- !@new_record
- end
-
- # Lazy-unmarshal session state.
- def data
- unless @data
- if @marshaled_data
- @data, @marshaled_data = self.class.unmarshal(@marshaled_data) || {}, nil
- else
- @data = {}
- end
- end
- @data
- end
-
- def loaded?
- @data
- end
-
- def save
- return false unless loaded?
- marshaled_data = self.class.marshal(data)
- connect = connection
-
- if @new_record
- @new_record = false
- connect.update <<-end_sql, 'Create session'
- INSERT INTO #{table_name} (
- #{connect.quote_column_name(session_id_column)},
- #{connect.quote_column_name(data_column)} )
- VALUES (
- #{connect.quote(session_id)},
- #{connect.quote(marshaled_data)} )
- end_sql
- else
- connect.update <<-end_sql, 'Update session'
- UPDATE #{table_name}
- SET #{connect.quote_column_name(data_column)}=#{connect.quote(marshaled_data)}
- WHERE #{connect.quote_column_name(session_id_column)}=#{connect.quote(session_id)}
- end_sql
- end
- end
-
- def destroy
- return if @new_record
-
- connect = connection
- connect.delete <<-end_sql, 'Destroy session'
- DELETE FROM #{table_name}
- WHERE #{connect.quote_column_name(session_id_column)}=#{connect.quote(session_id.to_s)}
- end_sql
- end
- end
-
- # The class used for session storage. Defaults to
- # ActiveRecord::SessionStore::Session
- cattr_accessor :session_class
- self.session_class = Session
-
- SESSION_RECORD_KEY = 'rack.session.record'
- ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY
-
- private
- def get_session(env, sid)
- Base.silence do
- unless sid and session = @@session_class.find_by_session_id(sid)
- # If the sid was nil or if there is no pre-existing session under the sid,
- # force the generation of a new sid and associate a new session associated with the new sid
- sid = generate_sid
- session = @@session_class.new(:session_id => sid, :data => {})
- end
- env[SESSION_RECORD_KEY] = session
- [sid, session.data]
- end
- end
-
- def set_session(env, sid, session_data, options)
- Base.silence do
- record = get_session_model(env, sid)
- record.data = session_data
- return false unless record.save
-
- session_data = record.data
- if session_data && session_data.respond_to?(:each_value)
- session_data.each_value do |obj|
- obj.clear_association_cache if obj.respond_to?(:clear_association_cache)
- end
- end
- end
-
- sid
- end
-
- def destroy_session(env, session_id, options)
- if sid = current_session_id(env)
- Base.silence do
- get_session_model(env, sid).destroy
- env[SESSION_RECORD_KEY] = nil
- end
- end
-
- generate_sid unless options[:drop]
- end
-
- def get_session_model(env, sid)
- if env[ENV_SESSION_OPTIONS_KEY][:id].nil?
- env[SESSION_RECORD_KEY] = find_session(sid)
- else
- env[SESSION_RECORD_KEY] ||= find_session(sid)
- end
- end
-
- def find_session(id)
- @@session_class.find_by_session_id(id) ||
- @@session_class.new(:session_id => id, :data => {})
- end
- end
-end
diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb
index d836acf18f..b4013ecc1e 100644
--- a/activerecord/lib/active_record/store.rb
+++ b/activerecord/lib/active_record/store.rb
@@ -1,6 +1,4 @@
-require 'active_support/concern'
require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
@@ -43,7 +41,7 @@ module ActiveRecord
extend ActiveSupport::Concern
included do
- class_attribute :stored_attributes, instance_writer: false
+ class_attribute :stored_attributes, instance_accessor: false
self.stored_attributes = {}
end
@@ -57,8 +55,7 @@ module ActiveRecord
keys = keys.flatten
keys.each do |key|
define_method("#{key}=") do |value|
- initialize_store_attribute(store_attribute)
- attribute = send(store_attribute)
+ attribute = initialize_store_attribute(store_attribute)
if value != attribute[key]
attribute[key] = value
send :"#{store_attribute}_will_change!"
@@ -66,8 +63,7 @@ module ActiveRecord
end
define_method(key) do
- initialize_store_attribute(store_attribute)
- send(store_attribute)[key]
+ initialize_store_attribute(store_attribute)[key]
end
end
@@ -77,16 +73,12 @@ module ActiveRecord
private
def initialize_store_attribute(store_attribute)
- case attribute = send(store_attribute)
- when ActiveSupport::HashWithIndifferentAccess
- # Already initialized. Do nothing.
- when Hash
- # Initialized as a Hash. Convert to indifferent access.
- send :"#{store_attribute}=", attribute.with_indifferent_access
- else
- # Uninitialized. Set to an indifferent hash.
- send :"#{store_attribute}=", ActiveSupport::HashWithIndifferentAccess.new
+ attribute = send(store_attribute)
+ unless attribute.is_a?(HashWithIndifferentAccess)
+ attribute = IndifferentCoder.as_indifferent_hash(attribute)
+ send :"#{store_attribute}=", attribute
end
+ attribute
end
class IndifferentCoder
@@ -109,7 +101,7 @@ module ActiveRecord
def self.as_indifferent_hash(obj)
case obj
- when ActiveSupport::HashWithIndifferentAccess
+ when HashWithIndifferentAccess
obj
when Hash
obj.with_indifferent_access
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
index f1241502f5..b41cc68b6a 100644
--- a/activerecord/lib/active_record/tasks/database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -3,13 +3,17 @@ module ActiveRecord
module DatabaseTasks # :nodoc:
extend self
- TASKS_PATTERNS = {
- /mysql/ => ActiveRecord::Tasks::MySQLDatabaseTasks,
- /postgresql/ => ActiveRecord::Tasks::PostgreSQLDatabaseTasks,
- /sqlite/ => ActiveRecord::Tasks::SQLiteDatabaseTasks
- }
LOCAL_HOSTS = ['127.0.0.1', 'localhost']
+ def register_task(pattern, task)
+ @tasks ||= {}
+ @tasks[pattern] = task
+ end
+
+ register_task(/mysql/, ActiveRecord::Tasks::MySQLDatabaseTasks)
+ register_task(/postgresql/, ActiveRecord::Tasks::PostgreSQLDatabaseTasks)
+ register_task(/sqlite/, ActiveRecord::Tasks::SQLiteDatabaseTasks)
+
def create(*arguments)
configuration = arguments.first
class_for_adapter(configuration['adapter']).new(*arguments).create
@@ -84,8 +88,8 @@ module ActiveRecord
private
def class_for_adapter(adapter)
- key = TASKS_PATTERNS.keys.detect { |pattern| adapter[pattern] }
- TASKS_PATTERNS[key]
+ key = @tasks.keys.detect { |pattern| adapter[pattern] }
+ @tasks[key]
end
def each_current_configuration(environment)
@@ -111,7 +115,7 @@ module ActiveRecord
end
def local_database?(configuration)
- configuration['host'].in?(LOCAL_HOSTS) || configuration['host'].blank?
+ configuration['host'].blank? || LOCAL_HOSTS.include?(configuration['host'])
end
end
end
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
index c7a6c37d50..c035ad43a2 100644
--- a/activerecord/lib/active_record/test_case.rb
+++ b/activerecord/lib/active_record/test_case.rb
@@ -1,4 +1,3 @@
-require 'active_support/deprecation'
require 'active_support/test_case'
ActiveSupport::Deprecation.warn('ActiveRecord::TestCase is deprecated, please use ActiveSupport::TestCase')
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
index e5b7a6bfba..c32e0d6bf8 100644
--- a/activerecord/lib/active_record/timestamp.rb
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
module ActiveRecord
ActiveSupport.on_load(:active_record_config) do
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index 9cb9b4627b..09318879d5 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -208,6 +208,21 @@ module ActiveRecord
connection.transaction(options, &block)
end
+ # This callback is called after a record has been created, updated, or destroyed.
+ #
+ # You can specify that the callback should only be fired by a certain action with
+ # the +:on+ option:
+ #
+ # after_commit :do_foo, :on => :create
+ # after_commit :do_bar, :on => :update
+ # after_commit :do_baz, :on => :destroy
+ #
+ # Also, to have the callback fired on create and update, but not on destroy:
+ #
+ # after_commit :do_zoo, :if => :persisted?
+ #
+ # Note that transactional fixtures do not play well with this feature. Please
+ # use the +test_after_commit+ gem to have these hooks fired in tests.
def after_commit(*args, &block)
options = args.last
if options.is_a?(Hash) && options[:on]
@@ -217,6 +232,9 @@ module ActiveRecord
set_callback(:commit, :after, *args, &block)
end
+ # This callback is called after a create, update, or destroy are rolled back.
+ #
+ # Please check the documentation of +after_commit+ for options.
def after_rollback(*args, &block)
options = args.last
if options.is_a?(Hash) && options[:on]
@@ -293,12 +311,10 @@ module ActiveRecord
begin
status = yield
rescue ActiveRecord::Rollback
- if defined?(@_start_transaction_state)
- @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
- end
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
status = nil
end
-
+
raise ActiveRecord::Rollback unless status
end
status
@@ -308,7 +324,6 @@ module ActiveRecord
# Save the new record state and id of a record so it can be restored later if a transaction fails.
def remember_transaction_record_state #:nodoc:
- @_start_transaction_state ||= {}
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
@_start_transaction_state[:new_record] = @new_record
@_start_transaction_state[:destroyed] = @destroyed
@@ -317,18 +332,16 @@ module ActiveRecord
# Clear the new record state and id of a record.
def clear_transaction_record_state #:nodoc:
- if defined?(@_start_transaction_state)
- @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
- remove_instance_variable(:@_start_transaction_state) if @_start_transaction_state[:level] < 1
- end
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
+ @_start_transaction_state.clear if @_start_transaction_state[:level] < 1
end
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
def restore_transaction_record_state(force = false) #:nodoc:
- if defined?(@_start_transaction_state)
+ unless @_start_transaction_state.empty?
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
- if @_start_transaction_state[:level] < 1
- restore_state = remove_instance_variable(:@_start_transaction_state)
+ if @_start_transaction_state[:level] < 1 || force
+ restore_state = @_start_transaction_state
was_frozen = @attributes.frozen?
@attributes = @attributes.dup if was_frozen
@new_record = restore_state[:new_record]
@@ -340,13 +353,14 @@ module ActiveRecord
@attributes_cache.delete(self.class.primary_key)
end
@attributes.freeze if was_frozen
+ @_start_transaction_state.clear
end
end
end
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
def transaction_record_state(state) #:nodoc:
- @_start_transaction_state[state] if defined?(@_start_transaction_state)
+ @_start_transaction_state[state]
end
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index d06020b3ce..cef2bbd563 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -81,3 +81,4 @@ end
require "active_record/validations/associated"
require "active_record/validations/uniqueness"
+require "active_record/validations/presence"
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index afce149da9..1fa6629980 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -1,6 +1,6 @@
module ActiveRecord
module Validations
- class AssociatedValidator < ActiveModel::EachValidator
+ class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
def validate_each(record, attribute, value)
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?(record.validation_context) }.any?
record.errors.add(attribute, :invalid, options.merge(:value => value))
@@ -9,7 +9,8 @@ module ActiveRecord
end
module ClassMethods
- # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
+ # Validates whether the associated object or objects are all valid
+ # themselves. Works with any kind of association.
#
# class Book < ActiveRecord::Base
# has_many :pages
@@ -18,23 +19,28 @@ module ActiveRecord
# validates_associated :pages, :library
# end
#
- # WARNING: This validation must not be used on both ends of an association. Doing so will lead to a circular dependency and cause infinite recursion.
+ # WARNING: This validation must not be used on both ends of an association.
+ # Doing so will lead to a circular dependency and cause infinite recursion.
#
- # NOTE: This validation will not fail if the association hasn't been assigned. If you want to
- # ensure that the association is both present and guaranteed to be valid, you also need to
- # use +validates_presence_of+.
+ # NOTE: This validation will not fail if the association hasn't been
+ # assigned. If you want to ensure that the association is both present and
+ # guaranteed to be valid, you also need to use +validates_presence_of+.
#
# Configuration options:
- # * <tt>:message</tt> - A custom error message (default is: "is invalid")
+ #
+ # * <tt>:message</tt> - A custom error message (default is: "is invalid").
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
# validation contexts by default (+nil+), other options are <tt>:create</tt>
# and <tt>:update</tt>.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: => Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
def validates_associated(*attr_names)
validates_with AssociatedValidator, _merge_attributes(attr_names)
end
diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb
new file mode 100644
index 0000000000..056527b512
--- /dev/null
+++ b/activerecord/lib/active_record/validations/presence.rb
@@ -0,0 +1,64 @@
+module ActiveRecord
+ module Validations
+ class PresenceValidator < ActiveModel::Validations::PresenceValidator
+ def validate(record)
+ super
+ attributes.each do |attribute|
+ next unless record.class.reflect_on_association(attribute)
+ value = record.send(attribute)
+ if Array(value).all? { |r| r.marked_for_destruction? }
+ record.errors.add(attribute, :blank, options)
+ end
+ end
+ end
+ end
+
+ module ClassMethods
+ # Validates that the specified attributes are not blank (as defined by
+ # Object#blank?), and, if the attribute is an association, that the
+ # associated object is not marked for destruction. Happens by default
+ # on save.
+ #
+ # class Person < ActiveRecord::Base
+ # has_one :face
+ # validates_presence_of :face
+ # end
+ #
+ # The face attribute must be in the object and it cannot be blank or marked
+ # for destruction.
+ #
+ # If you want to validate the presence of a boolean field (where the real values
+ # are true and false), you will want to use
+ # <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
+ #
+ # This is due to the way Object#blank? handles boolean values:
+ # <tt>false.blank? # => true</tt>.
+ #
+ # This validator defers to the ActiveModel validation for presence, adding the
+ # check to see that an associated object is not marked for destruction. This
+ # prevents the parent object from validating successfully and saving, which then
+ # deletes the associated object, thus putting the parent object into an invalid
+ # state.
+ #
+ # Configuration options:
+ # * <tt>:message</tt> - A custom error message (default is: "can't be blank").
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
+ # the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
+ # <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
+ # or string should return or evaluate to a true or false value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
+ # or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
+ # proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ def validates_presence_of(*attr_names)
+ validates_with PresenceValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 9e4b588ac2..c117872ac8 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -2,7 +2,7 @@ require 'active_support/core_ext/array/prepend_and_append'
module ActiveRecord
module Validations
- class UniquenessValidator < ActiveModel::EachValidator
+ class UniquenessValidator < ActiveModel::EachValidator #:nodoc:
def initialize(options)
super(options.reverse_merge(:case_sensitive => true))
end
@@ -26,7 +26,7 @@ module ActiveRecord
relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.send(:id))) if record.persisted?
Array(options[:scope]).each do |scope_item|
- scope_value = record.send(scope_item)
+ scope_value = record.read_attribute(scope_item)
reflection = record.class.reflect_on_association(scope_item)
if reflection
scope_value = record.send(reflection.foreign_key)
@@ -87,54 +87,67 @@ module ActiveRecord
end
module ClassMethods
- # Validates whether the value of the specified attributes are unique across the system.
- # Useful for making sure that only one user
+ # Validates whether the value of the specified attributes are unique
+ # across the system. Useful for making sure that only one user
# can be named "davidhh".
#
# class Person < ActiveRecord::Base
# validates_uniqueness_of :user_name
# end
#
- # It can also validate whether the value of the specified attributes are unique based on a scope parameter:
+ # It can also validate whether the value of the specified attributes are
+ # unique based on a <tt>:scope</tt> parameter:
#
# class Person < ActiveRecord::Base
- # validates_uniqueness_of :user_name, :scope => :account_id
+ # validates_uniqueness_of :user_name, scope: :account_id
# end
#
- # Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once
- # per semester for a particular class.
+ # Or even multiple scope parameters. For example, making sure that a
+ # teacher can only be on the schedule once per semester for a particular
+ # class.
#
# class TeacherSchedule < ActiveRecord::Base
- # validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
+ # validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
# end
#
- # It is also possible to limit the uniqueness constraint to a set of records matching certain conditions.
- # In this example archived articles are not being taken into consideration when validating uniqueness
+ # It is also possible to limit the uniqueness constraint to a set of
+ # records matching certain conditions. In this example archived articles
+ # are not being taken into consideration when validating uniqueness
# of the title attribute:
#
# class Article < ActiveRecord::Base
- # validates_uniqueness_of :title, :conditions => where('status != ?', 'archived')
+ # validates_uniqueness_of :title, conditions: where('status != ?', 'archived')
# end
#
- # When the record is created, a check is performed to make sure that no record exists in the database
- # with the given value for the specified attribute (that maps to a column). When the record is updated,
+ # When the record is created, a check is performed to make sure that no
+ # record exists in the database with the given value for the specified
+ # attribute (that maps to a column). When the record is updated,
# the same check is made but disregarding the record itself.
#
# Configuration options:
- # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
- # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
- # * <tt>:conditions</tt> - Specify the conditions to be included as a <tt>WHERE</tt> SQL fragment to limit
- # the uniqueness constraint lookup. (e.g. <tt>:conditions => where('status = ?', 'active')</tt>)
- # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
- # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
- # The method, proc or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or
- # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method, proc or string should
- # return or evaluate to a true or false value.
+ #
+ # * <tt>:message</tt> - Specifies a custom error message (default is:
+ # "has already been taken").
+ # * <tt>:scope</tt> - One or more columns by which to limit the scope of
+ # the uniqueness constraint.
+ # * <tt>:conditions</tt> - Specify the conditions to be included as a
+ # <tt>WHERE</tt> SQL fragment to limit the uniqueness constraint lookup
+ # (e.g. <tt>conditions: where('status = ?', 'active')</tt>).
+ # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by
+ # non-text columns (+true+ by default).
+ # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
+ # attribute is +nil+ (default is +false+).
+ # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
+ # attribute is blank (default is +false+).
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should ot occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
#
# === Concurrency and integrity
#
@@ -190,15 +203,16 @@ module ActiveRecord
#
# The bundled ActiveRecord::ConnectionAdapters distinguish unique index
# constraint errors from other types of database errors by throwing an
- # ActiveRecord::RecordNotUnique exception.
- # For other adapters you will have to parse the (database-specific) exception
- # message to detect such a case.
+ # ActiveRecord::RecordNotUnique exception. For other adapters you will
+ # have to parse the (database-specific) exception message to detect such
+ # a case.
+ #
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
+ #
# * ActiveRecord::ConnectionAdapters::MysqlAdapter
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- #
def validates_uniqueness_of(*attr_names)
validates_with UniquenessValidator, _merge_attributes(attr_names)
end
diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
index 1509e34473..f6a432c6e5 100644
--- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
@@ -11,15 +11,36 @@ module ActiveRecord
end
protected
- attr_reader :migration_action
+ attr_reader :migration_action, :join_tables
- def set_local_assigns!
- if file_name =~ /^(add|remove)_.*_(?:to|from)_(.*)/
- @migration_action = $1
- @table_name = $2.pluralize
+ def set_local_assigns!
+ case file_name
+ when /^(add|remove)_.*_(?:to|from)_(.*)/
+ @migration_action = $1
+ @table_name = $2.pluralize
+ when /join_table/
+ if attributes.length == 2
+ @migration_action = 'join'
+ @join_tables = attributes.map(&:plural_name)
+
+ set_index_names
end
end
+ end
+
+ def set_index_names
+ attributes.each_with_index do |attr, i|
+ attr.index_name = [attr, attributes[i - 1]].map{ |a| index_name_for(a) }
+ end
+ end
+ def index_name_for(attribute)
+ if attribute.foreign_key?
+ attribute.name
+ else
+ attribute.name.singularize.foreign_key
+ end.to_sym
+ end
end
end
end
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
index b1a0f83b5f..d5c07aecd3 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
@@ -2,30 +2,50 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<%- if migration_action == 'add' -%>
def change
<% attributes.each do |attribute| -%>
+ <%- if attribute.reference? -%>
+ add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
+ <%- else -%>
add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %>
<%- if attribute.has_index? -%>
add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<%- end -%>
+ <%- end -%>
<%- end -%>
end
+<%- elsif migration_action == 'join' -%>
+ def change
+ create_join_table :<%= join_tables.first %>, :<%= join_tables.second %> do |t|
+ <%- attributes.each do |attribute| -%>
+ <%= '# ' unless attribute.has_index? -%>t.index <%= attribute.index_name %><%= attribute.inject_index_options %>
+ <%- end -%>
+ end
+ end
<%- else -%>
def up
<% attributes.each do |attribute| -%>
- <%- if migration_action -%>
- <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %>
+<%- if migration_action -%>
+ <%- if attribute.reference? -%>
+ remove_reference :<%= table_name %>, :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %>
+ <%- else -%>
+ remove_column :<%= table_name %>, :<%= attribute.name %>
<%- end -%>
<%- end -%>
+<%- end -%>
end
def down
<% attributes.reverse.each do |attribute| -%>
- <%- if migration_action -%>
+<%- if migration_action -%>
+ <%- if attribute.reference? -%>
+ add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
+ <%- else -%>
add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %>
<%- if attribute.has_index? -%>
add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<%- end -%>
<%- end -%>
<%- end -%>
+<%- end -%>
end
<%- end -%>
end
diff --git a/activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb b/activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb
deleted file mode 100644
index 90923f6e74..0000000000
--- a/activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-require 'rails/generators/active_record'
-require 'active_support/core_ext/object/inclusion'
-
-module ActiveRecord
- module Generators
- class SessionMigrationGenerator < Base
- argument :name, :type => :string, :default => "add_sessions_table"
-
- def create_migration_file
- migration_template "migration.rb", "db/migrate/#{file_name}.rb"
- end
-
- protected
-
- def session_table_name
- current_table_name = ActiveRecord::SessionStore::Session.table_name
- if current_table_name.in?(["sessions", "session"])
- current_table_name = (ActiveRecord::Base.pluralize_table_names ? 'session'.pluralize : 'session')
- end
- current_table_name
- end
-
- end
- end
-end
diff --git a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb
deleted file mode 100644
index 9ea3248513..0000000000
--- a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-class <%= migration_class_name %> < ActiveRecord::Migration
- def change
- create_table :<%= session_table_name %> do |t|
- t.string :session_id, :null => false
- t.text :data
- t.timestamps
- end
-
- add_index :<%= session_table_name %>, :session_id
- add_index :<%= session_table_name %>, :updated_at
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
index 5e1c52c9ba..4bccd2cc59 100644
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -70,11 +70,14 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert_equal %w{ id data }, result.columns
@connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+
+ # if there are no bind parameters, it will return a string (due to
+ # the libmysql api)
result = @connection.exec_query('SELECT id, data FROM ex')
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
- assert_equal [[1, 'foo']], result.rows
+ assert_equal [['1', 'foo']], result.rows
end
def test_exec_with_binds
@@ -125,11 +128,12 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert_equal [["STRICT_ALL_TABLES"]], result.rows
end
- def test_mysql_strict_mode_disabled
+ def test_mysql_strict_mode_disabled_dont_override_global_sql_mode
run_without_connection do |orig_connection|
ActiveRecord::Model.establish_connection(orig_connection.merge({:strict => false}))
- result = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal [['']], result.rows
+ global_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@GLOBAL.sql_mode"
+ session_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal global_sql_mode.rows, session_sql_mode.rows
end
end
diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
index 475a292f85..ddfe42b375 100644
--- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
+++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
@@ -26,7 +26,9 @@ module ActiveRecord
result = @conn.exec_query('SELECT number FROM ex WHERE number = 10')
assert_equal 1, result.rows.length
- assert_equal 10, result.rows.last.last
+ # if there are no bind parameters, it will return a string (due to
+ # the libmysql api)
+ assert_equal '10', result.rows.last.last
end
def test_exec_insert_string
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
index 8e3eeac81e..aff971a955 100644
--- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
@@ -130,7 +130,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
end
def test_associations_work_with_reserved_words
- assert_nothing_raised { Select.scoped(:includes => [:groups]).all }
+ assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
end
#the following functions were added to DRY test cases
diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index 276c499276..c63e4fe5b6 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -44,11 +44,12 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert_equal [["STRICT_ALL_TABLES"]], result.rows
end
- def test_mysql_strict_mode_disabled
+ def test_mysql_strict_mode_disabled_dont_override_global_sql_mode
run_without_connection do |orig_connection|
ActiveRecord::Model.establish_connection(orig_connection.merge({:strict => false}))
- result = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal [['']], result.rows
+ global_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@GLOBAL.sql_mode"
+ session_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal global_sql_mode.rows, session_sql_mode.rows
end
end
diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
index 5c2c113c78..9fd07f014e 100644
--- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
@@ -130,7 +130,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
end
def test_associations_work_with_reserved_words
- assert_nothing_raised { Select.scoped(:includes => [:groups]).all }
+ assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
end
#the following functions were added to DRY test cases
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index f823ce33d8..1ff307c735 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -81,5 +81,78 @@ module ActiveRecord
assert_equal 'SCHEMA', @connection.logged[0][1]
end
+ def test_reconnection_after_simulated_disconnection_with_verify
+ assert @connection.active?
+ original_connection_pid = @connection.query('select pg_backend_pid()')
+
+ # Fail with bad connection on next query attempt.
+ raw_connection = @connection.raw_connection
+ raw_connection_class = class << raw_connection ; self ; end
+ raw_connection_class.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def query_fake(*args)
+ if !( @called ||= false )
+ self.stubs(:status).returns(PGconn::CONNECTION_BAD)
+ @called = true
+ raise PGError
+ else
+ self.unstub(:status)
+ query_unfake(*args)
+ end
+ end
+
+ alias query_unfake query
+ alias query query_fake
+ CODE
+
+ begin
+ @connection.verify!
+ new_connection_pid = @connection.query('select pg_backend_pid()')
+ ensure
+ raw_connection_class.class_eval <<-CODE
+ alias query query_unfake
+ undef query_fake
+ CODE
+ end
+
+ assert_not_equal original_connection_pid, new_connection_pid, "Should have a new underlying connection pid"
+ end
+
+ # Must have with_manual_interventions set to true for this
+ # test to run.
+ # When prompted, restart the PostgreSQL server with the
+ # "-m fast" option or kill the individual connection assuming
+ # you know the incantation to do that.
+ # To restart PostgreSQL 9.1 on OS X, installed via MacPorts, ...
+ # sudo su postgres -c "pg_ctl restart -D /opt/local/var/db/postgresql91/defaultdb/ -m fast"
+ def test_reconnection_after_actual_disconnection_with_verify
+ skip "with_manual_interventions is false in configuration" unless ARTest.config['with_manual_interventions']
+
+ original_connection_pid = @connection.query('select pg_backend_pid()')
+
+ # Sanity check.
+ assert @connection.active?
+
+ puts 'Kill the connection now (e.g. by restarting the PostgreSQL ' +
+ 'server with the "-m fast" option) and then press enter.'
+ $stdin.gets
+
+ @connection.verify!
+
+ assert @connection.active?
+
+ # If we get no exception here, then either we re-connected successfully, or
+ # we never actually got disconnected.
+ new_connection_pid = @connection.query('select pg_backend_pid()')
+
+ assert_not_equal original_connection_pid, new_connection_pid,
+ "umm -- looks like you didn't break the connection, because we're still " +
+ "successfully querying with the same connection pid."
+
+ # Repair all fixture connections so other tests won't break.
+ @fixture_connections.each do |c|
+ c.verify!
+ end
+ end
+
end
end
diff --git a/activerecord/test/cases/aggregations_test.rb b/activerecord/test/cases/aggregations_test.rb
new file mode 100644
index 0000000000..48b06a767f
--- /dev/null
+++ b/activerecord/test/cases/aggregations_test.rb
@@ -0,0 +1,160 @@
+require "cases/helper"
+require 'models/customer'
+require 'active_support/core_ext/exception'
+
+class AggregationsTest < ActiveRecord::TestCase
+ fixtures :customers
+
+ def test_find_single_value_object
+ assert_equal 50, customers(:david).balance.amount
+ assert_kind_of Money, customers(:david).balance
+ assert_equal 300, customers(:david).balance.exchange_to("DKK").amount
+ end
+
+ def test_find_multiple_value_object
+ assert_equal customers(:david).address_street, customers(:david).address.street
+ assert(
+ customers(:david).address.close_to?(Address.new("Different Street", customers(:david).address_city, customers(:david).address_country))
+ )
+ end
+
+ def test_change_single_value_object
+ customers(:david).balance = Money.new(100)
+ customers(:david).save
+ assert_equal 100, customers(:david).reload.balance.amount
+ end
+
+ def test_immutable_value_objects
+ customers(:david).balance = Money.new(100)
+ assert_raise(ActiveSupport::FrozenObjectError) { customers(:david).balance.instance_eval { @amount = 20 } }
+ end
+
+ def test_inferred_mapping
+ assert_equal "35.544623640962634", customers(:david).gps_location.latitude
+ assert_equal "-105.9309951055148", customers(:david).gps_location.longitude
+
+ customers(:david).gps_location = GpsLocation.new("39x-110")
+
+ assert_equal "39", customers(:david).gps_location.latitude
+ assert_equal "-110", customers(:david).gps_location.longitude
+
+ customers(:david).save
+
+ customers(:david).reload
+
+ assert_equal "39", customers(:david).gps_location.latitude
+ assert_equal "-110", customers(:david).gps_location.longitude
+ end
+
+ def test_reloaded_instance_refreshes_aggregations
+ assert_equal "35.544623640962634", customers(:david).gps_location.latitude
+ assert_equal "-105.9309951055148", customers(:david).gps_location.longitude
+
+ Customer.update_all("gps_location = '24x113'")
+ customers(:david).reload
+ assert_equal '24x113', customers(:david)['gps_location']
+
+ assert_equal GpsLocation.new('24x113'), customers(:david).gps_location
+ end
+
+ def test_gps_equality
+ assert_equal GpsLocation.new('39x110'), GpsLocation.new('39x110')
+ end
+
+ def test_gps_inequality
+ assert_not_equal GpsLocation.new('39x110'), GpsLocation.new('39x111')
+ end
+
+ def test_allow_nil_gps_is_nil
+ assert_nil customers(:zaphod).gps_location
+ end
+
+ def test_allow_nil_gps_set_to_nil
+ customers(:david).gps_location = nil
+ customers(:david).save
+ customers(:david).reload
+ assert_nil customers(:david).gps_location
+ end
+
+ def test_allow_nil_set_address_attributes_to_nil
+ customers(:zaphod).address = nil
+ assert_nil customers(:zaphod).attributes[:address_street]
+ assert_nil customers(:zaphod).attributes[:address_city]
+ assert_nil customers(:zaphod).attributes[:address_country]
+ end
+
+ def test_allow_nil_address_set_to_nil
+ customers(:zaphod).address = nil
+ customers(:zaphod).save
+ customers(:zaphod).reload
+ assert_nil customers(:zaphod).address
+ end
+
+ def test_nil_raises_error_when_allow_nil_is_false
+ assert_raise(NoMethodError) { customers(:david).balance = nil }
+ end
+
+ def test_allow_nil_address_loaded_when_only_some_attributes_are_nil
+ customers(:zaphod).address_street = nil
+ customers(:zaphod).save
+ customers(:zaphod).reload
+ assert_kind_of Address, customers(:zaphod).address
+ assert_nil customers(:zaphod).address.street
+ end
+
+ def test_nil_assignment_results_in_nil
+ customers(:david).gps_location = GpsLocation.new('39x111')
+ assert_not_nil customers(:david).gps_location
+ customers(:david).gps_location = nil
+ assert_nil customers(:david).gps_location
+ end
+
+ def test_nil_return_from_converter_is_respected_when_allow_nil_is_true
+ customers(:david).non_blank_gps_location = ""
+ customers(:david).save
+ customers(:david).reload
+ assert_nil customers(:david).non_blank_gps_location
+ ensure
+ Customer.gps_conversion_was_run = nil
+ end
+
+ def test_nil_return_from_converter_results_in_failure_when_allow_nil_is_false
+ assert_raises(NoMethodError) do
+ customers(:barney).gps_location = ""
+ end
+ end
+
+ def test_do_not_run_the_converter_when_nil_was_set
+ customers(:david).non_blank_gps_location = nil
+ assert_nil Customer.gps_conversion_was_run
+ end
+
+ def test_custom_constructor
+ assert_equal 'Barney GUMBLE', customers(:barney).fullname.to_s
+ assert_kind_of Fullname, customers(:barney).fullname
+ end
+
+ def test_custom_converter
+ customers(:barney).fullname = 'Barnoit Gumbleau'
+ assert_equal 'Barnoit GUMBLEAU', customers(:barney).fullname.to_s
+ assert_kind_of Fullname, customers(:barney).fullname
+ end
+end
+
+class OverridingAggregationsTest < ActiveRecord::TestCase
+ class Name; end
+ class DifferentName; end
+
+ class Person < ActiveRecord::Base
+ composed_of :composed_of, :mapping => %w(person_first_name first_name)
+ end
+
+ class DifferentPerson < Person
+ composed_of :composed_of, :class_name => 'DifferentName', :mapping => %w(different_person_first_name first_name)
+ end
+
+ def test_composed_of_aggregation_redefinition_reflections_should_differ_and_not_inherited
+ assert_not_equal Person.reflect_on_aggregation(:composed_of),
+ DifferentPerson.reflect_on_aggregation(:composed_of)
+ end
+end
diff --git a/activerecord/test/cases/associations/association_scope_test.rb b/activerecord/test/cases/associations/association_scope_test.rb
new file mode 100644
index 0000000000..d38648202e
--- /dev/null
+++ b/activerecord/test/cases/associations/association_scope_test.rb
@@ -0,0 +1,15 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/author'
+
+module ActiveRecord
+ module Associations
+ class AssociationScopeTest < ActiveRecord::TestCase
+ test 'does not duplicate conditions' do
+ association_scope = AssociationScope.new(Author.new.association(:welcome_posts))
+ wheres = association_scope.scope.where_values.map(&:right)
+ assert_equal wheres.uniq, wheres
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 2c7a240915..5f7825783b 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -73,14 +73,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_eager_loading_with_primary_key
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
- citibank_result = Client.scoped(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key).first
+ citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key).first
assert citibank_result.association_cache.key?(:firm_with_primary_key)
end
def test_eager_loading_with_primary_key_as_symbol
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
- citibank_result = Client.scoped(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key_symbols).first
+ citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key_symbols).first
assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols)
end
@@ -181,8 +181,8 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
end
def test_with_select
- assert_equal Company.find(2).firm_with_select.attributes.size, 1
- assert_equal Company.scoped(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size, 1
+ assert_equal 1, Company.find(2).firm_with_select.attributes.size
+ assert_equal 1, Company.all.merge!(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size
end
def test_belongs_to_counter
@@ -298,12 +298,12 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
- def test_belongs_to_counter_when_update_column
+ def test_belongs_to_counter_when_update_columns
topic = Topic.create!(:title => "37s")
topic.replies.create!(:title => "re: 37s", :content => "rails")
assert_equal 1, Topic.find(topic.id)[:replies_count]
- topic.update_column(:content, "rails is wonderfull")
+ topic.update_columns(content: "rails is wonderfull")
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
@@ -334,7 +334,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_new_record_with_foreign_key_but_no_object
c = Client.new("firm_id" => 1)
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- assert_equal Firm.scoped(:order => "id").first, c.firm_with_basic_id
+ assert_equal Firm.all.merge!(:order => "id").first, c.firm_with_basic_id
end
def test_setting_foreign_key_after_nil_target_loaded
@@ -396,7 +396,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_association_assignment_sticks
post = Post.first
- author1, author2 = Author.scoped(:limit => 2).all
+ author1, author2 = Author.all.merge!(:limit => 2).to_a
assert_not_nil author1
assert_not_nil author2
@@ -498,14 +498,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised do
Account.find(@account.id).save!
- Account.scoped(:includes => :firm).find(@account.id).save!
+ Account.all.merge!(:includes => :firm).find(@account.id).save!
end
@account.firm.delete
assert_nothing_raised do
Account.find(@account.id).save!
- Account.scoped(:includes => :firm).find(@account.id).save!
+ Account.all.merge!(:includes => :firm).find(@account.id).save!
end
end
@@ -524,13 +524,13 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_invalid_belongs_to_dependent_option_nullify_raises_exception
assert_raise ArgumentError do
- Author.belongs_to :special_author_address, :dependent => :nullify
+ Class.new(Author).belongs_to :special_author_address, :dependent => :nullify
end
end
def test_invalid_belongs_to_dependent_option_restrict_raises_exception
assert_raise ArgumentError do
- Author.belongs_to :special_author_address, :dependent => :restrict
+ Class.new(Author).belongs_to :special_author_address, :dependent => :restrict
end
end
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
index 01f7f18397..80bca7f63e 100644
--- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -16,7 +16,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
:categorizations, :people, :categories, :edges, :vertices
def test_eager_association_loading_with_cascaded_two_levels
- authors = Author.scoped(:includes=>{:posts=>:comments}, :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>:comments}, :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
@@ -24,7 +24,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_and_one_level
- authors = Author.scoped(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
@@ -35,16 +35,16 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
def test_eager_association_loading_with_hmt_does_not_table_name_collide_when_joining_associations
assert_nothing_raised do
- Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).all
+ Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).to_a
end
- authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).all
+ authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).to_a
assert_equal 1, assert_no_queries { authors.size }
assert_equal 10, assert_no_queries { authors[0].comments.size }
end
def test_eager_association_loading_grafts_stashed_associations_to_correct_parent
assert_nothing_raised do
- Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').all
+ Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').to_a
end
assert_equal people(:michael), Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').first
end
@@ -54,9 +54,9 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
assert_nothing_raised do
assert_equal 4, categories.count
- assert_equal 4, categories.all.count
+ assert_equal 4, categories.to_a.count
assert_equal 3, categories.count(:distinct => true)
- assert_equal 3, categories.all.uniq.size # Must uniq since instantiating with inner joins will get dupes
+ assert_equal 3, categories.to_a.uniq.size # Must uniq since instantiating with inner joins will get dupes
end
end
@@ -64,7 +64,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations)
assert_nothing_raised do
assert_equal 3, categories.count
- assert_equal 3, categories.all.size
+ assert_equal 3, categories.to_a.size
end
end
@@ -72,7 +72,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts)
assert_nothing_raised do
assert_equal 3, categories.count
- assert_equal 3, categories.all.size
+ assert_equal 3, categories.to_a.size
end
end
@@ -80,11 +80,11 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
authors = Author.joins(:special_posts).includes([:posts, :categorizations])
assert_nothing_raised { authors.count }
- assert_queries(3) { authors.all }
+ assert_queries(3) { authors.to_a }
end
def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
- authors = Author.scoped(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
@@ -92,7 +92,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference
- authors = Author.scoped(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal authors(:david).name, authors[0].name
@@ -100,13 +100,13 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_with_condition
- authors = Author.scoped(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").to_a
assert_equal 1, authors.size
assert_equal 5, authors[0].posts.size
end
def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
- firms = Firm.scoped(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").all
+ firms = Firm.all.merge!(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").to_a
assert_equal 2, firms.size
assert_equal firms.first.account, firms.first.account.firm.account
assert_equal companies(:first_firm).account, assert_no_queries { firms.first.account.firm.account }
@@ -114,7 +114,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_has_many_sti
- topics = Topic.scoped(:includes => :replies, :order => 'topics.id').all
+ topics = Topic.all.merge!(:includes => :replies, :order => 'topics.id').to_a
first, second, = topics(:first).replies.size, topics(:second).replies.size
assert_no_queries do
assert_equal first, topics[0].replies.size
@@ -127,7 +127,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
silly.parent_id = 1
assert silly.save
- topics = Topic.scoped(:includes => :replies, :order => ['topics.id', 'replies_topics.id']).all
+ topics = Topic.all.merge!(:includes => :replies, :order => ['topics.id', 'replies_topics.id']).to_a
assert_no_queries do
assert_equal 2, topics[0].replies.size
assert_equal 0, topics[1].replies.size
@@ -135,14 +135,14 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_belongs_to_sti
- replies = Reply.scoped(:includes => :topic, :order => 'topics.id').all
+ replies = Reply.all.merge!(:includes => :topic, :order => 'topics.id').to_a
assert replies.include?(topics(:second))
assert !replies.include?(topics(:first))
assert_equal topics(:first), assert_no_queries { replies.first.topic }
end
def test_eager_association_loading_with_multiple_stis_and_order
- author = Author.scoped(:includes => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :where => 'posts.id = 4').first
+ author = Author.all.merge!(:includes => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :where => 'posts.id = 4').first
assert_equal authors(:david), author
assert_no_queries do
author.posts.first.special_comments
@@ -151,7 +151,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_of_stis_with_multiple_references
- authors = Author.scoped(:includes => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :where => 'posts.id = 4').all
+ authors = Author.all.merge!(:includes => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :where => 'posts.id = 4').to_a
assert_equal [authors(:david)], authors
assert_no_queries do
authors.first.posts.first.special_comments.first.post.special_comments
@@ -160,7 +160,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_where_first_level_returns_nil
- authors = Author.scoped(:includes => {:post_about_thinking => :comments}, :order => 'authors.id DESC').all
+ authors = Author.all.merge!(:includes => {:post_about_thinking => :comments}, :order => 'authors.id DESC').to_a
assert_equal [authors(:bob), authors(:mary), authors(:david)], authors
assert_no_queries do
authors[2].post_about_thinking.comments.first
@@ -168,12 +168,12 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through
- source = Vertex.scoped(:includes=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id').first
+ source = Vertex.all.merge!(:includes=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id').first
assert_equal vertices(:vertex_4), assert_no_queries { source.sinks.first.sinks.first.sinks.first }
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_and_belongs_to_many
- sink = Vertex.scoped(:includes=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => 'vertices.id DESC').first
+ sink = Vertex.all.merge!(:includes=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => 'vertices.id DESC').first
assert_equal vertices(:vertex_1), assert_no_queries { sink.sources.first.sources.first.sources.first.sources.first }
end
end
diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
index bb0d6bc70b..5ff117eaa0 100644
--- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -92,7 +92,7 @@ class EagerLoadPolyAssocsTest < ActiveRecord::TestCase
end
def test_include_query
- res = ShapeExpression.scoped(:includes => [ :shape, { :paint => :non_poly } ]).all
+ res = ShapeExpression.all.merge!(:includes => [ :shape, { :paint => :non_poly } ]).to_a
assert_equal NUM_SHAPE_EXPRESSIONS, res.size
assert_queries(0) do
res.each do |se|
@@ -122,7 +122,7 @@ class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase
assert_nothing_raised do
# @davey_mcdave doesn't have any author_favorites
includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author }
- Author.scoped(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name').to_a
+ Author.all.merge!(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name').to_a
end
end
end
diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb
index 5805e71249..634f6b63ba 100644
--- a/activerecord/test/cases/associations/eager_singularization_test.rb
+++ b/activerecord/test/cases/associations/eager_singularization_test.rb
@@ -103,43 +103,43 @@ class EagerSingularizationTest < ActiveRecord::TestCase
def test_eager_no_extra_singularization_belongs_to
return unless @have_tables
assert_nothing_raised do
- Virus.scoped(:includes => :octopus).all
+ Virus.all.merge!(:includes => :octopus).to_a
end
end
def test_eager_no_extra_singularization_has_one
return unless @have_tables
assert_nothing_raised do
- Octopus.scoped(:includes => :virus).all
+ Octopus.all.merge!(:includes => :virus).to_a
end
end
def test_eager_no_extra_singularization_has_many
return unless @have_tables
assert_nothing_raised do
- Bus.scoped(:includes => :passes).all
+ Bus.all.merge!(:includes => :passes).to_a
end
end
def test_eager_no_extra_singularization_has_and_belongs_to_many
return unless @have_tables
assert_nothing_raised do
- Crisis.scoped(:includes => :messes).all
- Mess.scoped(:includes => :crises).all
+ Crisis.all.merge!(:includes => :messes).to_a
+ Mess.all.merge!(:includes => :crises).to_a
end
end
def test_eager_no_extra_singularization_has_many_through_belongs_to
return unless @have_tables
assert_nothing_raised do
- Crisis.scoped(:includes => :successes).all
+ Crisis.all.merge!(:includes => :successes).to_a
end
end
def test_eager_no_extra_singularization_has_many_through_has_many
return unless @have_tables
assert_nothing_raised do
- Crisis.scoped(:includes => :compresses).all
+ Crisis.all.merge!(:includes => :compresses).to_a
end
end
end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 31b11ee334..124bf65d3a 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -30,42 +30,42 @@ class EagerAssociationTest < ActiveRecord::TestCase
:developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
def test_eager_with_has_one_through_join_model_with_conditions_on_the_through
- member = Member.scoped(:includes => :favourite_club).find(members(:some_other_guy).id)
+ member = Member.all.merge!(:includes => :favourite_club).find(members(:some_other_guy).id)
assert_nil member.favourite_club
end
def test_loading_with_one_association
- posts = Post.scoped(:includes => :comments).all
+ posts = Post.all.merge!(:includes => :comments).to_a
post = posts.find { |p| p.id == 1 }
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
- post = Post.scoped(:includes => :comments, :where => "posts.title = 'Welcome to the weblog'").first
+ post = Post.all.merge!(:includes => :comments, :where => "posts.title = 'Welcome to the weblog'").first
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
- posts = Post.scoped(:includes => :last_comment).all
+ posts = Post.all.merge!(:includes => :last_comment).to_a
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end
def test_loading_with_one_association_with_non_preload
- posts = Post.scoped(:includes => :last_comment, :order => 'comments.id DESC').all
+ posts = Post.all.merge!(:includes => :last_comment, :order => 'comments.id DESC').to_a
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end
def test_loading_conditions_with_or
- posts = authors(:david).posts.references(:comments).scoped(
+ posts = authors(:david).posts.references(:comments).merge(
:includes => :comments,
:where => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'"
- ).all
+ ).to_a
assert_nil posts.detect { |p| p.author_id != authors(:david).id },
"expected to find only david's posts"
end
def test_with_ordering
- list = Post.scoped(:includes => :comments, :order => "posts.id DESC").all
+ list = Post.all.merge!(:includes => :comments, :order => "posts.id DESC").to_a
[:other_by_mary, :other_by_bob, :misc_by_mary, :misc_by_bob, :eager_other,
:sti_habtm, :sti_post_and_comments, :sti_comments, :authorless, :thinking, :welcome
].each_with_index do |post, index|
@@ -79,14 +79,14 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_loading_with_multiple_associations
- posts = Post.scoped(:includes => [ :comments, :author, :categories ], :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :comments, :author, :categories ], :order => "posts.id").to_a
assert_equal 2, posts.first.comments.size
assert_equal 2, posts.first.categories.size
assert posts.first.comments.include?(comments(:greetings))
end
def test_duplicate_middle_objects
- comments = Comment.scoped(:where => 'post_id = 1', :includes => [:post => :author]).all
+ comments = Comment.all.merge!(:where => 'post_id = 1', :includes => [:post => :author]).to_a
assert_no_queries do
comments.each {|comment| comment.post.author.name}
end
@@ -94,25 +94,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_preloading_has_many_in_multiple_queries_with_more_ids_than_database_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(5)
- posts = Post.scoped(:includes=>:comments).all
+ posts = Post.all.merge!(:includes=>:comments).to_a
assert_equal 11, posts.size
end
def test_preloading_has_many_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
- posts = Post.scoped(:includes=>:comments).all
+ posts = Post.all.merge!(:includes=>:comments).to_a
assert_equal 11, posts.size
end
def test_preloading_habtm_in_multiple_queries_with_more_ids_than_database_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(5)
- posts = Post.scoped(:includes=>:categories).all
+ posts = Post.all.merge!(:includes=>:categories).to_a
assert_equal 11, posts.size
end
def test_preloading_habtm_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
- posts = Post.scoped(:includes=>:categories).all
+ posts = Post.all.merge!(:includes=>:categories).to_a
assert_equal 11, posts.size
end
@@ -149,8 +149,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
popular_post.readers.create!(:person => people(:michael))
popular_post.readers.create!(:person => people(:david))
- readers = Reader.scoped(:where => ["post_id = ?", popular_post.id],
- :includes => {:post => :comments}).all
+ readers = Reader.all.merge!(:where => ["post_id = ?", popular_post.id],
+ :includes => {:post => :comments}).to_a
readers.each do |reader|
assert_equal [comment], reader.post.comments
end
@@ -162,8 +162,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
car_post.categories << categories(:technology)
comment = car_post.comments.create!(:body => "hmm")
- categories = Category.scoped(:where => { 'posts.id' => car_post.id },
- :includes => {:posts => :comments}).all
+ categories = Category.all.merge!(:where => { 'posts.id' => car_post.id },
+ :includes => {:posts => :comments}).to_a
categories.each do |category|
assert_equal [comment], category.posts[0].comments
end
@@ -181,7 +181,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_has_many_association_with_same_include_includes_only_once
author_id = authors(:david).id
- author = assert_queries(3) { Author.scoped(:includes => {:posts_with_comments => :comments}).find(author_id) } # find the author, then find the posts, then find the comments
+ author = assert_queries(3) { Author.all.merge!(:includes => {:posts_with_comments => :comments}).find(author_id) } # find the author, then find the posts, then find the comments
author.posts_with_comments.each do |post_with_comments|
assert_equal post_with_comments.comments.length, post_with_comments.comments.count
assert_nil post_with_comments.comments.to_a.uniq!
@@ -192,7 +192,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
author = authors(:david)
post = author.post_about_thinking_with_last_comment
last_comment = post.last_comment
- author = assert_queries(3) { Author.scoped(:includes => {:post_about_thinking_with_last_comment => :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments
+ author = assert_queries(3) { Author.all.merge!(:includes => {:post_about_thinking_with_last_comment => :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments
assert_no_queries do
assert_equal post, author.post_about_thinking_with_last_comment
assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment
@@ -203,7 +203,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
post = posts(:welcome)
author = post.author
author_address = author.author_address
- post = assert_queries(3) { Post.scoped(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author, then find the address
+ post = assert_queries(3) { Post.all.merge!(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author, then find the address
assert_no_queries do
assert_equal author, post.author_with_address
assert_equal author_address, post.author_with_address.author_address
@@ -213,7 +213,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_null_belongs_to_association_with_same_include_includes_only_once
post = posts(:welcome)
post.update_attributes!(:author => nil)
- post = assert_queries(1) { Post.scoped(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author which is null so no query for the author or address
+ post = assert_queries(1) { Post.all.merge!(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author which is null so no query for the author or address
assert_no_queries do
assert_equal nil, post.author_with_address
end
@@ -222,56 +222,56 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_null_belongs_to_polymorphic_association
sponsor = sponsors(:moustache_club_sponsor_for_groucho)
sponsor.update_attributes!(:sponsorable => nil)
- sponsor = assert_queries(1) { Sponsor.scoped(:includes => :sponsorable).find(sponsor.id) }
+ sponsor = assert_queries(1) { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) }
assert_no_queries do
assert_equal nil, sponsor.sponsorable
end
end
def test_loading_from_an_association
- posts = authors(:david).posts.scoped(:includes => :comments, :order => "posts.id").all
+ posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a
assert_equal 2, posts.first.comments.size
end
def test_loading_from_an_association_that_has_a_hash_of_conditions
assert_nothing_raised do
- Author.scoped(:includes => :hello_posts_with_hash_conditions).all
+ Author.all.merge!(:includes => :hello_posts_with_hash_conditions).to_a
end
- assert !Author.scoped(:includes => :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty?
+ assert !Author.all.merge!(:includes => :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty?
end
def test_loading_with_no_associations
- assert_nil Post.scoped(:includes => :author).find(posts(:authorless).id).author
+ assert_nil Post.all.merge!(:includes => :author).find(posts(:authorless).id).author
end
def test_nested_loading_with_no_associations
assert_nothing_raised do
- Post.scoped(:includes => {:author => :author_addresss}).find(posts(:authorless).id)
+ Post.all.merge!(:includes => {:author => :author_addresss}).find(posts(:authorless).id)
end
end
def test_nested_loading_through_has_one_association
- aa = AuthorAddress.scoped(:includes => {:author => :posts}).find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}).find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order
- aa = AuthorAddress.scoped(:includes => {:author => :posts}, :order => 'author_addresses.id').find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'author_addresses.id').find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order_on_association
- aa = AuthorAddress.scoped(:includes => {:author => :posts}, :order => 'authors.id').find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'authors.id').find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order_on_nested_association
- aa = AuthorAddress.scoped(:includes => {:author => :posts}, :order => 'posts.id').find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'posts.id').find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_conditions
- aa = AuthorAddress.references(:author_addresses).scoped(
+ aa = AuthorAddress.references(:author_addresses).merge(
:includes => {:author => :posts},
:where => "author_addresses.id > 0"
).find author_addresses(:david_address).id
@@ -279,7 +279,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_nested_loading_through_has_one_association_with_conditions_on_association
- aa = AuthorAddress.references(:authors).scoped(
+ aa = AuthorAddress.references(:authors).merge(
:includes => {:author => :posts},
:where => "authors.id > 0"
).find author_addresses(:david_address).id
@@ -287,7 +287,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_nested_loading_through_has_one_association_with_conditions_on_nested_association
- aa = AuthorAddress.references(:posts).scoped(
+ aa = AuthorAddress.references(:posts).merge(
:includes => {:author => :posts},
:where => "posts.id > 0"
).find author_addresses(:david_address).id
@@ -295,12 +295,12 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_belongs_to_and_foreign_keys
- pets = Pet.scoped(:includes => :owner).all
+ pets = Pet.all.merge!(:includes => :owner).to_a
assert_equal 3, pets.length
end
def test_eager_association_loading_with_belongs_to
- comments = Comment.scoped(:includes => :post).all
+ comments = Comment.all.merge!(:includes => :post).to_a
assert_equal 11, comments.length
titles = comments.map { |c| c.post.title }
assert titles.include?(posts(:welcome).title)
@@ -308,31 +308,31 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_belongs_to_and_limit
- comments = Comment.scoped(:includes => :post, :limit => 5, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => 'comments.id').to_a
assert_equal 5, comments.length
assert_equal [1,2,3,5,6], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_conditions
- comments = Comment.scoped(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [5,6,7], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset
- comments = Comment.scoped(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [3,5,6], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions
- comments = Comment.scoped(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [6,7,8], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
- comments = Comment.scoped(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [6,7,8], comments.collect { |c| c.id }
end
@@ -340,7 +340,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name
assert_nothing_raised do
ActiveSupport::Deprecation.silence do
- Comment.scoped(:includes => :post, :where => ['posts.id = ?',4]).all
+ Comment.all.merge!(:includes => :post, :where => ['posts.id = ?',4]).to_a
end
end
end
@@ -348,7 +348,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_conditions_hash
comments = []
assert_nothing_raised do
- comments = Comment.scoped(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').to_a
end
assert_equal 3, comments.length
assert_equal [5,6,7], comments.collect { |c| c.id }
@@ -361,14 +361,14 @@ class EagerAssociationTest < ActiveRecord::TestCase
quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
assert_nothing_raised do
ActiveSupport::Deprecation.silence do
- Comment.scoped(:includes => :post, :where => ["#{quoted_posts_id} = ?",4]).all
+ Comment.all.merge!(:includes => :post, :where => ["#{quoted_posts_id} = ?",4]).to_a
end
end
end
def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name
assert_nothing_raised do
- Comment.scoped(:includes => :post, :order => 'posts.id').all
+ Comment.all.merge!(:includes => :post, :order => 'posts.id').to_a
end
end
@@ -376,25 +376,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
assert_nothing_raised do
ActiveSupport::Deprecation.silence do
- Comment.scoped(:includes => :post, :order => quoted_posts_id).all
+ Comment.all.merge!(:includes => :post, :order => quoted_posts_id).to_a
end
end
end
def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations
- posts = Post.scoped(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').all
+ posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').to_a
assert_equal 1, posts.length
assert_equal [1], posts.collect { |p| p.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations
- posts = Post.scoped(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').all
+ posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').to_a
assert_equal 1, posts.length
assert_equal [2], posts.collect { |p| p.id }
end
def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name
- author_favorite = AuthorFavorite.scoped(:includes => :favorite_author).first
+ author_favorite = AuthorFavorite.all.merge!(:includes => :favorite_author).first
assert_equal authors(:mary), assert_no_queries { author_favorite.favorite_author }
end
@@ -405,26 +405,26 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_load_has_one_quotes_table_and_column_names
- michael = Person.scoped(:includes => :favourite_reference).find(people(:michael))
+ michael = Person.all.merge!(:includes => :favourite_reference).find(people(:michael))
references(:michael_unicyclist)
assert_no_queries{ assert_equal references(:michael_unicyclist), michael.favourite_reference}
end
def test_eager_load_has_many_quotes_table_and_column_names
- michael = Person.scoped(:includes => :references).find(people(:michael))
+ michael = Person.all.merge!(:includes => :references).find(people(:michael))
references(:michael_magician,:michael_unicyclist)
assert_no_queries{ assert_equal references(:michael_magician,:michael_unicyclist), michael.references.sort_by(&:id) }
end
def test_eager_load_has_many_through_quotes_table_and_column_names
- michael = Person.scoped(:includes => :jobs).find(people(:michael))
+ michael = Person.all.merge!(:includes => :jobs).find(people(:michael))
jobs(:magician, :unicyclist)
assert_no_queries{ assert_equal jobs(:unicyclist, :magician), michael.jobs.sort_by(&:id) }
end
def test_eager_load_has_many_with_string_keys
subscriptions = subscriptions(:webster_awdr, :webster_rfr)
- subscriber =Subscriber.scoped(:includes => :subscriptions).find(subscribers(:second).id)
+ subscriber =Subscriber.all.merge!(:includes => :subscriptions).find(subscribers(:second).id)
assert_equal subscriptions, subscriber.subscriptions.sort_by(&:id)
end
@@ -442,25 +442,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_load_has_many_through_with_string_keys
books = books(:awdr, :rfr)
- subscriber = Subscriber.scoped(:includes => :books).find(subscribers(:second).id)
+ subscriber = Subscriber.all.merge!(:includes => :books).find(subscribers(:second).id)
assert_equal books, subscriber.books.sort_by(&:id)
end
def test_eager_load_belongs_to_with_string_keys
subscriber = subscribers(:second)
- subscription = Subscription.scoped(:includes => :subscriber).find(subscriptions(:webster_awdr).id)
+ subscription = Subscription.all.merge!(:includes => :subscriber).find(subscriptions(:webster_awdr).id)
assert_equal subscriber, subscription.subscriber
end
def test_eager_association_loading_with_explicit_join
- posts = Post.scoped(:includes => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => 'author_id').all
+ posts = Post.all.merge!(:includes => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => 'author_id').to_a
assert_equal 1, posts.length
end
def test_eager_with_has_many_through
- posts_with_comments = people(:michael).posts.scoped(:includes => :comments, :order => 'posts.id').all
- posts_with_author = people(:michael).posts.scoped(:includes => :author, :order => 'posts.id').all
- posts_with_comments_and_author = people(:michael).posts.scoped(:includes => [ :comments, :author ], :order => 'posts.id').all
+ posts_with_comments = people(:michael).posts.merge(:includes => :comments, :order => 'posts.id').to_a
+ posts_with_author = people(:michael).posts.merge(:includes => :author, :order => 'posts.id').to_a
+ posts_with_comments_and_author = people(:michael).posts.merge(:includes => [ :comments, :author ], :order => 'posts.id').to_a
assert_equal 2, posts_with_comments.inject(0) { |sum, post| sum += post.comments.size }
assert_equal authors(:david), assert_no_queries { posts_with_author.first.author }
assert_equal authors(:david), assert_no_queries { posts_with_comments_and_author.first.author }
@@ -471,32 +471,32 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.create!(:author => author, :title => "TITLE", :body => "BODY")
author.author_favorites.create(:favorite_author_id => 1)
author.author_favorites.create(:favorite_author_id => 2)
- posts_with_author_favorites = author.posts.scoped(:includes => :author_favorites).all
+ posts_with_author_favorites = author.posts.merge(:includes => :author_favorites).to_a
assert_no_queries { posts_with_author_favorites.first.author_favorites.first.author_id }
end
def test_eager_with_has_many_through_an_sti_join_model
- author = Author.scoped(:includes => :special_post_comments, :order => 'authors.id').first
+ author = Author.all.merge!(:includes => :special_post_comments, :order => 'authors.id').first
assert_equal [comments(:does_it_hurt)], assert_no_queries { author.special_post_comments }
end
def test_eager_with_has_many_through_an_sti_join_model_with_conditions_on_both
- author = Author.scoped(:includes => :special_nonexistant_post_comments, :order => 'authors.id').first
+ author = Author.all.merge!(:includes => :special_nonexistant_post_comments, :order => 'authors.id').first
assert_equal [], author.special_nonexistant_post_comments
end
def test_eager_with_has_many_through_join_model_with_conditions
- assert_equal Author.scoped(:includes => :hello_post_comments,
+ assert_equal Author.all.merge!(:includes => :hello_post_comments,
:order => 'authors.id').first.hello_post_comments.sort_by(&:id),
- Author.scoped(:order => 'authors.id').first.hello_post_comments.sort_by(&:id)
+ Author.all.merge!(:order => 'authors.id').first.hello_post_comments.sort_by(&:id)
end
def test_eager_with_has_many_through_join_model_with_conditions_on_top_level
- assert_equal comments(:more_greetings), Author.scoped(:includes => :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first
+ assert_equal comments(:more_greetings), Author.all.merge!(:includes => :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first
end
def test_eager_with_has_many_through_join_model_with_include
- author_comments = Author.scoped(:includes => :comments_with_include).find(authors(:david).id).comments_with_include.to_a
+ author_comments = Author.all.merge!(:includes => :comments_with_include).find(authors(:david).id).comments_with_include.to_a
assert_no_queries do
author_comments.first.post.title
end
@@ -504,7 +504,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_through_with_conditions_join_model_with_include
post_tags = Post.find(posts(:welcome).id).misc_tags
- eager_post_tags = Post.scoped(:includes => :misc_tags).find(1).misc_tags
+ eager_post_tags = Post.all.merge!(:includes => :misc_tags).find(1).misc_tags
assert_equal post_tags, eager_post_tags
end
@@ -515,16 +515,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_many_and_limit
- posts = Post.scoped(:order => 'posts.id asc', :includes => [ :author, :comments ], :limit => 2).all
+ posts = Post.all.merge!(:order => 'posts.id asc', :includes => [ :author, :comments ], :limit => 2).to_a
assert_equal 2, posts.size
assert_equal 3, posts.inject(0) { |sum, post| sum += post.comments.size }
end
def test_eager_with_has_many_and_limit_and_conditions
if current_adapter?(:OpenBaseAdapter)
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "FETCHBLOB(posts.body) = 'hello'", :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "FETCHBLOB(posts.body) = 'hello'", :order => "posts.id").to_a
else
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a
end
assert_equal 2, posts.size
assert_equal [4,5], posts.collect { |p| p.id }
@@ -532,9 +532,9 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_and_limit_and_conditions_array
if current_adapter?(:OpenBaseAdapter)
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => [ "FETCHBLOB(posts.body) = ?", 'hello' ], :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "FETCHBLOB(posts.body) = ?", 'hello' ], :order => "posts.id").to_a
else
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").to_a
end
assert_equal 2, posts.size
assert_equal [4,5], posts.collect { |p| p.id }
@@ -542,7 +542,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
posts = ActiveSupport::Deprecation.silence do
- Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => [ "authors.name = ?", 'David' ]).all
+ Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "authors.name = ?", 'David' ]).to_a
end
assert_equal 2, posts.size
@@ -553,34 +553,34 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_many_and_limit_and_high_offset
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).to_a
assert_equal 0, posts.size
end
def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions
assert_queries(1) do
posts = Post.references(:authors, :comments).
- scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
- :where => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]).all
+ merge(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
+ :where => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]).to_a
assert_equal 0, posts.size
end
end
def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions
assert_queries(1) do
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
- :where => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }).all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
+ :where => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }).to_a
assert_equal 0, posts.size
end
end
def test_count_eager_with_has_many_and_limit_and_high_offset
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).count(:all)
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).count(:all)
assert_equal 0, posts
end
def test_eager_with_has_many_and_limit_with_no_results
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").to_a
assert_equal 0, posts.size
end
@@ -597,7 +597,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_and_belongs_to_many_and_limit
- posts = Post.scoped(:includes => :categories, :order => "posts.id", :limit => 3).all
+ posts = Post.all.merge!(:includes => :categories, :order => "posts.id", :limit => 3).to_a
assert_equal 3, posts.size
assert_equal 2, posts[0].categories.size
assert_equal 1, posts[1].categories.size
@@ -663,7 +663,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_habtm
- posts = Post.scoped(:includes => :categories, :order => "posts.id").all
+ posts = Post.all.merge!(:includes => :categories, :order => "posts.id").to_a
assert_equal 2, posts[0].categories.size
assert_equal 1, posts[1].categories.size
assert_equal 0, posts[2].categories.size
@@ -672,23 +672,23 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_inheritance
- SpecialPost.scoped(:includes => [ :comments ]).all
+ SpecialPost.all.merge!(:includes => [ :comments ]).to_a
end
def test_eager_has_one_with_association_inheritance
- post = Post.scoped(:includes => [ :very_special_comment ]).find(4)
+ post = Post.all.merge!(:includes => [ :very_special_comment ]).find(4)
assert_equal "VerySpecialComment", post.very_special_comment.class.to_s
end
def test_eager_has_many_with_association_inheritance
- post = Post.scoped(:includes => [ :special_comments ]).find(4)
+ post = Post.all.merge!(:includes => [ :special_comments ]).find(4)
post.special_comments.each do |special_comment|
assert special_comment.is_a?(SpecialComment)
end
end
def test_eager_habtm_with_association_inheritance
- post = Post.scoped(:includes => [ :special_categories ]).find(6)
+ post = Post.all.merge!(:includes => [ :special_categories ]).find(6)
assert_equal 1, post.special_categories.size
post.special_categories.each do |special_category|
assert_equal "SpecialCategory", special_category.class.to_s
@@ -697,7 +697,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_one_dependent_does_not_destroy_dependent
assert_not_nil companies(:first_firm).account
- f = Firm.scoped(:includes => :account,
+ f = Firm.all.merge!(:includes => :account,
:where => ["companies.name = ?", "37signals"]).first
assert_not_nil f.account
assert_equal companies(:first_firm, :reload).account, f.account
@@ -712,22 +712,22 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_invalid_association_reference
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- Post.scoped(:includes=> :monkeys ).find(6)
+ Post.all.merge!(:includes=> :monkeys ).find(6)
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- Post.scoped(:includes=>[ :monkeys ]).find(6)
+ Post.all.merge!(:includes=>[ :monkeys ]).find(6)
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- Post.scoped(:includes=>[ 'monkeys' ]).find(6)
+ Post.all.merge!(:includes=>[ 'monkeys' ]).find(6)
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
- Post.scoped(:includes=>[ :monkeys, :elephants ]).find(6)
+ Post.all.merge!(:includes=>[ :monkeys, :elephants ]).find(6)
}
end
def test_eager_with_default_scope
developer = EagerDeveloperWithDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -735,7 +735,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_class_method
developer = EagerDeveloperWithClassMethodDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -743,7 +743,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_lambda
developer = EagerDeveloperWithLambdaDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -751,7 +751,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_block
developer = EagerDeveloperWithBlockDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -759,58 +759,58 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_callable
developer = EagerDeveloperWithCallableDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
end
def find_all_ordered(className, include=nil)
- className.scoped(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).all
+ className.all.merge!(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).to_a
end
def test_limited_eager_with_order
assert_equal(
posts(:thinking, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => 'UPPER(posts.title)', :limit => 2, :offset => 1
- ).all
+ ).to_a
)
assert_equal(
posts(:sti_post_and_comments, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1
- ).all
+ ).to_a
)
end
def test_limited_eager_with_multiple_order_columns
assert_equal(
posts(:thinking, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1
- ).all
+ ).to_a
)
assert_equal(
posts(:sti_post_and_comments, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1
- ).all
+ ).to_a
)
end
def test_limited_eager_with_numeric_in_association
assert_equal(
people(:david, :susan),
- Person.references(:number1_fans_people).scoped(
+ Person.references(:number1_fans_people).merge(
:includes => [:readers, :primary_contact, :number1_fan],
:where => "number1_fans_people.first_name like 'M%'",
:order => 'people.id', :limit => 2, :offset => 0
- ).all
+ ).to_a
)
end
@@ -823,9 +823,9 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_polymorphic_type_condition
- post = Post.scoped(:includes => :taggings).find(posts(:thinking).id)
+ post = Post.all.merge!(:includes => :taggings).find(posts(:thinking).id)
assert post.taggings.include?(taggings(:thinking_general))
- post = SpecialPost.scoped(:includes => :taggings).find(posts(:thinking).id)
+ post = SpecialPost.all.merge!(:includes => :taggings).find(posts(:thinking).id)
assert post.taggings.include?(taggings(:thinking_general))
end
@@ -876,13 +876,13 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
def test_eager_with_valid_association_as_string_not_symbol
- assert_nothing_raised { Post.scoped(:includes => 'comments').all }
+ assert_nothing_raised { Post.all.merge!(:includes => 'comments').to_a }
end
def test_eager_with_floating_point_numbers
assert_queries(2) do
# Before changes, the floating point numbers will be interpreted as table names and will cause this to run in one query
- Comment.scoped(:where => "123.456 = 123.456", :includes => :post).all
+ Comment.all.merge!(:where => "123.456 = 123.456", :includes => :post).to_a
end
end
@@ -936,21 +936,21 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_load_with_sti_sharing_association
assert_queries(2) do #should not do 1 query per subclass
- Comment.includes(:post).all
+ Comment.includes(:post).to_a
end
end
def test_conditions_on_join_table_with_include_and_limit
- assert_equal 3, Developer.scoped(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).all.size
+ assert_equal 3, Developer.all.merge!(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).to_a.size
end
def test_order_on_join_table_with_include_and_limit
- assert_equal 5, Developer.scoped(:includes => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).all.size
+ assert_equal 5, Developer.all.merge!(:includes => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).to_a.size
end
def test_eager_loading_with_order_on_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:joins => :comments, :includes => :author, :order => 'comments.id DESC').all
+ Post.all.merge!(:joins => :comments, :includes => :author, :order => 'comments.id DESC').to_a
end
assert_equal posts(:eager_other), posts[1]
assert_equal authors(:mary), assert_no_queries { posts[1].author}
@@ -958,37 +958,49 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_loading_with_conditions_on_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
posts = assert_queries(2) do
- Post.scoped(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => 'posts.id').all
+ Post.all.merge!(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => 'posts.id').to_a
end
assert_equal posts(:welcome, :thinking), posts
posts = assert_queries(2) do
- Post.scoped(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').all
+ Post.all.merge!(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').to_a
end
assert_equal posts(:welcome, :thinking), posts
end
+ def test_preload_has_many_with_association_condition_and_default_scope
+ post = Post.create!(:title => 'Beaches', :body => "I like beaches!")
+ Reader.create! :person => people(:david), :post => post
+ LazyReader.create! :person => people(:susan), :post => post
+
+ assert_equal 1, post.lazy_readers.to_a.size
+ assert_equal 2, post.lazy_readers_skimmers_or_not.to_a.size
+
+ post_with_readers = Post.includes(:lazy_readers_skimmers_or_not).find(post.id)
+ assert_equal 2, post_with_readers.lazy_readers_skimmers_or_not.to_a.size
+ end
+
def test_eager_loading_with_conditions_on_string_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
@@ -996,7 +1008,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_loading_with_select_on_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:select => 'posts.*, authors.name as author_name', :includes => :comments, :joins => :author, :order => 'posts.id').all
+ Post.all.merge!(:select => 'posts.*, authors.name as author_name', :includes => :comments, :joins => :author, :order => 'posts.id').to_a
end
assert_equal 'David', posts[0].author_name
assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments}
@@ -1004,14 +1016,14 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_loading_with_conditions_on_join_model_preloads
authors = assert_queries(2) do
- Author.scoped(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").all
+ Author.all.merge!(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").to_a
end
assert_equal authors(:david), authors[0]
assert_equal author_addresses(:david_address), authors[0].author_address
end
def test_preload_belongs_to_uses_exclusive_scope
- people = Person.males.scoped(:includes => :primary_contact).all
+ people = Person.males.merge(:includes => :primary_contact).to_a
assert_not_equal people.length, 0
people.each do |person|
assert_no_queries {assert_not_nil person.primary_contact}
@@ -1020,7 +1032,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_preload_has_many_uses_exclusive_scope
- people = Person.males.includes(:agents).all
+ people = Person.males.includes(:agents).to_a
people.each do |person|
assert_equal Person.find(person.id).agents, person.agents
end
@@ -1038,9 +1050,9 @@ class EagerAssociationTest < ActiveRecord::TestCase
expected = Firm.find(1).clients_using_primary_key.sort_by(&:name)
# Oracle adapter truncates alias to 30 characters
if current_adapter?(:OracleAdapter)
- firm = Firm.scoped(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name').find(1)
+ firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name').find(1)
else
- firm = Firm.scoped(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name').find(1)
+ firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name').find(1)
end
assert_no_queries do
assert_equal expected, firm.clients_using_primary_key
@@ -1049,7 +1061,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_preload_has_one_using_primary_key
expected = accounts(:signals37)
- firm = Firm.scoped(:includes => :account_using_primary_key, :order => 'companies.id').first
+ firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => 'companies.id').first
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
@@ -1057,7 +1069,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_include_has_one_using_primary_key
expected = accounts(:signals37)
- firm = Firm.scoped(:includes => :account_using_primary_key, :order => 'accounts.id').all.detect {|f| f.id == 1}
+ firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => 'accounts.id').to_a.detect {|f| f.id == 1}
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
@@ -1121,7 +1133,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_deep_including_through_habtm
- posts = Post.scoped(:includes => {:categories => :categorizations}, :order => "posts.id").all
+ posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a
assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length }
assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length }
assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index d7c489c2b5..bd5a426ca8 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -64,14 +64,14 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
def test_proxy_association_after_scoped
post = posts(:welcome)
assert_equal post.association(:comments), post.comments.the_association
- assert_equal post.association(:comments), post.comments.scoped.the_association
+ assert_equal post.association(:comments), post.comments.where('1=1').the_association
end
private
def extension_name(model)
- builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, {}) { }
+ builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, nil, {}) { }
builder.send(:wrap_block_extension)
- builder.options[:extend].first.name
+ builder.extension_module.name
end
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 24bb4adf0a..f3520d43e0 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -67,12 +67,15 @@ end
class DeveloperWithCounterSQL < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects,
- :class_name => "DeveloperWithCounterSQL",
- :join_table => "developers_projects",
- :association_foreign_key => "project_id",
- :foreign_key => "developer_id",
- :counter_sql => proc { "SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}" }
+
+ ActiveSupport::Deprecation.silence do
+ has_and_belongs_to_many :projects,
+ :class_name => "DeveloperWithCounterSQL",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id",
+ :foreign_key => "developer_id",
+ :counter_sql => proc { "SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}" }
+ end
end
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
@@ -356,7 +359,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_deleting_array
david = Developer.find(1)
david.projects.reload
- david.projects.delete(Project.all)
+ david.projects.delete(Project.all.to_a)
assert_equal 0, david.projects.size
assert_equal 0, david.projects(true).size
end
@@ -423,7 +426,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_destroying_many
david = Developer.find(1)
david.projects.reload
- projects = Project.all
+ projects = Project.all.to_a
assert_no_difference "Project.count" do
david.projects.destroy(*projects)
@@ -555,21 +558,21 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_find_with_merged_options
assert_equal 1, projects(:active_record).limited_developers.size
- assert_equal 1, projects(:active_record).limited_developers.all.size
- assert_equal 3, projects(:active_record).limited_developers.limit(nil).all.size
+ assert_equal 1, projects(:active_record).limited_developers.to_a.size
+ assert_equal 3, projects(:active_record).limited_developers.limit(nil).to_a.size
end
def test_dynamic_find_should_respect_association_order
# Developers are ordered 'name DESC, id DESC'
high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
- assert_equal high_id_jamis, projects(:active_record).developers.scoped(:where => "name = 'Jamis'").first
+ assert_equal high_id_jamis, projects(:active_record).developers.merge(:where => "name = 'Jamis'").first
assert_equal high_id_jamis, projects(:active_record).developers.find_by_name('Jamis')
end
- def test_find_should_append_to_association_order
+ def test_find_should_prepend_to_association_order
ordered_developers = projects(:active_record).developers.order('projects.id')
- assert_equal ['developers.name desc, developers.id desc', 'projects.id'], ordered_developers.order_values
+ assert_equal ['projects.id', 'developers.name desc, developers.id desc'], ordered_developers.order_values
end
def test_dynamic_find_all_should_respect_readonly_access
@@ -590,7 +593,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_in_association_with_options
- developers = projects(:active_record).developers.all
+ developers = projects(:active_record).developers.to_a
assert_equal 3, developers.size
assert_equal developers(:poor_jamis), projects(:active_record).developers.where("salary < 10000").first
@@ -636,7 +639,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
project = SpecialProject.create("name" => "Special Project")
assert developer.save
developer.projects << project
- developer.update_column("name", "Bruza")
+ developer.update_columns("name" => "Bruza")
assert_equal 1, Developer.connection.select_value(<<-end_sql).to_i
SELECT count(*) FROM developers_projects
WHERE project_id = #{project.id}
@@ -668,7 +671,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_join_table_alias
assert_equal(
3,
- Developer.references(:developers_projects_join).scoped(
+ Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers},
:where => 'developers_projects_join.joined_on IS NOT NULL'
).to_a.size
@@ -684,7 +687,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal(
3,
- Developer.references(:developers_projects_join).scoped(
+ Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers}, :where => 'developers_projects_join.joined_on IS NOT NULL',
:group => group.join(",")
).to_a.size
@@ -692,8 +695,8 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_grouped
- all_posts_from_category1 = Post.scoped(:where => "category_id = 1", :joins => :categories).all
- grouped_posts_of_category1 = Post.scoped(:where => "category_id = 1", :group => "author_id", :select => 'count(posts.id) as posts_count', :joins => :categories).all
+ all_posts_from_category1 = Post.all.merge!(:where => "category_id = 1", :joins => :categories).to_a
+ grouped_posts_of_category1 = Post.all.merge!(:where => "category_id = 1", :group => "author_id", :select => 'count(posts.id) as posts_count', :joins => :categories).to_a
assert_equal 5, all_posts_from_category1.size
assert_equal 2, grouped_posts_of_category1.size
end
@@ -841,4 +844,16 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
developer = project.developers.build
assert project.developers.include?(developer)
end
+
+ test ":insert_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ def klass.name; 'Foo'; end
+ assert_deprecated { klass.has_and_belongs_to_many :posts, :insert_sql => 'lol' }
+ end
+
+ test ":delete_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ def klass.name; 'Foo'; end
+ assert_deprecated { klass.has_and_belongs_to_many :posts, :delete_sql => 'lol' }
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 3ea6201d60..04714f42e9 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -22,7 +22,9 @@ require 'models/engine'
class HasManyAssociationsTestForCountWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
- has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
+ end
end
def test_should_fail
assert_raise(ArgumentError) do
@@ -33,7 +35,9 @@ end
class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
- has_many :custom_line_items, :class_name => 'LineItem', :counter_sql => "SELECT COUNT(*) line_items.* from line_items"
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :counter_sql => "SELECT COUNT(*) line_items.* from line_items"
+ end
end
def test_should_fail
assert_raise(ArgumentError) do
@@ -44,7 +48,9 @@ end
class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
- has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
+ end
end
def test_should_count_distinct_results
@@ -178,7 +184,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
# would be convenient), because this would cause that scope to be applied to any callbacks etc.
def test_build_and_create_should_not_happen_within_scope
car = cars(:honda)
- scoped_count = car.foo_bulbs.scoped.where_values.count
+ scoped_count = car.foo_bulbs.where_values.count
bulb = car.foo_bulbs.build
assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
@@ -227,19 +233,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
def test_counting_with_counter_sql
- assert_equal 2, Firm.scoped(:order => "id").first.clients.count
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.count
end
def test_counting
- assert_equal 2, Firm.scoped(:order => "id").first.plain_clients.count
+ assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count
end
def test_counting_with_single_hash
- assert_equal 1, Firm.scoped(:order => "id").first.plain_clients.where(:name => "Microsoft").count
+ assert_equal 1, Firm.all.merge!(:order => "id").first.plain_clients.where(:name => "Microsoft").count
end
def test_counting_with_column_name_and_hash
- assert_equal 2, Firm.scoped(:order => "id").first.plain_clients.count(:name)
+ assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count(:name)
end
def test_counting_with_association_limit
@@ -249,7 +255,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_finding
- assert_equal 2, Firm.scoped(:order => "id").first.clients.length
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.length
end
def test_finding_array_compatibility
@@ -258,23 +264,23 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_find_with_blank_conditions
[[], {}, nil, ""].each do |blank|
- assert_equal 2, Firm.scoped(:order => "id").first.clients.where(blank).all.size
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.where(blank).to_a.size
end
end
def test_find_many_with_merged_options
assert_equal 1, companies(:first_firm).limited_clients.size
- assert_equal 1, companies(:first_firm).limited_clients.all.size
- assert_equal 2, companies(:first_firm).limited_clients.limit(nil).all.size
+ assert_equal 1, companies(:first_firm).limited_clients.to_a.size
+ assert_equal 2, companies(:first_firm).limited_clients.limit(nil).to_a.size
end
- def test_find_should_append_to_association_order
+ def test_find_should_prepend_to_association_order
ordered_clients = companies(:first_firm).clients_sorted_desc.order('companies.id')
- assert_equal ['id DESC', 'companies.id'], ordered_clients.order_values
+ assert_equal ['companies.id', 'id DESC'], ordered_clients.order_values
end
def test_dynamic_find_should_respect_association_order
- assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.scoped(:where => "type = 'Client'").first
+ assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
end
@@ -284,54 +290,54 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_finding_default_orders
- assert_equal "Summit", Firm.scoped(:order => "id").first.clients.first.name
+ assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients.first.name
end
def test_finding_with_different_class_name_and_order
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_sorted_desc.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name
end
def test_finding_with_foreign_key
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_of_firm.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_of_firm.first.name
end
def test_finding_with_condition
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_like_ms.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms.first.name
end
def test_finding_with_condition_hash
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
end
def test_finding_using_primary_key
- assert_equal "Summit", Firm.scoped(:order => "id").first.clients_using_primary_key.first.name
+ assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name
end
def test_finding_using_sql
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.order("id").first
first_client = firm.clients_using_sql.first
assert_not_nil first_client
assert_equal "Microsoft", first_client.name
assert_equal 1, firm.clients_using_sql.size
- assert_equal 1, Firm.scoped(:order => "id").first.clients_using_sql.size
+ assert_equal 1, Firm.order("id").first.clients_using_sql.size
end
def test_finding_using_sql_take_into_account_only_uniq_ids
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.order("id").first
client = firm.clients_using_sql.first
assert_equal client, firm.clients_using_sql.find(client.id, client.id)
assert_equal client, firm.clients_using_sql.find(client.id, client.id.to_s)
end
def test_counting_using_sql
- assert_equal 1, Firm.scoped(:order => "id").first.clients_using_counter_sql.size
- assert Firm.scoped(:order => "id").first.clients_using_counter_sql.any?
- assert_equal 0, Firm.scoped(:order => "id").first.clients_using_zero_counter_sql.size
- assert !Firm.scoped(:order => "id").first.clients_using_zero_counter_sql.any?
+ assert_equal 1, Firm.order("id").first.clients_using_counter_sql.size
+ assert Firm.order("id").first.clients_using_counter_sql.any?
+ assert_equal 0, Firm.order("id").first.clients_using_zero_counter_sql.size
+ assert !Firm.order("id").first.clients_using_zero_counter_sql.any?
end
def test_counting_non_existant_items_using_sql
- assert_equal 0, Firm.scoped(:order => "id").first.no_clients_using_counter_sql.size
+ assert_equal 0, Firm.order("id").first.no_clients_using_counter_sql.size
end
def test_counting_using_finder_sql
@@ -346,7 +352,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_ids
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
@@ -366,7 +372,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_string_ids_when_using_finder_sql
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.order("id").first
client = firm.clients_using_finder_sql.find("2")
assert_kind_of Client, client
@@ -382,9 +388,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_all
- firm = Firm.scoped(:order => "id").first
- assert_equal 2, firm.clients.scoped(:where => "#{QUOTED_TYPE} = 'Client'").all.length
- assert_equal 1, firm.clients.scoped(:where => "name = 'Summit'").all.length
+ firm = Firm.all.merge!(:order => "id").first
+ assert_equal 2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
+ assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
end
def test_find_each
@@ -428,29 +434,29 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_find_all_sanitized
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- firm = Firm.scoped(:order => "id").first
- summit = firm.clients.scoped(:where => "name = 'Summit'").all
- assert_equal summit, firm.clients.scoped(:where => ["name = ?", "Summit"]).all
- assert_equal summit, firm.clients.scoped(:where => ["name = :name", { :name => "Summit" }]).all
+ firm = Firm.all.merge!(:order => "id").first
+ summit = firm.clients.where("name = 'Summit'").to_a
+ assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
+ assert_equal summit, firm.clients.where("name = :name", { :name => "Summit" }).to_a
end
def test_find_first
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
client2 = Client.find(2)
- assert_equal firm.clients.first, firm.clients.scoped(:order => "id").first
- assert_equal client2, firm.clients.scoped(:where => "#{QUOTED_TYPE} = 'Client'", :order => "id").first
+ assert_equal firm.clients.first, firm.clients.order("id").first
+ assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
end
def test_find_first_sanitized
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
client2 = Client.find(2)
- assert_equal client2, firm.clients.scoped(:where => ["#{QUOTED_TYPE} = ?", 'Client'], :order => "id").first
- assert_equal client2, firm.clients.scoped(:where => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }], :order => "id").first
+ assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = ?", 'Client'], :order => "id").first
+ assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }], :order => "id").first
end
def test_find_all_with_include_and_conditions
assert_nothing_raised do
- Developer.scoped(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).all
+ Developer.all.merge!(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).to_a
end
end
@@ -460,8 +466,8 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_grouped
- all_clients_of_firm1 = Client.scoped(:where => "firm_id = 1").all
- grouped_clients_of_firm1 = Client.scoped(:where => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count').all
+ all_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1").to_a
+ grouped_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count').to_a
assert_equal 2, all_clients_of_firm1.size
assert_equal 1, grouped_clients_of_firm1.size
end
@@ -519,7 +525,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_create_with_bang_on_has_many_raises_when_record_not_saved
assert_raise(ActiveRecord::RecordInvalid) do
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
firm.plain_clients.create!
end
end
@@ -718,7 +724,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_deleting_updates_counter_cache_with_dependent_delete_all
post = posts(:welcome)
- post.update_column(:taggings_with_delete_all_count, post.taggings_count)
+ post.update_columns(taggings_with_delete_all_count: post.taggings_count)
assert_difference "post.reload.taggings_with_delete_all_count", -1 do
post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first)
@@ -727,7 +733,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_deleting_updates_counter_cache_with_dependent_destroy
post = posts(:welcome)
- post.update_column(:taggings_with_destroy_count, post.taggings_count)
+ post.update_columns(taggings_with_destroy_count: post.taggings_count)
assert_difference "post.reload.taggings_with_destroy_count", -1 do
post.taggings_with_destroy.delete(post.taggings_with_destroy.first)
@@ -897,7 +903,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm = Firm.first
# break the vanilla firm_id foreign key
assert_equal 2, firm.clients.count
- firm.clients.first.update_column(:firm_id, nil)
+ firm.clients.first.update_columns(firm_id: nil)
assert_equal 1, firm.clients(true).count
assert_equal 1, firm.clients_using_primary_key_with_delete_all.count
old_record = firm.clients_using_primary_key_with_delete_all.first
@@ -1023,7 +1029,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm = companies(:first_firm)
assert_equal 2, firm.clients.size
firm.destroy
- assert Client.scoped(:where => "firm_id=#{firm.id}").all.empty?
+ assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty?
end
def test_dependence_for_associations_with_hash_condition
@@ -1033,7 +1039,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_destroy_dependent_when_deleted_from_association
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
assert_equal 2, firm.clients.size
client = firm.clients.first
@@ -1061,7 +1067,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm.destroy rescue "do nothing"
- assert_equal 2, Client.scoped(:where => "firm_id=#{firm.id}").all.size
+ assert_equal 2, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size
end
def test_dependence_on_account
@@ -1085,9 +1091,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_restrict
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
-
firm = RestrictedFirm.create!(:name => 'restrict')
firm.companies.create(:name => 'child')
@@ -1095,15 +1098,25 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
assert RestrictedFirm.exists?(:name => 'restrict')
assert firm.companies.exists?(:name => 'child')
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
- def test_restrict_when_dependent_restrict_raises_config_set_to_false
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = false
+ def test_restrict_is_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :posts, dependent: :restrict }
+ end
- firm = RestrictedFirm.create!(:name => 'restrict')
+ def test_restrict_with_exception
+ firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
+ firm.companies.create(:name => 'child')
+
+ assert !firm.companies.empty?
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
+ assert firm.companies.exists?(:name => 'child')
+ end
+
+ def test_restrict_with_error
+ firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
firm.companies.create(:name => 'child')
assert !firm.companies.empty?
@@ -1113,10 +1126,8 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !firm.errors.empty?
assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
- assert RestrictedFirm.exists?(:name => 'restrict')
+ assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
assert firm.companies.exists?(:name => 'child')
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
def test_included_in_collection
@@ -1128,7 +1139,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_replace_with_less
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
firm.clients = [companies(:first_client)]
assert firm.save, "Could not save firm"
firm.reload
@@ -1142,7 +1153,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_replace_with_new
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
firm.save
firm.reload
@@ -1242,7 +1253,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_dynamic_find_should_respect_association_order_for_through
- assert_equal Comment.find(10), authors(:david).comments_desc.scoped(:where => "comments.type = 'SpecialComment'").first
+ assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
end
@@ -1431,7 +1442,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm = Namespaced::Firm.create({ :name => 'Some Company' })
firm.clients.create({ :name => 'Some Client' })
- stats = Namespaced::Firm.scoped(
+ stats = Namespaced::Firm.all.merge!(
:select => "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
:joins => :clients,
:group => "#{Namespaced::Firm.table_name}.id"
@@ -1460,14 +1471,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_creating_using_primary_key
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
client = firm.clients_using_primary_key.create!(:name => 'test')
assert_equal firm.name, client.firm_name
end
def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
- class_eval <<-EOF
+ class_eval(<<-EOF, __FILE__, __LINE__ + 1)
class DeleteAllModel < ActiveRecord::Base
has_many :nonentities, :dependent => :delete_all
end
@@ -1476,7 +1487,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
- class_eval <<-EOF
+ class_eval(<<-EOF, __FILE__, __LINE__ + 1)
class NullifyModel < ActiveRecord::Base
has_many :nonentities, :dependent => :nullify
end
@@ -1596,18 +1607,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [bulb1, bulb3], result
end
- def test_building_has_many_association_with_restrict_dependency
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
-
- klass = Class.new(ActiveRecord::Base)
-
- assert_deprecated { klass.has_many :companies, :dependent => :restrict }
- assert_not_deprecated { klass.has_many :companies }
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
- end
-
def test_collection_association_with_private_kernel_method
firm = companies(:first_firm)
assert_equal [accounts(:signals37)], firm.accounts.open
@@ -1638,4 +1637,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
post.taggings_with_delete_all.delete_all
end
end
+
+ test ":finder_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :foo, :finder_sql => 'lol' }
+ end
+
+ test ":counter_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :foo, :counter_sql => 'lol' }
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 1c06007d86..36e5ba9660 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -327,7 +327,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_update_counter_caches_on_delete_with_dependent_destroy
post = posts(:welcome)
tag = post.tags.create!(:name => 'doomed')
- post.update_column(:tags_with_destroy_count, post.tags.count)
+ post.update_columns(tags_with_destroy_count: post.tags.count)
assert_difference ['post.reload.taggings_count', 'post.reload.tags_with_destroy_count'], -1 do
posts(:welcome).tags_with_destroy.delete(tag)
@@ -337,7 +337,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_update_counter_caches_on_delete_with_dependent_nullify
post = posts(:welcome)
tag = post.tags.create!(:name => 'doomed')
- post.update_column(:tags_with_nullify_count, post.tags.count)
+ post.update_columns(tags_with_nullify_count: post.tags.count)
assert_no_difference 'post.reload.taggings_count' do
assert_difference 'post.reload.tags_with_nullify_count', -1 do
@@ -706,7 +706,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_through_association_readonly_should_be_false
assert !people(:michael).posts.first.readonly?
- assert !people(:michael).posts.all.first.readonly?
+ assert !people(:michael).posts.to_a.first.readonly?
end
def test_can_update_through_association
@@ -742,7 +742,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_has_many_through_with_default_scope_on_join_model
- assert_equal posts(:welcome).comments.order('id').all, authors(:david).comments_on_first_posts
+ assert_equal posts(:welcome).comments.order('id').to_a, authors(:david).comments_on_first_posts
end
def test_create_has_many_through_with_default_scope_on_join_model
@@ -813,13 +813,6 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert post[:author_count].nil?
end
- def test_interpolated_conditions
- post = posts(:welcome)
- assert !post.tags.empty?
- assert_equal post.tags, post.interpolated_tags
- assert_equal post.tags, post.interpolated_tags_2
- end
-
def test_primary_key_option_on_source
post = posts(:welcome)
category = categories(:general)
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index 88ec65706c..8bc633f2b5 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -25,13 +25,13 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_queries(1) { assert_nil firm.account }
assert_queries(0) { assert_nil firm.account }
- firms = Firm.scoped(:includes => :account).all
+ firms = Firm.all.merge!(:includes => :account).to_a
assert_queries(0) { firms.each(&:account) }
end
def test_with_select
assert_equal Firm.find(1).account_with_select.attributes.size, 2
- assert_equal Firm.scoped(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
+ assert_equal Firm.all.merge!(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
end
def test_finding_using_primary_key
@@ -156,10 +156,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { firm.destroy }
end
- def test_dependence_with_restrict
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
-
+ def test_restrict
firm = RestrictedFirm.create!(:name => 'restrict')
firm.create_account(:credit_limit => 10)
@@ -168,38 +165,26 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
assert RestrictedFirm.exists?(:name => 'restrict')
assert firm.account.present?
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
- def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = false
+ def test_restrict_is_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_one :post, dependent: :restrict }
+ end
- firm = RestrictedFirm.create!(:name => 'restrict')
+ def test_restrict_with_exception
+ firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
firm.create_account(:credit_limit => 10)
assert_not_nil firm.account
- firm.destroy
-
- assert !firm.errors.empty?
- assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
- assert RestrictedFirm.exists?(:name => 'restrict')
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
assert firm.account.present?
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
- def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false_and_attribute_name
- old_backend = I18n.backend
- I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations 'en', :activerecord => {:attributes => {:restricted_firm => {:account => "account model"}}}
-
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = false
-
- firm = RestrictedFirm.create!(:name => 'restrict')
+ def test_restrict_with_error
+ firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
firm.create_account(:credit_limit => 10)
assert_not_nil firm.account
@@ -207,12 +192,9 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
firm.destroy
assert !firm.errors.empty?
- assert_equal "Cannot delete record because a dependent account model exists", firm.errors[:base].first
- assert RestrictedFirm.exists?(:name => 'restrict')
+ assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
+ assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
assert firm.account.present?
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
- I18n.backend = old_backend
end
def test_successful_build_association
@@ -226,7 +208,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_build_and_create_should_not_happen_within_scope
pirate = pirates(:blackbeard)
- scoped_count = pirate.association(:foo_bulb).scoped.where_values.count
+ scoped_count = pirate.association(:foo_bulb).scope.where_values.count
bulb = pirate.build_foo_bulb
assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
@@ -346,14 +328,14 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised do
Firm.find(@firm.id).save!
- Firm.scoped(:includes => :account).find(@firm.id).save!
+ Firm.all.merge!(:includes => :account).find(@firm.id).save!
end
@firm.account.destroy
assert_nothing_raised do
Firm.find(@firm.id).save!
- Firm.scoped(:includes => :account).find(@firm.id).save!
+ Firm.all.merge!(:includes => :account).find(@firm.id).save!
end
end
@@ -524,15 +506,16 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal car.id, bulb.attributes_after_initialize['car_id']
end
- def test_building_has_one_association_with_dependent_restrict
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
+ def test_has_one_transaction
+ company = companies(:first_firm)
+ account = Account.find(1)
- klass = Class.new(ActiveRecord::Base)
+ company.account # force loading
+ assert_no_queries { company.account = account }
- assert_deprecated { klass.has_one :account, :dependent => :restrict }
- assert_not_deprecated { klass.has_one :account }
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
+ company.account = nil
+ assert_no_queries { company.account = nil }
+ account = Account.find(2)
+ assert_queries { company.account = account }
end
end
diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb
index 94b9639e57..90c557e886 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -73,7 +73,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_eager_loading
members = assert_queries(3) do #base table, through table, clubs table
- Member.scoped(:includes => :club, :where => ["name = ?", "Groucho Marx"]).all
+ Member.all.merge!(:includes => :club, :where => ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].club}
@@ -81,7 +81,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_eager_loading_through_polymorphic
members = assert_queries(3) do #base table, through table, clubs table
- Member.scoped(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).all
+ Member.all.merge!(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].sponsor_club}
@@ -89,14 +89,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_with_conditions_eager_loading
# conditions on the through table
- assert_equal clubs(:moustache_club), Member.scoped(:includes => :favourite_club).find(@member.id).favourite_club
- memberships(:membership_of_favourite_club).update_column(:favourite, false)
- assert_equal nil, Member.scoped(:includes => :favourite_club).find(@member.id).reload.favourite_club
+ assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :favourite_club).find(@member.id).favourite_club
+ memberships(:membership_of_favourite_club).update_columns(favourite: false)
+ assert_equal nil, Member.all.merge!(:includes => :favourite_club).find(@member.id).reload.favourite_club
# conditions on the source table
- assert_equal clubs(:moustache_club), Member.scoped(:includes => :hairy_club).find(@member.id).hairy_club
- clubs(:moustache_club).update_column(:name, "Association of Clean-Shaven Persons")
- assert_equal nil, Member.scoped(:includes => :hairy_club).find(@member.id).reload.hairy_club
+ assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :hairy_club).find(@member.id).hairy_club
+ clubs(:moustache_club).update_columns(name: "Association of Clean-Shaven Persons")
+ assert_equal nil, Member.all.merge!(:includes => :hairy_club).find(@member.id).reload.hairy_club
end
def test_has_one_through_polymorphic_with_source_type
@@ -104,14 +104,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
end
def test_eager_has_one_through_polymorphic_with_source_type
- clubs = Club.scoped(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).all
+ clubs = Club.all.merge!(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a
# Only the eyebrow fanciers club has a sponsored_member
assert_not_nil assert_no_queries {clubs[0].sponsored_member}
end
def test_has_one_through_nonpreload_eagerloading
members = assert_queries(1) do
- Member.scoped(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').all #force fallback
+ Member.all.merge!(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].club}
@@ -119,7 +119,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_nonpreload_eager_loading_through_polymorphic
members = assert_queries(1) do
- Member.scoped(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').all #force fallback
+ Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].sponsor_club}
@@ -128,7 +128,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save!
members = assert_queries(1) do
- Member.scoped(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC').all #force fallback
+ Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries { members[0].sponsor_club }
@@ -197,7 +197,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
@member.member_detail = @member_detail
@member.organization = @organization
@member_details = assert_queries(3) do
- MemberDetail.scoped(:includes => :member_type).all
+ MemberDetail.all.merge!(:includes => :member_type).to_a
end
@new_detail = @member_details[0]
assert @new_detail.send(:association, :member_type).loaded?
@@ -210,14 +210,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised do
Club.find(@club.id).save!
- Club.scoped(:includes => :sponsored_member).find(@club.id).save!
+ Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
end
@club.sponsor.destroy
assert_nothing_raised do
Club.find(@club.id).save!
- Club.scoped(:includes => :sponsored_member).find(@club.id).save!
+ Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
end
end
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 1d61d5c474..4f246f575e 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -71,18 +71,18 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
end
def test_count_honors_implicit_inner_joins
- real_count = Author.scoped.to_a.sum{|a| a.posts.count }
+ real_count = Author.all.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.joins(:posts).count, "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins
- real_count = Author.scoped.to_a.sum{|a| a.posts.count }
+ real_count = Author.all.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.joins(:posts).calculate(:count, 'authors.id'), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
- real_count = Author.scoped.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
- authors_with_welcoming_post_titles = Author.scoped(:joins => :posts, :where => "posts.title like 'Welcome%'").calculate(:count, 'authors.id', :distinct => true)
+ real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
+ authors_with_welcoming_post_titles = Author.all.merge!(:joins => :posts, :where => "posts.title like 'Welcome%'").calculate(:count, 'authors.id', :distinct => true)
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index f35ffb2994..aad48e7ce9 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -96,7 +96,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :face).first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :face).first
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -104,7 +104,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
f.man.name = 'Mungo'
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :face, :order => 'faces.id').first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :face, :order => 'faces.id').first
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -179,7 +179,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_eager_loaded_children
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :interests).first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :interests).first
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -189,7 +189,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :interests, :order => 'interests.id').first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :interests, :order => 'interests.id').first
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -259,6 +259,12 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
end
+ def test_parent_instance_should_be_shared_with_first_and_last_child
+ man = Man.first
+ assert man.interests.first.man.equal? man
+ assert man.interests.last.man.equal? man
+ end
+
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.first.secret_interests }
end
@@ -278,7 +284,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.scoped(:includes => :man, :where => {:description => 'trusting'}).first
+ f = Face.all.merge!(:includes => :man, :where => {:description => 'trusting'}).first
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -286,7 +292,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
m.face.description = 'pleasing'
assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
- f = Face.scoped(:includes => :man, :order => 'men.id', :where => {:description => 'trusting'}).first
+ f = Face.all.merge!(:includes => :man, :order => 'men.id', :where => {:description => 'trusting'}).first
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -351,7 +357,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
fixtures :men, :faces, :interests
def test_child_instance_should_be_shared_with_parent_on_find
- f = Face.scoped(:where => {:description => 'confused'}).first
+ f = Face.all.merge!(:where => {:description => 'confused'}).first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -361,7 +367,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.scoped(:where => {:description => 'confused'}, :includes => :man).first
+ f = Face.all.merge!(:where => {:description => 'confused'}, :includes => :man).first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -369,7 +375,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
m.polymorphic_face.description = 'pleasing'
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
- f = Face.scoped(:where => {:description => 'confused'}, :includes => :man, :order => 'men.id').first
+ f = Face.all.merge!(:where => {:description => 'confused'}, :includes => :man, :order => 'men.id').first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 783b83631c..86893ec4b3 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'models/tag'
require 'models/tagging'
require 'models/post'
@@ -51,7 +50,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_uniq_through_find
- assert_equal 1, authors(:mary).unique_categorized_posts.all.size
+ assert_equal 1, authors(:mary).unique_categorized_posts.to_a.size
end
def test_polymorphic_has_many_going_through_join_model
@@ -175,7 +174,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_many_with_delete_all
assert_equal 1, posts(:welcome).taggings.count
- posts(:welcome).taggings.first.update_column :taggable_type, 'PostWithHasManyDeleteAll'
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDeleteAll'
post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)
old_count = Tagging.count
@@ -186,7 +185,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_many_with_destroy
assert_equal 1, posts(:welcome).taggings.count
- posts(:welcome).taggings.first.update_column :taggable_type, 'PostWithHasManyDestroy'
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDestroy'
post = find_post_with_dependency(1, :has_many, :taggings, :destroy)
old_count = Tagging.count
@@ -197,7 +196,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_many_with_nullify
assert_equal 1, posts(:welcome).taggings.count
- posts(:welcome).taggings.first.update_column :taggable_type, 'PostWithHasManyNullify'
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyNullify'
post = find_post_with_dependency(1, :has_many, :taggings, :nullify)
old_count = Tagging.count
@@ -208,7 +207,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_one_with_destroy
assert posts(:welcome).tagging
- posts(:welcome).tagging.update_column :taggable_type, 'PostWithHasOneDestroy'
+ posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneDestroy'
post = find_post_with_dependency(1, :has_one, :tagging, :destroy)
old_count = Tagging.count
@@ -219,7 +218,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_one_with_nullify
assert posts(:welcome).tagging
- posts(:welcome).tagging.update_column :taggable_type, 'PostWithHasOneNullify'
+ posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneNullify'
post = find_post_with_dependency(1, :has_one, :tagging, :nullify)
old_count = Tagging.count
@@ -233,8 +232,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_include_has_many_through
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_authors = Post.scoped(:includes => :authors, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_authors = Post.all.merge!(:includes => :authors, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_authors.length
posts.length.times do |i|
assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length }
@@ -258,8 +257,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_include_polymorphic_has_many_through
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_tags = Post.scoped(:includes => :tags, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_tags = Post.all.merge!(:includes => :tags, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_tags.length
posts.length.times do |i|
assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
@@ -267,8 +266,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_include_polymorphic_has_many
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_taggings = Post.scoped(:includes => :taggings, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_taggings.length
posts.length.times do |i|
assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
@@ -276,7 +275,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_find_all
- assert_equal [categories(:general)], authors(:david).categories.all
+ assert_equal [categories(:general)], authors(:david).categories.to_a
end
def test_has_many_find_first
@@ -288,8 +287,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_find_conditions
- assert_equal categories(:general), authors(:david).categories.scoped(:where => "categories.name = 'General'").first
- assert_nil authors(:david).categories.scoped(:where => "categories.name = 'Technology'").first
+ assert_equal categories(:general), authors(:david).categories.where("categories.name = 'General'").first
+ assert_nil authors(:david).categories.where("categories.name = 'Technology'").first
end
def test_has_many_array_methods_called_by_method_missing
@@ -355,7 +354,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_eager_has_many_polymorphic_with_source_type
- tag_with_include = Tag.scoped(:includes => :tagged_posts).find(tags(:general).id)
+ tag_with_include = Tag.all.merge!(:includes => :tagged_posts).find(tags(:general).id)
desired = posts(:welcome, :thinking)
assert_no_queries do
# added sort by ID as otherwise test using JRuby was failing as array elements were in different order
@@ -365,20 +364,20 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_through_has_many_find_all
- assert_equal comments(:greetings), authors(:david).comments.scoped(:order => 'comments.id').all.first
+ assert_equal comments(:greetings), authors(:david).comments.order('comments.id').to_a.first
end
def test_has_many_through_has_many_find_all_with_custom_class
- assert_equal comments(:greetings), authors(:david).funky_comments.scoped(:order => 'comments.id').all.first
+ assert_equal comments(:greetings), authors(:david).funky_comments.order('comments.id').to_a.first
end
def test_has_many_through_has_many_find_first
- assert_equal comments(:greetings), authors(:david).comments.scoped(:order => 'comments.id').first
+ assert_equal comments(:greetings), authors(:david).comments.order('comments.id').first
end
def test_has_many_through_has_many_find_conditions
options = { :where => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
- assert_equal comments(:does_it_hurt), authors(:david).comments.scoped(options).first
+ assert_equal comments(:does_it_hurt), authors(:david).comments.merge(options).first
end
def test_has_many_through_has_many_find_by_id
@@ -386,7 +385,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_through_polymorphic_has_one
- assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).tagging
+ assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).taggings_2
end
def test_has_many_through_polymorphic_has_many
@@ -402,7 +401,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_eager_load_has_many_through_has_many
- author = Author.scoped(:where => ['name = ?', 'David'], :includes => :comments, :order => 'comments.id').first
+ author = Author.all.merge!(:where => ['name = ?', 'David'], :includes => :comments, :order => 'comments.id').first
SpecialComment.new; VerySpecialComment.new
assert_no_queries do
assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id)
@@ -410,7 +409,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_eager_load_has_many_through_has_many_with_conditions
- post = Post.scoped(:includes => :invalid_tags).first
+ post = Post.all.merge!(:includes => :invalid_tags).first
assert_no_queries do
post.invalid_tags
end
@@ -418,8 +417,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_eager_belongs_to_and_has_one_not_singularized
assert_nothing_raised do
- Author.scoped(:includes => :author_address).first
- AuthorAddress.scoped(:includes => :author).first
+ Author.all.merge!(:includes => :author_address).first
+ AuthorAddress.all.merge!(:includes => :author).first
end
end
@@ -454,7 +453,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert saved_post.tags.include?(new_tag)
assert new_tag.persisted?
- assert new_tag.in?(saved_post.reload.tags(true))
+ assert saved_post.reload.tags(true).include?(new_tag)
new_post = Post.new(:title => "Association replacmenet works!", :body => "You best believe it.")
@@ -467,7 +466,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_post.save!
assert new_post.persisted?
- assert saved_tag.in?(new_post.reload.tags(true))
+ assert new_post.reload.tags(true).include?(saved_tag)
assert !posts(:thinking).tags.build.persisted?
assert !posts(:thinking).tags.new.persisted?
@@ -625,7 +624,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_polymorphic_has_many
expected = taggings(:welcome_general)
- p = Post.scoped(:includes => :taggings).find(posts(:welcome).id)
+ p = Post.all.merge!(:includes => :taggings).find(posts(:welcome).id)
assert_no_queries {assert p.taggings.include?(expected)}
assert posts(:welcome).taggings.include?(taggings(:welcome_general))
end
@@ -633,18 +632,18 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_polymorphic_has_one
expected = posts(:welcome)
- tagging = Tagging.scoped(:includes => :taggable).find(taggings(:welcome_general).id)
+ tagging = Tagging.all.merge!(:includes => :taggable).find(taggings(:welcome_general).id)
assert_no_queries { assert_equal expected, tagging.taggable}
end
def test_polymorphic_belongs_to
- p = Post.scoped(:includes => {:taggings => :taggable}).find(posts(:welcome).id)
+ p = Post.all.merge!(:includes => {:taggings => :taggable}).find(posts(:welcome).id)
assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable}
end
def test_preload_polymorphic_has_many_through
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_tags = Post.scoped(:includes => :tags, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_tags = Post.all.merge!(:includes => :tags, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_tags.length
posts.length.times do |i|
assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
@@ -652,7 +651,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_preload_polymorph_many_types
- taggings = Tagging.scoped(:includes => :taggable, :where => ['taggable_type != ?', 'FakeModel']).all
+ taggings = Tagging.all.merge!(:includes => :taggable, :where => ['taggable_type != ?', 'FakeModel']).to_a
assert_no_queries do
taggings.first.taggable.id
taggings[1].taggable.id
@@ -665,13 +664,13 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_preload_nil_polymorphic_belongs_to
assert_nothing_raised do
- Tagging.scoped(:includes => :taggable, :where => ['taggable_type IS NULL']).all
+ Tagging.all.merge!(:includes => :taggable, :where => ['taggable_type IS NULL']).to_a
end
end
def test_preload_polymorphic_has_many
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_taggings = Post.scoped(:includes => :taggings, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_taggings.length
posts.length.times do |i|
assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
@@ -679,7 +678,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_belongs_to_shared_parent
- comments = Comment.scoped(:includes => :post, :where => 'post_id = 1').all
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 1').to_a
assert_no_queries do
assert_equal comments.first.post, comments[1].post
end
@@ -734,7 +733,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
# create dynamic Post models to allow different dependency options
def find_post_with_dependency(post_id, association, association_name, dependency)
class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
- Post.find(post_id).update_column :type, class_name
+ Post.find(post_id).update_columns type: class_name
klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
klass.table_name = 'posts'
klass.send(association, association_name, :as => :taggable, :dependent => dependency)
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 1d0550afaf..c0f1945cec 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -67,15 +67,15 @@ class AssociationsTest < ActiveRecord::TestCase
ship = Ship.create!(:name => "The good ship Dollypop")
part = ship.parts.create!(:name => "Mast")
part.mark_for_destruction
- ShipPart.find(part.id).update_column(:name, 'Deck')
+ ShipPart.find(part.id).update_columns(name: 'Deck')
ship.parts.send(:load_target)
assert_equal 'Deck', ship.parts[0].name
end
def test_include_with_order_works
- assert_nothing_raised {Account.scoped(:order => 'id', :includes => :firm).first}
- assert_nothing_raised {Account.scoped(:order => :id, :includes => :firm).first}
+ assert_nothing_raised {Account.all.merge!(:order => 'id', :includes => :firm).first}
+ assert_nothing_raised {Account.all.merge!(:order => :id, :includes => :firm).first}
end
def test_bad_collection_keys
@@ -86,7 +86,7 @@ class AssociationsTest < ActiveRecord::TestCase
def test_should_construct_new_finder_sql_after_create
person = Person.new :first_name => 'clark'
- assert_equal [], person.readers.all
+ assert_equal [], person.readers.to_a
person.save!
reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar")
assert person.readers.find(reader.id)
@@ -110,7 +110,7 @@ class AssociationsTest < ActiveRecord::TestCase
end
def test_using_limitable_reflections_helper
- using_limitable_reflections = lambda { |reflections| Tagging.scoped.send :using_limitable_reflections?, reflections }
+ using_limitable_reflections = lambda { |reflections| Tagging.all.send :using_limitable_reflections?, reflections }
belongs_to_reflections = [Tagging.reflect_on_association(:tag), Tagging.reflect_on_association(:super_tag)]
has_many_reflections = [Tag.reflect_on_association(:taggings), Developer.reflect_on_association(:projects)]
mixed_reflections = (belongs_to_reflections + has_many_reflections).uniq
@@ -131,7 +131,7 @@ class AssociationsTest < ActiveRecord::TestCase
def test_association_with_references
firm = companies(:first_firm)
- assert_equal ['foo'], firm.association_with_references.scoped.references_values
+ assert_equal ['foo'], firm.association_with_references.references_values
end
end
@@ -176,7 +176,7 @@ class AssociationProxyTest < ActiveRecord::TestCase
david = developers(:david)
assert !david.projects.loaded?
- david.update_column(:created_at, Time.now)
+ david.update_columns(created_at: Time.now)
assert !david.projects.loaded?
end
@@ -216,7 +216,14 @@ class AssociationProxyTest < ActiveRecord::TestCase
end
def test_scoped_allows_conditions
- assert developers(:david).projects.scoped(where: 'foo').where_values.include?('foo')
+ assert developers(:david).projects.merge!(where: 'foo').where_values.include?('foo')
+ end
+
+ test "getting a scope from an association" do
+ david = developers(:david)
+
+ assert david.projects.scope.is_a?(ActiveRecord::Relation)
+ assert_equal david.projects, david.projects.scope
end
end
diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb
index f4c40b8b97..da5d9d8c2a 100644
--- a/activerecord/test/cases/attribute_methods/read_test.rb
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'thread'
module ActiveRecord
@@ -48,13 +47,13 @@ module ActiveRecord
instance = @klass.new
@klass.column_names.each do |name|
- assert !name.in?(instance.methods.map(&:to_s))
+ assert !instance.methods.map(&:to_s).include?(name)
end
@klass.define_attribute_methods
@klass.column_names.each do |name|
- assert name.in?(instance.methods.map(&:to_s)), "#{name} is not defined"
+ assert instance.methods.map(&:to_s).include?(name), "#{name} is not defined"
end
end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index fe385feb4a..d08b157011 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'models/minimalistic'
require 'models/developer'
require 'models/auto_id'
@@ -35,7 +34,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert t.attribute_present?("written_on")
assert !t.attribute_present?("content")
assert !t.attribute_present?("author_name")
-
end
def test_attribute_present_with_booleans
@@ -397,7 +395,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def test_query_attribute_with_custom_fields
object = Company.find_by_sql(<<-SQL).first
- SELECT c1.*, c2.ruby_type as string_value, c2.rating as int_value
+ SELECT c1.*, c2.type as string_value, c2.rating as int_value
FROM companies c1, companies c2
WHERE c1.firm_id = c2.id
AND c1.id = 2
@@ -484,9 +482,9 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Topic.create(:title => 'Budget')
# Oracle does not support boolean expressions in SELECT
if current_adapter?(:OracleAdapter)
- topic = Topic.scoped(:select => "topics.*, 0 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 0 as is_test").first
else
- topic = Topic.scoped(:select => "topics.*, 1=2 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 1=2 as is_test").first
end
assert !topic.is_test?
end
@@ -495,9 +493,9 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Topic.create(:title => 'Budget')
# Oracle does not support boolean expressions in SELECT
if current_adapter?(:OracleAdapter)
- topic = Topic.scoped(:select => "topics.*, 1 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 1 as is_test").first
else
- topic = Topic.scoped(:select => "topics.*, 2=2 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 2=2 as is_test").first
end
assert topic.is_test?
end
@@ -544,10 +542,10 @@ class AttributeMethodsTest < ActiveRecord::TestCase
val = t.send attr_name unless attr_name == "type"
if attribute_gets_cached
assert cached_columns.include?(attr_name)
- assert_equal val, cache[attr_name]
+ assert_equal val, cache[attr_name.to_sym]
else
assert uncached_columns.include?(attr_name)
- assert !cache.include?(attr_name)
+ assert !cache.include?(attr_name.to_sym)
end
end
end
@@ -731,11 +729,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Object.send(:undef_method, :title) # remove test method from object
end
- def test_list_of_serialized_attributes
- assert_equal %w(content), Topic.serialized_attributes.keys
- assert_equal %w(preferences), Contact.serialized_attributes.keys
- end
-
def test_instance_method_should_be_defined_on_the_base_class
subklass = Class.new(Topic)
@@ -816,7 +809,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
def privatize(method_signature)
- @target.class_eval <<-private_method
+ @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1)
private
def #{method_signature}
"I'm private"
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 8ef3bfef15..fd4f09ab36 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -20,22 +20,6 @@ require 'models/company'
require 'models/eye'
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
- def test_autosave_should_be_a_valid_option_for_has_one
- assert ActiveRecord::Associations::Builder::HasOne.valid_options.include?(:autosave)
- end
-
- def test_autosave_should_be_a_valid_option_for_belongs_to
- assert ActiveRecord::Associations::Builder::BelongsTo.valid_options.include?(:autosave)
- end
-
- def test_autosave_should_be_a_valid_option_for_has_many
- assert ActiveRecord::Associations::Builder::HasMany.valid_options.include?(:autosave)
- end
-
- def test_autosave_should_be_a_valid_option_for_has_and_belongs_to_many
- assert ActiveRecord::Associations::Builder::HasAndBelongsToMany.valid_options.include?(:autosave)
- end
-
def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
assert_no_difference_when_adding_callbacks_twice_for Pirate, :ship
end
@@ -155,7 +139,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
end
def test_not_resaved_when_unchanged
- firm = Firm.scoped(:includes => :account).first
+ firm = Firm.all.merge!(:includes => :account).first
firm.name += '-changed'
assert_queries(1) { firm.save! }
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index e34f505a02..9fcee99222 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -26,7 +26,6 @@ require 'models/bird'
require 'models/teapot'
require 'rexml/document'
require 'active_support/core_ext/exception'
-require 'bcrypt'
class FirstAbstractClass < ActiveRecord::Base
self.abstract_class = true
@@ -131,36 +130,36 @@ class BasicsTest < ActiveRecord::TestCase
unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
def test_limit_with_comma
- assert Topic.limit("1,2").all
+ assert Topic.limit("1,2").to_a
end
end
def test_limit_without_comma
- assert_equal 1, Topic.limit("1").all.length
- assert_equal 1, Topic.limit(1).all.length
+ assert_equal 1, Topic.limit("1").to_a.length
+ assert_equal 1, Topic.limit(1).to_a.length
end
def test_invalid_limit
assert_raises(ArgumentError) do
- Topic.limit("asdfadf").all
+ Topic.limit("asdfadf").to_a
end
end
def test_limit_should_sanitize_sql_injection_for_limit_without_comas
assert_raises(ArgumentError) do
- Topic.limit("1 select * from schema").all
+ Topic.limit("1 select * from schema").to_a
end
end
def test_limit_should_sanitize_sql_injection_for_limit_with_comas
assert_raises(ArgumentError) do
- Topic.limit("1, 7 procedure help()").all
+ Topic.limit("1, 7 procedure help()").to_a
end
end
unless current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
def test_limit_should_allow_sql_literal
- assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length
+ assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
end
end
@@ -231,6 +230,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal 11, Topic.find(1).written_on.sec
assert_equal 223300, Topic.find(1).written_on.usec
assert_equal 9900, Topic.find(2).written_on.usec
+ assert_equal 129346, Topic.find(3).written_on.usec
end
end
@@ -349,13 +349,13 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_load
- topics = Topic.scoped(:order => 'id').all
+ topics = Topic.all.merge!(:order => 'id').to_a
assert_equal(4, topics.size)
assert_equal(topics(:first).title, topics.first.title)
end
def test_load_with_condition
- topics = Topic.scoped(:where => "author_name = 'Mary'").all
+ topics = Topic.all.merge!(:where => "author_name = 'Mary'").to_a
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
@@ -466,13 +466,13 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_singular_table_name_guesses_for_individual_table
- CreditCard.pluralize_table_names = false
- CreditCard.reset_table_name
- assert_equal "credit_card", CreditCard.table_name
+ Post.pluralize_table_names = false
+ Post.reset_table_name
+ assert_equal "post", Post.table_name
assert_equal "categories", Category.table_name
ensure
- CreditCard.pluralize_table_names = true
- CreditCard.reset_table_name
+ Post.pluralize_table_names = true
+ Post.reset_table_name
end
if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
@@ -603,13 +603,19 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "changed", post.body
end
+ def test_attr_readonly_is_class_level_setting
+ post = ReadonlyTitlePost.new
+ assert_raise(NoMethodError) { post._attr_readonly = [:title] }
+ assert_deprecated { post._attr_readonly }
+ end
+
def test_non_valid_identifier_column_name
weird = Weird.create('a$b' => 'value')
weird.reload
assert_equal 'value', weird.send('a$b')
assert_equal 'value', weird.read_attribute('a$b')
- weird.update_column('a$b', 'value2')
+ weird.update_columns('a$b' => 'value2')
weird.reload
assert_equal 'value2', weird.send('a$b')
assert_equal 'value2', weird.read_attribute('a$b')
@@ -907,6 +913,51 @@ class BasicsTest < ActiveRecord::TestCase
end
end
+ def test_multiparameter_assignment_of_aggregation
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country }
+ customer.attributes = attributes
+ assert_equal address, customer.address
+ end
+
+ def test_multiparameter_assignment_of_aggregation_out_of_order
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(3)" => address.country, "address(2)" => address.city, "address(1)" => address.street }
+ customer.attributes = attributes
+ assert_equal address, customer.address
+ end
+
+ def test_multiparameter_assignment_of_aggregation_with_missing_values
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(2)" => address.city, "address(3)" => address.country }
+ customer.attributes = attributes
+ end
+ assert_equal("address", ex.errors[0].attribute)
+ end
+
+ def test_multiparameter_assignment_of_aggregation_with_blank_values
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(1)" => "", "address(2)" => address.city, "address(3)" => address.country }
+ customer.attributes = attributes
+ assert_equal Address.new(nil, "The City", "The Country"), customer.address
+ end
+
+ def test_multiparameter_assignment_of_aggregation_with_large_index
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(1)" => "The Street", "address(2)" => address.city, "address(3000)" => address.country }
+ customer.attributes = attributes
+ end
+
+ assert_equal("address", ex.errors[0].attribute)
+ end
+
def test_attributes_on_dummy_time
# Oracle, and Sybase do not have a TIME datatype.
return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
@@ -996,6 +1047,26 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal("c", duped_topic.title)
end
+ def test_dup_with_aggregate_of_same_name_as_attribute
+ dev = DeveloperWithAggregate.find(1)
+ assert_kind_of DeveloperSalary, dev.salary
+
+ dup = nil
+ assert_nothing_raised { dup = dev.dup }
+ assert_kind_of DeveloperSalary, dup.salary
+ assert_equal dev.salary.amount, dup.salary.amount
+ assert !dup.persisted?
+
+ # test if the attributes have been dupd
+ original_amount = dup.salary.amount
+ dev.salary.amount = 1
+ assert_equal original_amount, dup.salary.amount
+
+ assert dup.save
+ assert dup.persisted?
+ assert_not_equal dup.id, dev.id
+ end
+
def test_dup_does_not_copy_associations
author = authors(:david)
assert_not_equal [], author.posts
@@ -1218,202 +1289,13 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_quoting_arrays
- replies = Reply.scoped(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).all
+ replies = Reply.all.merge!(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a
assert_equal topics(:first).replies.size, replies.size
- replies = Reply.scoped(:where => [ "id IN (?)", [] ]).all
+ replies = Reply.all.merge!(:where => [ "id IN (?)", [] ]).to_a
assert_equal 0, replies.size
end
- MyObject = Struct.new :attribute1, :attribute2
-
- def test_serialized_attribute
- Topic.serialize("content", MyObject)
-
- myobj = MyObject.new('value1', 'value2')
- topic = Topic.create("content" => myobj)
- assert_equal(myobj, topic.content)
-
- topic.reload
- assert_equal(myobj, topic.content)
- end
-
- def test_serialized_attribute_in_base_class
- Topic.serialize("content", Hash)
-
- hash = { 'content1' => 'value1', 'content2' => 'value2' }
- important_topic = ImportantTopic.create("content" => hash)
- assert_equal(hash, important_topic.content)
-
- important_topic.reload
- assert_equal(hash, important_topic.content)
- end
-
- # This test was added to fix GH #4004. Obviously the value returned
- # is not really the value 'before type cast' so we should maybe think
- # about changing that in the future.
- def test_serialized_attribute_before_type_cast_returns_unserialized_value
- klass = Class.new(ActiveRecord::Base)
- klass.table_name = "topics"
- klass.serialize :content, Hash
-
- t = klass.new(:content => { :foo => :bar })
- assert_equal({ :foo => :bar }, t.content_before_type_cast)
- t.save!
- t.reload
- assert_equal({ :foo => :bar }, t.content_before_type_cast)
- end
-
- def test_serialized_attribute_calling_dup_method
- klass = Class.new(ActiveRecord::Base)
- klass.table_name = "topics"
- klass.serialize :content, JSON
-
- t = klass.new(:content => { :foo => :bar }).dup
- assert_equal({ :foo => :bar }, t.content_before_type_cast)
- end
-
- def test_serialized_attribute_declared_in_subclass
- hash = { 'important1' => 'value1', 'important2' => 'value2' }
- important_topic = ImportantTopic.create("important" => hash)
- assert_equal(hash, important_topic.important)
-
- important_topic.reload
- assert_equal(hash, important_topic.important)
- assert_equal(hash, important_topic.read_attribute(:important))
- end
-
- def test_serialized_time_attribute
- myobj = Time.local(2008,1,1,1,0)
- topic = Topic.create("content" => myobj).reload
- assert_equal(myobj, topic.content)
- end
-
- def test_serialized_string_attribute
- myobj = "Yes"
- topic = Topic.create("content" => myobj).reload
- assert_equal(myobj, topic.content)
- end
-
- def test_nil_serialized_attribute_without_class_constraint
- topic = Topic.new
- assert_nil topic.content
- end
-
- def test_nil_not_serialized_without_class_constraint
- assert Topic.new(:content => nil).save
- assert_equal 1, Topic.where(:content => nil).count
- end
-
- def test_nil_not_serialized_with_class_constraint
- Topic.serialize :content, Hash
- assert Topic.new(:content => nil).save
- assert_equal 1, Topic.where(:content => nil).count
- ensure
- Topic.serialize(:content)
- end
-
- def test_should_raise_exception_on_serialized_attribute_with_type_mismatch
- myobj = MyObject.new('value1', 'value2')
- topic = Topic.new(:content => myobj)
- assert topic.save
- Topic.serialize(:content, Hash)
- assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).reload.content }
- ensure
- Topic.serialize(:content)
- end
-
- def test_serialized_attribute_with_class_constraint
- settings = { "color" => "blue" }
- Topic.serialize(:content, Hash)
- topic = Topic.new(:content => settings)
- assert topic.save
- assert_equal(settings, Topic.find(topic.id).content)
- ensure
- Topic.serialize(:content)
- end
-
- def test_serialized_default_class
- Topic.serialize(:content, Hash)
- topic = Topic.new
- assert_equal Hash, topic.content.class
- assert_equal Hash, topic.read_attribute(:content).class
- topic.content["beer"] = "MadridRb"
- assert topic.save
- topic.reload
- assert_equal Hash, topic.content.class
- assert_equal "MadridRb", topic.content["beer"]
- ensure
- Topic.serialize(:content)
- end
-
- def test_serialized_no_default_class_for_object
- topic = Topic.new
- assert_nil topic.content
- end
-
- def test_serialized_boolean_value_true
- Topic.serialize(:content)
- topic = Topic.new(:content => true)
- assert topic.save
- topic = topic.reload
- assert_equal topic.content, true
- end
-
- def test_serialized_boolean_value_false
- Topic.serialize(:content)
- topic = Topic.new(:content => false)
- assert topic.save
- topic = topic.reload
- assert_equal topic.content, false
- end
-
- def test_serialize_with_coder
- coder = Class.new {
- # Identity
- def load(thing)
- thing
- end
-
- # base 64
- def dump(thing)
- [thing].pack('m')
- end
- }.new
-
- Topic.serialize(:content, coder)
- s = 'hello world'
- topic = Topic.new(:content => s)
- assert topic.save
- topic = topic.reload
- assert_equal [s].pack('m'), topic.content
- ensure
- Topic.serialize(:content)
- end
-
- def test_serialize_with_bcrypt_coder
- crypt_coder = Class.new {
- def load(thing)
- return unless thing
- BCrypt::Password.new thing
- end
-
- def dump(thing)
- BCrypt::Password.create(thing).to_s
- end
- }.new
-
- Topic.serialize(:content, crypt_coder)
- password = 'password'
- topic = Topic.new(:content => password)
- assert topic.save
- topic = topic.reload
- assert_kind_of BCrypt::Password, topic.content
- assert_equal(true, topic.content == password, 'password should equal')
- ensure
- Topic.serialize(:content)
- end
-
def test_quote
author_name = "\\ \001 ' \n \\n \""
topic = Topic.create('author_name' => author_name)
@@ -1556,57 +1438,57 @@ class BasicsTest < ActiveRecord::TestCase
def test_no_limit_offset
assert_nothing_raised do
- Developer.scoped(:offset => 2).all
+ Developer.all.merge!(:offset => 2).to_a
end
end
def test_find_last
last = Developer.last
- assert_equal last, Developer.scoped(:order => 'id desc').first
+ assert_equal last, Developer.all.merge!(:order => 'id desc').first
end
def test_last
- assert_equal Developer.scoped(:order => 'id desc').first, Developer.last
+ assert_equal Developer.all.merge!(:order => 'id desc').first, Developer.last
end
def test_all
developers = Developer.all
- assert_kind_of Array, developers
+ assert_kind_of ActiveRecord::Relation, developers
assert_equal Developer.all, developers
end
def test_all_with_conditions
- assert_equal Developer.scoped(:order => 'id desc').all, Developer.order('id desc').all
+ assert_equal Developer.all.merge!(:order => 'id desc').to_a, Developer.order('id desc').to_a
end
def test_find_ordered_last
- last = Developer.scoped(:order => 'developers.salary ASC').last
- assert_equal last, Developer.scoped(:order => 'developers.salary ASC').all.last
+ last = Developer.all.merge!(:order => 'developers.salary ASC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.salary ASC').to_a.last
end
def test_find_reverse_ordered_last
- last = Developer.scoped(:order => 'developers.salary DESC').last
- assert_equal last, Developer.scoped(:order => 'developers.salary DESC').all.last
+ last = Developer.all.merge!(:order => 'developers.salary DESC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.salary DESC').to_a.last
end
def test_find_multiple_ordered_last
- last = Developer.scoped(:order => 'developers.name, developers.salary DESC').last
- assert_equal last, Developer.scoped(:order => 'developers.name, developers.salary DESC').all.last
+ last = Developer.all.merge!(:order => 'developers.name, developers.salary DESC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.name, developers.salary DESC').to_a.last
end
def test_find_keeps_multiple_order_values
- combined = Developer.scoped(:order => 'developers.name, developers.salary').all
- assert_equal combined, Developer.scoped(:order => ['developers.name', 'developers.salary']).all
+ combined = Developer.all.merge!(:order => 'developers.name, developers.salary').to_a
+ assert_equal combined, Developer.all.merge!(:order => ['developers.name', 'developers.salary']).to_a
end
def test_find_keeps_multiple_group_values
- combined = Developer.scoped(:group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at').all
- assert_equal combined, Developer.scoped(:group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at']).all
+ combined = Developer.all.merge!(:group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at').to_a
+ assert_equal combined, Developer.all.merge!(:group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at']).to_a
end
def test_find_symbol_ordered_last
- last = Developer.scoped(:order => :salary).last
- assert_equal last, Developer.scoped(:order => :salary).all.last
+ last = Developer.all.merge!(:order => :salary).last
+ assert_equal last, Developer.all.merge!(:order => :salary).to_a.last
end
def test_abstract_class
@@ -1619,18 +1501,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_nil AbstractCompany.table_name
end
- def test_base_class
- assert_equal LoosePerson, LoosePerson.base_class
- assert_equal LooseDescendant, LooseDescendant.base_class
- assert_equal TightPerson, TightPerson.base_class
- assert_equal TightPerson, TightDescendant.base_class
-
- assert_equal Post, Post.base_class
- assert_equal Post, SpecialPost.base_class
- assert_equal Post, StiPost.base_class
- assert_equal SubStiPost, SubStiPost.base_class
- end
-
def test_descends_from_active_record
assert !ActiveRecord::Base.descends_from_active_record?
@@ -1684,6 +1554,12 @@ class BasicsTest < ActiveRecord::TestCase
assert_kind_of String, Client.first.to_param
end
+ def test_to_param_returns_id_even_if_not_persisted
+ client = Client.new
+ client.id = 1
+ assert_equal "1", client.to_param
+ end
+
def test_inspect_class
assert_equal 'ActiveRecord::Base', ActiveRecord::Base.inspect
assert_equal 'LoosePerson(abstract)', LoosePerson.inspect
@@ -1700,8 +1576,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_inspect_limited_select_instance
- assert_equal %(#<Topic id: 1>), Topic.scoped(:select => 'id', :where => 'id = 1').first.inspect
- assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.scoped(:select => 'id, title', :where => 'id = 1').first.inspect
+ assert_equal %(#<Topic id: 1>), Topic.all.merge!(:select => 'id', :where => 'id = 1').first.inspect
+ assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.all.merge!(:select => 'id, title', :where => 'id = 1').first.inspect
end
def test_inspect_class_without_table
@@ -1814,7 +1690,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_current_scope_is_reset
Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
- UnloadablePost.send(:current_scope=, UnloadablePost.scoped)
+ UnloadablePost.send(:current_scope=, UnloadablePost.all)
UnloadablePost.unloadable
assert_not_nil Thread.current[:UnloadablePost_current_scope]
@@ -1859,7 +1735,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_attribute_names
- assert_equal ["id", "type", "ruby_type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id", "description"],
+ assert_equal ["id", "type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id", "description"],
Company.attribute_names
end
@@ -1890,13 +1766,13 @@ class BasicsTest < ActiveRecord::TestCase
def test_cache_key_format_for_existing_record_with_nil_updated_at
dev = Developer.first
- dev.update_column(:updated_at, nil)
+ dev.update_columns(updated_at: nil)
assert_match(/\/#{dev.id}$/, dev.cache_key)
end
def test_uniq_delegates_to_scoped
scope = stub
- Bird.stubs(:scoped).returns(mock(:uniq => scope))
+ Bird.stubs(:all).returns(mock(:uniq => scope))
assert_equal scope, Bird.uniq
end
@@ -1963,7 +1839,7 @@ class BasicsTest < ActiveRecord::TestCase
scope.expects(meth).with(:foo, :bar).returns(record)
klass = Class.new(ActiveRecord::Base)
- klass.stubs(:scoped => scope)
+ klass.stubs(:all => scope)
assert_equal record, klass.public_send(meth, :foo, :bar)
end
@@ -1971,6 +1847,6 @@ class BasicsTest < ActiveRecord::TestCase
test "scoped can take a values hash" do
klass = Class.new(ActiveRecord::Base)
- assert_equal ['foo'], klass.scoped(select: 'foo').select_values
+ assert_equal ['foo'], klass.all.merge!(select: 'foo').select_values
end
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index e1c1e449ef..40e712072f 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -40,8 +40,8 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
- assert_equal 0, NumericData.scoped.send(:type_cast_calculated_value, 0, nil, 'avg')
- assert_equal 53.0, NumericData.scoped.send(:type_cast_calculated_value, 53, nil, 'avg')
+ assert_equal 0, NumericData.all.send(:type_cast_calculated_value, 0, nil, 'avg')
+ assert_equal 53.0, NumericData.all.send(:type_cast_calculated_value, 53, nil, 'avg')
end
def test_should_get_maximum_of_field
@@ -91,24 +91,24 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_order_by_grouped_field
- c = Account.scoped(:group => :firm_id, :order => "firm_id").sum(:credit_limit)
+ c = Account.all.merge!(:group => :firm_id, :order => "firm_id").sum(:credit_limit)
assert_equal [1, 2, 6, 9], c.keys.compact
end
def test_should_order_by_calculation
- c = Account.scoped(:group => :firm_id, :order => "sum_credit_limit desc, firm_id").sum(:credit_limit)
+ c = Account.all.merge!(:group => :firm_id, :order => "sum_credit_limit desc, firm_id").sum(:credit_limit)
assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 9, 1], c.keys.compact
end
def test_should_limit_calculation
- c = Account.scoped(:where => "firm_id IS NOT NULL",
+ c = Account.all.merge!(:where => "firm_id IS NOT NULL",
:group => :firm_id, :order => "firm_id", :limit => 2).sum(:credit_limit)
assert_equal [1, 2], c.keys.compact
end
def test_should_limit_calculation_with_offset
- c = Account.scoped(:where => "firm_id IS NOT NULL", :group => :firm_id,
+ c = Account.all.merge!(:where => "firm_id IS NOT NULL", :group => :firm_id,
:order => "firm_id", :limit => 2, :offset => 1).sum(:credit_limit)
assert_equal [2, 6], c.keys.compact
end
@@ -159,7 +159,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_having_condition
- c = Account.scoped(:group => :firm_id,
+ c = Account.all.merge!(:group => :firm_id,
:having => 'sum(credit_limit) > 50').sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
@@ -195,7 +195,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_with_conditions
- c = Account.scoped(:where => 'firm_id > 1',
+ c = Account.all.merge!(:where => 'firm_id > 1',
:group => :firm_id).sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
@@ -203,7 +203,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_with_conditions_and_having
- c = Account.scoped(:where => 'firm_id > 1',
+ c = Account.all.merge!(:where => 'firm_id > 1',
:group => :firm_id,
:having => 'sum(credit_limit) > 60').sum(:credit_limit)
assert_nil c[1]
@@ -326,19 +326,19 @@ class CalculationsTest < ActiveRecord::TestCase
def test_should_count_scoped_select
Account.update_all("credit_limit = NULL")
- assert_equal 0, Account.scoped(:select => "credit_limit").count
+ assert_equal 0, Account.all.merge!(:select => "credit_limit").count
end
def test_should_count_scoped_select_with_options
Account.update_all("credit_limit = NULL")
- Account.last.update_column('credit_limit', 49)
- Account.first.update_column('credit_limit', 51)
+ Account.last.update_columns('credit_limit' => 49)
+ Account.first.update_columns('credit_limit' => 51)
- assert_equal 1, Account.scoped(:select => "credit_limit").where('credit_limit >= 50').count
+ assert_equal 1, Account.all.merge!(:select => "credit_limit").where('credit_limit >= 50').count
end
def test_should_count_manual_select_with_include
- assert_equal 6, Account.scoped(:select => "DISTINCT accounts.id", :includes => :firm).count
+ assert_equal 6, Account.all.merge!(:select => "DISTINCT accounts.id", :includes => :firm).count
end
def test_count_with_column_parameter
@@ -355,7 +355,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_count_field_in_joined_table_with_group_by
- c = Account.scoped(:group => 'accounts.firm_id', :joins => :firm).count('companies.id')
+ c = Account.all.merge!(:group => 'accounts.firm_id', :joins => :firm).count('companies.id')
[1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
end
@@ -433,7 +433,7 @@ class CalculationsTest < ActiveRecord::TestCase
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
# TODO: Investigate why PG isn't being typecast
- if current_adapter?(:PostgreSQLAdapter)
+ if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:MysqlAdapter)
assert_equal "7", Company.includes(:contracts).maximum(:developer_id)
else
assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
@@ -444,7 +444,7 @@ class CalculationsTest < ActiveRecord::TestCase
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
# TODO: Investigate why PG isn't being typecast
- if current_adapter?(:PostgreSQLAdapter)
+ if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:MysqlAdapter)
assert_equal "7", Company.includes(:contracts).minimum(:developer_id)
else
assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
index 17cb447105..e1579d037f 100644
--- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb
+++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
@@ -4,16 +4,11 @@ module ActiveRecord
module ConnectionAdapters
class ConnectionHandlerTest < ActiveRecord::TestCase
def setup
+ @klass = Class.new { include Model::Tag }
+ @subklass = Class.new(@klass) { include Model::Tag }
+
@handler = ConnectionHandler.new
- @handler.establish_connection 'america', Base.connection_pool.spec
- @klass = Class.new do
- include Model::Tag
- def self.name; 'america'; end
- end
- @subklass = Class.new(@klass) do
- include Model::Tag
- def self.name; 'north america'; end
- end
+ @handler.establish_connection @klass, Base.connection_pool.spec
end
def test_retrieve_connection
@@ -42,6 +37,8 @@ module ActiveRecord
def test_retrieve_connection_pool_uses_superclass_pool_after_subclass_establish_and_remove
@handler.establish_connection 'north america', Base.connection_pool.spec
+ assert_same @handler.retrieve_connection_pool(@klass),
+ @handler.retrieve_connection_pool(@subklass)
@handler.remove_connection @subklass
assert_same @handler.retrieve_connection_pool(@klass),
diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb
index cd3d19e783..ee443741ca 100644
--- a/activerecord/test/cases/counter_cache_test.rb
+++ b/activerecord/test/cases/counter_cache_test.rb
@@ -8,9 +8,11 @@ require 'models/category'
require 'models/categorization'
require 'models/dog'
require 'models/dog_lover'
+require 'models/person'
+require 'models/friendship'
class CounterCacheTest < ActiveRecord::TestCase
- fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers
+ fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships
class ::SpecialTopic < ::Topic
has_many :special_replies, :foreign_key => 'parent_id'
@@ -109,4 +111,11 @@ class CounterCacheTest < ActiveRecord::TestCase
Topic.update_counters([t1.id, t2.id], :replies_count => 2)
end
end
+
+ test "reset the right counter if two have the same foreign key" do
+ michael = people(:michael)
+ assert_nothing_raised(ActiveRecord::StatementInvalid) do
+ Person.reset_counters(michael.id, :followers)
+ end
+ end
end
diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb
index 42ef51ef3e..e8290297e3 100644
--- a/activerecord/test/cases/custom_locking_test.rb
+++ b/activerecord/test/cases/custom_locking_test.rb
@@ -9,7 +9,7 @@ module ActiveRecord
if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
assert_match 'SHARE MODE', Person.lock('LOCK IN SHARE MODE').to_sql
assert_sql(/LOCK IN SHARE MODE/) do
- Person.scoped(:lock => 'LOCK IN SHARE MODE').find(1)
+ Person.all.merge!(:lock => 'LOCK IN SHARE MODE').find(1)
end
end
end
diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb
index b3a281d960..deaf5252db 100644
--- a/activerecord/test/cases/defaults_test.rb
+++ b/activerecord/test/cases/defaults_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'models/default'
require 'models/entrant'
@@ -95,7 +94,7 @@ if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
assert_equal 0, klass.columns_hash['zero'].default
assert !klass.columns_hash['zero'].null
# 0 in MySQL 4, nil in 5.
- assert klass.columns_hash['omit'].default.in?([0, nil])
+ assert [0, nil].include?(klass.columns_hash['omit'].default)
assert !klass.columns_hash['omit'].null
assert_raise(ActiveRecord::StatementInvalid) { klass.create! }
diff --git a/activerecord/test/cases/deprecated_dynamic_methods_test.rb b/activerecord/test/cases/deprecated_dynamic_methods_test.rb
index 09ca61aa1b..392f5f4cd5 100644
--- a/activerecord/test/cases/deprecated_dynamic_methods_test.rb
+++ b/activerecord/test/cases/deprecated_dynamic_methods_test.rb
@@ -1,4 +1,4 @@
-# This file should be deleted when active_record_deprecated_finders is removed as
+# This file should be deleted when activerecord-deprecated_finders is removed as
# a dependency.
#
# It is kept for now as there is some fairly nuanced behaviour in the dynamic
@@ -45,6 +45,32 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
assert_equal [], Topic.find_all_by_title("The First Topic!!")
end
+ def test_find_all_by_one_attribute_that_is_an_aggregate
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customers = Customer.find_all_by_balance(balance)
+ assert_equal 1, found_customers.size
+ assert_equal customers(:david), found_customers.first
+ end
+
+ def test_find_all_by_two_attributes_that_are_both_aggregates
+ balance = customers(:david).balance
+ address = customers(:david).address
+ assert_kind_of Money, balance
+ assert_kind_of Address, address
+ found_customers = Customer.find_all_by_balance_and_address(balance, address)
+ assert_equal 1, found_customers.size
+ assert_equal customers(:david), found_customers.first
+ end
+
+ def test_find_all_by_two_attributes_with_one_being_an_aggregate
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customers = Customer.find_all_by_balance_and_name(balance, customers(:david).name)
+ assert_equal 1, found_customers.size
+ assert_equal customers(:david), found_customers.first
+ end
+
def test_find_all_by_one_attribute_with_options
topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC")
assert_equal topics(:first), topics.last
@@ -111,6 +137,14 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
assert_equal 17, sig38.firm_id
end
+ def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
+ number_of_customers = Customer.count
+ created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth")
+ assert_equal number_of_customers + 1, Customer.count
+ assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth")
+ assert created_customer.persisted?
+ end
+
def test_find_or_create_from_one_attribute_and_hash
number_of_companies = Company.count
sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
@@ -133,12 +167,38 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
assert_equal 23, sig38.client_of
end
+ def test_find_or_create_from_one_aggregate_attribute
+ number_of_customers = Customer.count
+ created_customer = Customer.find_or_create_by_balance(Money.new(123))
+ assert_equal number_of_customers + 1, Customer.count
+ assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123))
+ assert created_customer.persisted?
+ end
+
+ def test_find_or_create_from_one_aggregate_attribute_and_hash
+ number_of_customers = Customer.count
+ balance = Money.new(123)
+ name = "Elizabeth"
+ created_customer = Customer.find_or_create_by_balance({:balance => balance, :name => name})
+ assert_equal number_of_customers + 1, Customer.count
+ assert_equal created_customer, Customer.find_or_create_by_balance({:balance => balance, :name => name})
+ assert created_customer.persisted?
+ assert_equal balance, created_customer.balance
+ assert_equal name, created_customer.name
+ end
+
def test_find_or_initialize_from_one_attribute
sig38 = Company.find_or_initialize_by_name("38signals")
assert_equal "38signals", sig38.name
assert !sig38.persisted?
end
+ def test_find_or_initialize_from_one_aggregate_attribute
+ new_customer = Customer.find_or_initialize_by_balance(Money.new(123))
+ assert_equal 123, new_customer.balance.amount
+ assert !new_customer.persisted?
+ end
+
def test_find_or_initialize_from_one_attribute_should_not_set_attribute_even_when_protected
c = Company.find_or_initialize_by_name({:name => "Fortune 1000", :rating => 1000})
assert_equal "Fortune 1000", c.name
@@ -225,6 +285,13 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
assert_raise(ArgumentError) { Topic.find_or_initialize_by_title_and_author_name("Another topic") }
end
+ def test_find_or_initialize_from_one_aggregate_attribute_and_one_not
+ new_customer = Customer.find_or_initialize_by_balance_and_name(Money.new(123), "Elizabeth")
+ assert_equal 123, new_customer.balance.amount
+ assert_equal "Elizabeth", new_customer.name
+ assert !new_customer.persisted?
+ end
+
def test_find_or_initialize_from_one_attribute_and_hash
sig38 = Company.find_or_initialize_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
assert_equal "38signals", sig38.name
@@ -233,6 +300,15 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
assert !sig38.persisted?
end
+ def test_find_or_initialize_from_one_aggregate_attribute_and_hash
+ balance = Money.new(123)
+ name = "Elizabeth"
+ new_customer = Customer.find_or_initialize_by_balance({:balance => balance, :name => name})
+ assert_equal balance, new_customer.balance
+ assert_equal name, new_customer.name
+ assert !new_customer.persisted?
+ end
+
def test_find_last_by_one_attribute
assert_equal Topic.last, Topic.find_last_by_title(Topic.last.title)
assert_nil Topic.find_last_by_title("A title with no matches")
@@ -260,21 +336,21 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
def test_find_last_with_limit_gives_same_result_when_loaded_and_unloaded
scope = Topic.limit(2)
unloaded_last = scope.last
- loaded_last = scope.all.last
+ loaded_last = scope.to_a.last
assert_equal loaded_last, unloaded_last
end
def test_find_last_with_limit_and_offset_gives_same_result_when_loaded_and_unloaded
scope = Topic.offset(2).limit(2)
unloaded_last = scope.last
- loaded_last = scope.all.last
+ loaded_last = scope.to_a.last
assert_equal loaded_last, unloaded_last
end
def test_find_last_with_offset_gives_same_result_when_loaded_and_unloaded
scope = Topic.offset(3)
unloaded_last = scope.last
- loaded_last = scope.all.last
+ loaded_last = scope.to_a.last
assert_equal loaded_last, unloaded_last
end
@@ -292,17 +368,17 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_should_respect_association_order
- assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.scoped(:where => "type = 'Client'").all
+ assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.where("type = 'Client'").to_a
assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.find_all_by_type('Client')
end
def test_dynamic_find_all_should_respect_association_limit
- assert_equal 1, companies(:first_firm).limited_clients.scoped(:where => "type = 'Client'").all.length
+ assert_equal 1, companies(:first_firm).limited_clients.where("type = 'Client'").to_a.length
assert_equal 1, companies(:first_firm).limited_clients.find_all_by_type('Client').length
end
def test_dynamic_find_all_limit_should_override_association_limit
- assert_equal 2, companies(:first_firm).limited_clients.scoped(:where => "type = 'Client'", :limit => 9_000).all.length
+ assert_equal 2, companies(:first_firm).limited_clients.where("type = 'Client'").limit(9_000).to_a.length
assert_equal 2, companies(:first_firm).limited_clients.find_all_by_type('Client', :limit => 9_000).length
end
@@ -320,22 +396,22 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_should_respect_association_order_for_through
- assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.scoped(:where => "comments.type = 'SpecialComment'").all
+ assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.where("comments.type = 'SpecialComment'").to_a
assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.find_all_by_type('SpecialComment')
end
def test_dynamic_find_all_should_respect_association_limit_for_through
- assert_equal 1, authors(:david).limited_comments.scoped(:where => "comments.type = 'SpecialComment'").all.length
+ assert_equal 1, authors(:david).limited_comments.where("comments.type = 'SpecialComment'").to_a.length
assert_equal 1, authors(:david).limited_comments.find_all_by_type('SpecialComment').length
end
def test_dynamic_find_all_order_should_override_association_limit_for_through
- assert_equal 4, authors(:david).limited_comments.scoped(:where => "comments.type = 'SpecialComment'", :limit => 9_000).all.length
+ assert_equal 4, authors(:david).limited_comments.where("comments.type = 'SpecialComment'").limit(9_000).to_a.length
assert_equal 4, authors(:david).limited_comments.find_all_by_type('SpecialComment', :limit => 9_000).length
end
def test_find_all_include_over_the_same_table_for_through
- assert_equal 2, people(:michael).posts.scoped(:includes => :people).all.length
+ assert_equal 2, people(:michael).posts.includes(:people).to_a.length
end
def test_find_or_create_by_resets_cached_counters
@@ -411,7 +487,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_by_attributes
- authors = Author.scoped
+ authors = Author.all
davids = authors.find_all_by_name('David')
assert_kind_of Array, davids
@@ -419,7 +495,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_or_initialize_by_attributes
- authors = Author.scoped
+ authors = Author.all
lifo = authors.find_or_initialize_by_name('Lifo')
assert_equal "Lifo", lifo.name
@@ -429,7 +505,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_or_create_by_attributes
- authors = Author.scoped
+ authors = Author.all
lifo = authors.find_or_create_by_name('Lifo')
assert_equal "Lifo", lifo.name
@@ -439,7 +515,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_or_create_by_attributes_bang
- authors = Author.scoped
+ authors = Author.all
assert_raises(ActiveRecord::RecordInvalid) { authors.find_or_create_by_name!('') }
@@ -504,7 +580,7 @@ class DynamicScopeTest < ActiveRecord::TestCase
def test_dynamic_scope
assert_equal @test_klass.scoped_by_author_id(1).find(1), @test_klass.find(1)
- assert_equal @test_klass.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, @test_klass.scoped(:where => { :author_id => 1, :title => "Welcome to the weblog"}).first
+ assert_equal @test_klass.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, @test_klass.all.merge!(:where => { :author_id => 1, :title => "Welcome to the weblog"}).first
end
def test_dynamic_scope_should_create_methods_after_hitting_method_missing
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index 97ffc068af..9a2a5a4e3c 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -201,7 +201,7 @@ class DirtyTest < ActiveRecord::TestCase
end
end
- def test_nullable_integer_zero_to_string_zero_not_marked_as_changed
+ def test_integer_zero_to_string_zero_not_marked_as_changed
pirate = Pirate.new
pirate.parrot_id = 0
pirate.catchphrase = 'arrr'
@@ -213,6 +213,19 @@ class DirtyTest < ActiveRecord::TestCase
assert !pirate.changed?
end
+ def test_integer_zero_to_integer_zero_not_marked_as_changed
+ pirate = Pirate.new
+ pirate.parrot_id = 0
+ pirate.catchphrase = 'arrr'
+ assert pirate.save!
+
+ assert !pirate.changed?
+
+ pirate.parrot_id = 0
+ assert !pirate.changed?
+ end
+
+
def test_zero_to_blank_marked_as_changed
pirate = Pirate.new
pirate.catchphrase = "Yarrrr, me hearties"
@@ -424,7 +437,7 @@ class DirtyTest < ActiveRecord::TestCase
with_partial_updates(Topic) do
Topic.create!(:author_name => 'Bill', :content => {:a => "a"})
topic = Topic.select('id, author_name').first
- topic.update_column :author_name, 'John'
+ topic.update_columns author_name: 'John'
topic = Topic.first
assert_not_nil topic.content
end
@@ -496,6 +509,16 @@ class DirtyTest < ActiveRecord::TestCase
assert_not_nil pirate.previous_changes['updated_on'][1]
assert !pirate.previous_changes.key?('parrot_id')
assert !pirate.previous_changes.key?('created_on')
+
+ pirate = Pirate.find_by_catchphrase("Ahoy!")
+ pirate.update_attribute(:catchphrase, "Ninjas suck!")
+
+ assert_equal 2, pirate.previous_changes.size
+ assert_equal ["Ahoy!", "Ninjas suck!"], pirate.previous_changes['catchphrase']
+ assert_not_nil pirate.previous_changes['updated_on'][0]
+ assert_not_nil pirate.previous_changes['updated_on'][1]
+ assert !pirate.previous_changes.key?('parrot_id')
+ assert !pirate.previous_changes.key?('created_on')
end
if ActiveRecord::Base.connection.supports_migrations?
@@ -512,6 +535,21 @@ class DirtyTest < ActiveRecord::TestCase
end
end
+ def test_setting_time_attributes_with_time_zone_field_to_same_time_should_not_be_marked_as_a_change
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ created_on = Time.now
+
+ pirate = target.create(:created_on => created_on)
+ pirate.reload # Here mysql truncate the usec value to 0
+
+ pirate.created_on = created_on
+ assert !pirate.created_on_changed?
+ end
+ end
+
private
def with_partial_updates(klass, on = true)
old = klass.partial_updates?
diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb
index cb7781f8e7..6dce8ccdd1 100644
--- a/activerecord/test/cases/explain_test.rb
+++ b/activerecord/test/cases/explain_test.rb
@@ -20,7 +20,7 @@ if ActiveRecord::Base.connection.supports_explain?
end
with_threshold(0) do
- Car.where(:name => 'honda').all
+ Car.where(:name => 'honda').to_a
end
end
@@ -45,7 +45,7 @@ if ActiveRecord::Base.connection.supports_explain?
queries = Thread.current[:available_queries_for_explain] = []
with_threshold(0) do
- Car.where(:name => 'honda').all
+ Car.where(:name => 'honda').to_a
end
sql, binds = queries[0]
@@ -58,7 +58,7 @@ if ActiveRecord::Base.connection.supports_explain?
def test_collecting_queries_for_explain
result, queries = ActiveRecord::Base.collecting_queries_for_explain do
- Car.where(:name => 'honda').all
+ Car.where(:name => 'honda').to_a
end
sql, binds = queries[0]
@@ -68,6 +68,16 @@ if ActiveRecord::Base.connection.supports_explain?
assert_equal [cars(:honda)], result
end
+ def test_logging_query_plan_when_counting_by_sql
+ base.logger.expects(:warn).with do |message|
+ message.starts_with?('EXPLAIN for:')
+ end
+
+ with_threshold(0) do
+ Car.count_by_sql "SELECT COUNT(*) FROM cars WHERE name = 'honda'"
+ end
+ end
+
def test_exec_explain_with_no_binds
sqls = %w(foo bar)
binds = [[], []]
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 576a455f09..20c8e8894d 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -83,6 +83,21 @@ class FinderTest < ActiveRecord::TestCase
assert !Topic.exists?
end
+ def test_exists_with_aggregate_having_three_mappings
+ existing_address = customers(:david).address
+ assert Customer.exists?(:address => existing_address)
+ end
+
+ def test_exists_with_aggregate_having_three_mappings_with_one_difference
+ existing_address = customers(:david).address
+ assert !Customer.exists?(:address =>
+ Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
+ assert !Customer.exists?(:address =>
+ Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
+ assert !Customer.exists?(:address =>
+ Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
+ end
+
def test_exists_does_not_instantiate_records
Developer.expects(:instantiate).never
Developer.exists?
@@ -99,14 +114,14 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_by_ids_with_limit_and_offset
- assert_equal 2, Entrant.scoped(:limit => 2).find([1,3,2]).size
- assert_equal 1, Entrant.scoped(:limit => 3, :offset => 2).find([1,3,2]).size
+ assert_equal 2, Entrant.all.merge!(:limit => 2).find([1,3,2]).size
+ assert_equal 1, Entrant.all.merge!(:limit => 3, :offset => 2).find([1,3,2]).size
# Also test an edge case: If you have 11 results, and you set a
# limit of 3 and offset of 9, then you should find that there
# will be only 2 results, regardless of the limit.
devs = Developer.all
- last_devs = Developer.scoped(:limit => 3, :offset => 9).find devs.map(&:id)
+ last_devs = Developer.all.merge!(:limit => 3, :offset => 9).find devs.map(&:id)
assert_equal 2, last_devs.size
end
@@ -123,7 +138,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_group_and_sanitized_having_method
- developers = Developer.group(:salary).having("sum(salary) > ?", 10000).select('salary').all
+ developers = Developer.group(:salary).having("sum(salary) > ?", 10000).select('salary').to_a
assert_equal 3, developers.size
assert_equal 3, developers.map(&:salary).uniq.size
assert developers.all? { |developer| developer.salary > 10000 }
@@ -259,7 +274,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_only_some_columns
- topic = Topic.scoped(:select => "author_name").find(1)
+ topic = Topic.all.merge!(:select => "author_name").find(1)
assert_raise(ActiveModel::MissingAttributeError) {topic.title}
assert_nil topic.read_attribute("title")
assert_equal "David", topic.author_name
@@ -270,23 +285,23 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_on_array_conditions
- assert Topic.scoped(:where => ["approved = ?", false]).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => ["approved = ?", true]).find(1) }
+ assert Topic.all.merge!(:where => ["approved = ?", false]).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => ["approved = ?", true]).find(1) }
end
def test_find_on_hash_conditions
- assert Topic.scoped(:where => { :approved => false }).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :approved => true }).find(1) }
+ assert Topic.all.merge!(:where => { :approved => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :approved => true }).find(1) }
end
def test_find_on_hash_conditions_with_explicit_table_name
- assert Topic.scoped(:where => { 'topics.approved' => false }).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { 'topics.approved' => true }).find(1) }
+ assert Topic.all.merge!(:where => { 'topics.approved' => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { 'topics.approved' => true }).find(1) }
end
def test_find_on_hash_conditions_with_hashed_table_name
- assert Topic.scoped(:where => {:topics => { :approved => false }}).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => {:topics => { :approved => true }}).find(1) }
+ assert Topic.all.merge!(:where => {:topics => { :approved => false }}).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => {:topics => { :approved => true }}).find(1) }
end
def test_find_with_hash_conditions_on_joined_table
@@ -296,90 +311,140 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_hash_conditions_on_joined_table_and_with_range
- firms = DependentFirm.scoped :joins => :account, :where => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}
+ firms = DependentFirm.all.merge!(:joins => :account, :where => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }})
assert_equal 1, firms.size
assert_equal companies(:rails_core), firms.first
end
+ def test_find_on_hash_conditions_with_explicit_table_name_and_aggregate
+ david = customers(:david)
+ assert Customer.where('customers.name' => david.name, :address => david.address).find(david.id)
+ assert_raise(ActiveRecord::RecordNotFound) {
+ Customer.where('customers.name' => david.name + "1", :address => david.address).find(david.id)
+ }
+ end
+
def test_find_on_association_proxy_conditions
assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10, 12], Comment.where(post_id: authors(:david).posts).map(&:id).sort
end
def test_find_on_hash_conditions_with_range
- assert_equal [1,2], Topic.scoped(:where => { :id => 1..2 }).all.map(&:id).sort
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :id => 2..3 }).find(1) }
+ assert_equal [1,2], Topic.all.merge!(:where => { :id => 1..2 }).to_a.map(&:id).sort
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :id => 2..3 }).find(1) }
end
def test_find_on_hash_conditions_with_end_exclusive_range
- assert_equal [1,2,3], Topic.scoped(:where => { :id => 1..3 }).all.map(&:id).sort
- assert_equal [1,2], Topic.scoped(:where => { :id => 1...3 }).all.map(&:id).sort
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :id => 2...3 }).find(3) }
+ assert_equal [1,2,3], Topic.all.merge!(:where => { :id => 1..3 }).to_a.map(&:id).sort
+ assert_equal [1,2], Topic.all.merge!(:where => { :id => 1...3 }).to_a.map(&:id).sort
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :id => 2...3 }).find(3) }
end
def test_find_on_hash_conditions_with_multiple_ranges
- assert_equal [1,2,3], Comment.scoped(:where => { :id => 1..3, :post_id => 1..2 }).all.map(&:id).sort
- assert_equal [1], Comment.scoped(:where => { :id => 1..1, :post_id => 1..10 }).all.map(&:id).sort
+ assert_equal [1,2,3], Comment.all.merge!(:where => { :id => 1..3, :post_id => 1..2 }).to_a.map(&:id).sort
+ assert_equal [1], Comment.all.merge!(:where => { :id => 1..1, :post_id => 1..10 }).to_a.map(&:id).sort
end
def test_find_on_hash_conditions_with_array_of_integers_and_ranges
- assert_equal [1,2,3,5,6,7,8,9], Comment.scoped(:where => {:id => [1..2, 3, 5, 6..8, 9]}).all.map(&:id).sort
+ assert_equal [1,2,3,5,6,7,8,9], Comment.all.merge!(:where => {:id => [1..2, 3, 5, 6..8, 9]}).to_a.map(&:id).sort
end
def test_find_on_multiple_hash_conditions
- assert Topic.scoped(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }).find(1) }
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
+ assert Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }).find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
end
def test_condition_interpolation
assert_kind_of Firm, Company.where("name = '%s'", "37signals").first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!"]).first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = %d", 1]).first.written_on
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = %d", 1]).first.written_on
end
def test_condition_array_interpolation
- assert_kind_of Firm, Company.scoped(:where => ["name = '%s'", "37signals"]).first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!"]).first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = %d", 1]).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = '%s'", "37signals"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = %d", 1]).first.written_on
end
def test_condition_hash_interpolation
- assert_kind_of Firm, Company.scoped(:where => { :name => "37signals"}).first
- assert_nil Company.scoped(:where => { :name => "37signals!"}).first
- assert_kind_of Time, Topic.scoped(:where => {:id => 1}).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => { :name => "37signals"}).first
+ assert_nil Company.all.merge!(:where => { :name => "37signals!"}).first
+ assert_kind_of Time, Topic.all.merge!(:where => {:id => 1}).first.written_on
end
def test_hash_condition_find_malformed
assert_raise(ActiveRecord::StatementInvalid) {
- Company.scoped(:where => { :id => 2, :dhh => true }).first
+ Company.all.merge!(:where => { :id => 2, :dhh => true }).first
}
end
def test_hash_condition_find_with_escaped_characters
Company.create("name" => "Ain't noth'n like' \#stuff")
- assert Company.scoped(:where => { :name => "Ain't noth'n like' \#stuff" }).first
+ assert Company.all.merge!(:where => { :name => "Ain't noth'n like' \#stuff" }).first
end
def test_hash_condition_find_with_array
- p1, p2 = Post.scoped(:limit => 2, :order => 'id asc').all
- assert_equal [p1, p2], Post.scoped(:where => { :id => [p1, p2] }, :order => 'id asc').all
- assert_equal [p1, p2], Post.scoped(:where => { :id => [p1, p2.id] }, :order => 'id asc').all
+ p1, p2 = Post.all.merge!(:limit => 2, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => { :id => [p1, p2] }, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => { :id => [p1, p2.id] }, :order => 'id asc').to_a
end
def test_hash_condition_find_with_nil
- topic = Topic.scoped(:where => { :last_read => nil } ).first
+ topic = Topic.all.merge!(:where => { :last_read => nil } ).first
assert_not_nil topic
assert_nil topic.last_read
end
+ def test_hash_condition_find_with_aggregate_having_one_mapping
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customer = Customer.where(:balance => balance).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate
+ gps_location = customers(:david).gps_location
+ assert_kind_of GpsLocation, gps_location
+ found_customer = Customer.where(:gps_location => gps_location).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customer = Customer.where(:balance => balance.amount).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value
+ gps_location = customers(:david).gps_location
+ assert_kind_of GpsLocation, gps_location
+ found_customer = Customer.where(:gps_location => gps_location.gps_location).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_having_three_mappings
+ address = customers(:david).address
+ assert_kind_of Address, address
+ found_customer = Customer.where(:address => address).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not
+ address = customers(:david).address
+ assert_kind_of Address, address
+ found_customer = Customer.where(:address => address, :name => customers(:david).name).first
+ assert_equal customers(:david), found_customer
+ end
+
def test_condition_utc_time_interpolation_with_default_timezone_local
with_env_tz 'America/New_York' do
with_active_record_default_timezone :local do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => ['written_on = ?', topic.written_on.getutc]).first
+ assert_equal topic, Topic.all.merge!(:where => ['written_on = ?', topic.written_on.getutc]).first
end
end
end
@@ -388,7 +453,7 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :local do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => {:written_on => topic.written_on.getutc}).first
+ assert_equal topic, Topic.all.merge!(:where => {:written_on => topic.written_on.getutc}).first
end
end
end
@@ -397,7 +462,7 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :utc do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => ['written_on = ?', topic.written_on.getlocal]).first
+ assert_equal topic, Topic.all.merge!(:where => ['written_on = ?', topic.written_on.getlocal]).first
end
end
end
@@ -406,32 +471,32 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :utc do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => {:written_on => topic.written_on.getlocal}).first
+ assert_equal topic, Topic.all.merge!(:where => {:written_on => topic.written_on.getlocal}).first
end
end
end
def test_bind_variables
- assert_kind_of Firm, Company.scoped(:where => ["name = ?", "37signals"]).first
- assert_nil Company.scoped(:where => ["name = ?", "37signals!"]).first
- assert_nil Company.scoped(:where => ["name = ?", "37signals!' OR 1=1"]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = ?", 1]).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = ?", "37signals"]).first
+ assert_nil Company.all.merge!(:where => ["name = ?", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = ?", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = ?", 1]).first.written_on
assert_raise(ActiveRecord::PreparedStatementInvalid) {
- Company.scoped(:where => ["id=? AND name = ?", 2]).first
+ Company.all.merge!(:where => ["id=? AND name = ?", 2]).first
}
assert_raise(ActiveRecord::PreparedStatementInvalid) {
- Company.scoped(:where => ["id=?", 2, 3, 4]).first
+ Company.all.merge!(:where => ["id=?", 2, 3, 4]).first
}
end
def test_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
- assert Company.scoped(:where => ["name = ?", "37signals' go'es agains"]).first
+ assert Company.all.merge!(:where => ["name = ?", "37signals' go'es agains"]).first
end
def test_named_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
- assert Company.scoped(:where => ["name = :name", {:name => "37signals' go'es agains"}]).first
+ assert Company.all.merge!(:where => ["name = :name", {:name => "37signals' go'es agains"}]).first
end
def test_bind_arity
@@ -449,10 +514,10 @@ class FinderTest < ActiveRecord::TestCase
assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
- assert_kind_of Firm, Company.scoped(:where => ["name = :name", { :name => "37signals" }]).first
- assert_nil Company.scoped(:where => ["name = :name", { :name => "37signals!" }]).first
- assert_nil Company.scoped(:where => ["name = :name", { :name => "37signals!' OR 1=1" }]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = :id", { :id => 1 }]).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = :name", { :name => "37signals" }]).first
+ assert_nil Company.all.merge!(:where => ["name = :name", { :name => "37signals!" }]).first
+ assert_nil Company.all.merge!(:where => ["name = :name", { :name => "37signals!' OR 1=1" }]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = :id", { :id => 1 }]).first.written_on
end
class SimpleEnumerable
@@ -548,6 +613,40 @@ class FinderTest < ActiveRecord::TestCase
assert_equal accounts(:rails_core_account), Account.where('firm_id = ?', 6).find_by_credit_limit(50)
end
+ def test_find_by_one_attribute_that_is_an_aggregate
+ address = customers(:david).address
+ assert_kind_of Address, address
+ found_customer = Customer.find_by_address(address)
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_find_by_one_attribute_that_is_an_aggregate_with_one_attribute_difference
+ address = customers(:david).address
+ assert_kind_of Address, address
+ missing_address = Address.new(address.street, address.city, address.country + "1")
+ assert_nil Customer.find_by_address(missing_address)
+ missing_address = Address.new(address.street, address.city + "1", address.country)
+ assert_nil Customer.find_by_address(missing_address)
+ missing_address = Address.new(address.street + "1", address.city, address.country)
+ assert_nil Customer.find_by_address(missing_address)
+ end
+
+ def test_find_by_two_attributes_that_are_both_aggregates
+ balance = customers(:david).balance
+ address = customers(:david).address
+ assert_kind_of Money, balance
+ assert_kind_of Address, address
+ found_customer = Customer.find_by_balance_and_address(balance, address)
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_find_by_two_attributes_with_one_being_an_aggregate
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customer = Customer.find_by_balance_and_name(balance, customers(:david).name)
+ assert_equal customers(:david), found_customer
+ end
+
def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
# ensure this test can run independently of order
class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.include?(:find_by_credit_limit)
@@ -595,10 +694,10 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_all_with_join
- developers_on_project_one = Developer.scoped(
+ developers_on_project_one = Developer.all.merge!(
:joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
:where => 'project_id=1'
- ).all
+ ).to_a
assert_equal 3, developers_on_project_one.length
developer_names = developers_on_project_one.map { |d| d.name }
assert developer_names.include?('David')
@@ -606,7 +705,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_joins_dont_clobber_id
- first = Firm.scoped(
+ first = Firm.all.merge!(
:joins => 'INNER JOIN companies clients ON clients.firm_id = companies.id',
:where => 'companies.id = 1'
).first
@@ -614,7 +713,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_joins_with_string_array
- person_with_reader_and_post = Post.scoped(
+ person_with_reader_and_post = Post.all.merge!(
:joins => [
"INNER JOIN categorizations ON categorizations.post_id = posts.id",
"INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
@@ -644,9 +743,9 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_by_records
- p1, p2 = Post.scoped(:limit => 2, :order => 'id asc').all
- assert_equal [p1, p2], Post.scoped(:where => ['id in (?)', [p1, p2]], :order => 'id asc')
- assert_equal [p1, p2], Post.scoped(:where => ['id in (?)', [p1, p2.id]], :order => 'id asc')
+ p1, p2 = Post.all.merge!(:limit => 2, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => ['id in (?)', [p1, p2]], :order => 'id asc')
+ assert_equal [p1, p2], Post.all.merge!(:where => ['id in (?)', [p1, p2.id]], :order => 'id asc')
end
def test_select_value
@@ -673,14 +772,14 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct
- assert_equal 2, Post.scoped(:includes => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).all.size
+ assert_equal 2, Post.all.merge!(:includes => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).to_a.size
- assert_equal 3, Post.scoped(:includes => { :author => :author_address, :authors => :author_address},
- :order => 'author_addresses_authors.id DESC ', :limit => 3).all.size
+ assert_equal 3, Post.all.merge!(:includes => { :author => :author_address, :authors => :author_address},
+ :order => 'author_addresses_authors.id DESC ', :limit => 3).to_a.size
end
def test_find_with_nil_inside_set_passed_for_one_attribute
- client_of = Company.scoped(
+ client_of = Company.all.merge!(
:where => {
:client_of => [2, 1, nil],
:name => ['37signals', 'Summit', 'Microsoft'] },
@@ -692,7 +791,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_nil_inside_set_passed_for_attribute
- client_of = Company.scoped(
+ client_of = Company.all.merge!(
:where => { :client_of => [nil] },
:order => 'client_of DESC'
).map { |x| x.client_of }
@@ -701,10 +800,10 @@ class FinderTest < ActiveRecord::TestCase
end
def test_with_limiting_with_custom_select
- posts = Post.references(:authors).scoped(
+ posts = Post.references(:authors).merge(
:includes => :author, :select => ' posts.*, authors.id as "author_id"',
:limit => 3, :order => 'posts.id'
- ).all
+ ).to_a
assert_equal 3, posts.size
assert_equal [0, 1, 1], posts.map(&:author_id).sort
end
@@ -719,7 +818,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_finder_with_offset_string
- assert_nothing_raised(ActiveRecord::StatementInvalid) { Topic.scoped(:offset => "3").all }
+ assert_nothing_raised(ActiveRecord::StatementInvalid) { Topic.all.merge!(:offset => "3").to_a }
end
protected
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index 44d08a8ee4..4c6d4666ed 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -6,8 +6,8 @@ gem 'minitest'
require 'minitest/autorun'
require 'stringio'
-require 'cases/test_case'
require 'active_record'
+require 'cases/test_case'
require 'active_support/dependencies'
require 'active_support/logger'
@@ -19,9 +19,6 @@ require 'support/connection'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
-# Avoid deprecation warning setting dependent_restrict_raises to false. The default is true
-ActiveRecord::Base.dependent_restrict_raises = false
-
# Connect to the database
ARTest.connect
diff --git a/activerecord/test/cases/inclusion_test.rb b/activerecord/test/cases/inclusion_test.rb
index 9b9c09d2d8..8f095e4953 100644
--- a/activerecord/test/cases/inclusion_test.rb
+++ b/activerecord/test/cases/inclusion_test.rb
@@ -84,8 +84,10 @@ class InclusionUnitTest < ActiveRecord::TestCase
end
def test_deprecation_proxy
- assert_equal ActiveRecord::Model.name, ActiveRecord::Model::DeprecationProxy.name
- assert_equal ActiveRecord::Base.superclass, assert_deprecated { ActiveRecord::Model::DeprecationProxy.superclass }
+ proxy = ActiveRecord::Model::DeprecationProxy.new
+
+ assert_equal ActiveRecord::Model.name, proxy.name
+ assert_equal ActiveRecord::Base.superclass, assert_deprecated { proxy.superclass }
sup, sup2 = nil, nil
ActiveSupport.on_load(:__test_active_record_model_deprecation) do
@@ -93,11 +95,29 @@ class InclusionUnitTest < ActiveRecord::TestCase
sup2 = send(:superclass)
end
assert_deprecated do
- ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, ActiveRecord::Model::DeprecationProxy)
+ ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, proxy)
end
assert_equal ActiveRecord::Base.superclass, sup
assert_equal ActiveRecord::Base.superclass, sup2
end
+
+ test "including in deprecation proxy" do
+ model, base = ActiveRecord::Model.dup, ActiveRecord::Base.dup
+ proxy = ActiveRecord::Model::DeprecationProxy.new(model, base)
+
+ mod = Module.new
+ proxy.include mod
+ assert model < mod
+ end
+
+ test "extending in deprecation proxy" do
+ model, base = ActiveRecord::Model.dup, ActiveRecord::Base.dup
+ proxy = ActiveRecord::Model::DeprecationProxy.new(model, base)
+
+ mod = Module.new
+ assert_deprecated { proxy.extend mod }
+ assert base.singleton_class < mod
+ end
end
class InclusionFixturesTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index 06de51f5cd..8fded9159f 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -1,10 +1,14 @@
require "cases/helper"
require 'models/company'
+require 'models/person'
+require 'models/post'
require 'models/project'
require 'models/subscriber'
+require 'models/teapot'
+require 'models/vegetables'
class InheritanceTest < ActiveRecord::TestCase
- fixtures :companies, :projects, :subscribers, :accounts
+ fixtures :companies, :projects, :subscribers, :accounts, :vegetables
def test_class_with_store_full_sti_class_returns_full_name
old = ActiveRecord::Base.store_full_sti_class
@@ -24,7 +28,7 @@ class InheritanceTest < ActiveRecord::TestCase
end
})
company.save!
- company = Company.all.find { |x| x.id == company.id }
+ company = Company.all.to_a.find { |x| x.id == company.id }
assert_equal ' ', company.type
end
@@ -70,6 +74,33 @@ class InheritanceTest < ActiveRecord::TestCase
assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base'
end
+ def test_inheritance_base_class
+ assert_equal Post, Post.base_class
+ assert_equal Post, SpecialPost.base_class
+ assert_equal Post, StiPost.base_class
+ assert_equal SubStiPost, SubStiPost.base_class
+ end
+
+ def test_active_record_model_included_base_class
+ assert_equal Teapot, Teapot.base_class
+ end
+
+ def test_abstract_inheritance_base_class
+ assert_equal LoosePerson, LoosePerson.base_class
+ assert_equal LooseDescendant, LooseDescendant.base_class
+ assert_equal TightPerson, TightPerson.base_class
+ assert_equal TightPerson, TightDescendant.base_class
+ end
+
+ def test_base_class_activerecord_error
+ klass = Class.new {
+ extend ActiveRecord::Configuration
+ include ActiveRecord::Inheritance
+ }
+
+ assert_raise(ActiveRecord::ActiveRecordError) { klass.base_class }
+ end
+
def test_a_bad_type_column
#SQLServer need to turn Identity Insert On before manually inserting into the Identity column
if current_adapter?(:SybaseAdapter)
@@ -92,21 +123,29 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_alt_inheritance_find
- switch_to_alt_inheritance_column
- test_inheritance_find
- switch_to_default_inheritance_column
+ assert_kind_of Cucumber, Vegetable.find(1)
+ assert_kind_of Cucumber, Cucumber.find(1)
+ assert_kind_of Cabbage, Vegetable.find(2)
+ assert_kind_of Cabbage, Cabbage.find(2)
+ end
+
+ def test_alt_becomes_works_with_sti
+ vegetable = Vegetable.find(1)
+ assert_kind_of Vegetable, vegetable
+ cabbage = vegetable.becomes(Cabbage)
+ assert_kind_of Cabbage, cabbage
end
def test_inheritance_find_all
- companies = Company.scoped(:order => 'id').all
+ companies = Company.all.merge!(:order => 'id').to_a
assert_kind_of Firm, companies[0], "37signals should be a firm"
assert_kind_of Client, companies[1], "Summit should be a client"
end
def test_alt_inheritance_find_all
- switch_to_alt_inheritance_column
- test_inheritance_find_all
- switch_to_default_inheritance_column
+ companies = Vegetable.all.merge!(:order => 'id').to_a
+ assert_kind_of Cucumber, companies[0]
+ assert_kind_of Cabbage, companies[1]
end
def test_inheritance_save
@@ -119,9 +158,11 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_alt_inheritance_save
- switch_to_alt_inheritance_column
- test_inheritance_save
- switch_to_default_inheritance_column
+ cabbage = Cabbage.new(:name => 'Savoy')
+ cabbage.save!
+
+ savoy = Vegetable.find(cabbage.id)
+ assert_kind_of Cabbage, savoy
end
def test_inheritance_condition
@@ -131,9 +172,9 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_alt_inheritance_condition
- switch_to_alt_inheritance_column
- test_inheritance_condition
- switch_to_default_inheritance_column
+ assert_equal 4, Vegetable.count
+ assert_equal 1, Cucumber.count
+ assert_equal 3, Cabbage.count
end
def test_finding_incorrect_type_data
@@ -142,22 +183,21 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_alt_finding_incorrect_type_data
- switch_to_alt_inheritance_column
- test_finding_incorrect_type_data
- switch_to_default_inheritance_column
+ assert_raise(ActiveRecord::RecordNotFound) { Cucumber.find(2) }
+ assert_nothing_raised { Cucumber.find(1) }
end
def test_update_all_within_inheritance
Client.update_all "name = 'I am a client'"
- assert_equal "I am a client", Client.all.first.name
+ assert_equal "I am a client", Client.first.name
# Order by added as otherwise Oracle tests were failing because of different order of results
- assert_equal "37signals", Firm.scoped(:order => "id").all.first.name
+ assert_equal "37signals", Firm.all.merge!(:order => "id").to_a.first.name
end
def test_alt_update_all_within_inheritance
- switch_to_alt_inheritance_column
- test_update_all_within_inheritance
- switch_to_default_inheritance_column
+ Cabbage.update_all "name = 'the cabbage'"
+ assert_equal "the cabbage", Cabbage.first.name
+ assert_equal ["my cucumber"], Cucumber.all.map(&:name).uniq
end
def test_destroy_all_within_inheritance
@@ -167,57 +207,60 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_alt_destroy_all_within_inheritance
- switch_to_alt_inheritance_column
- test_destroy_all_within_inheritance
- switch_to_default_inheritance_column
+ Cabbage.destroy_all
+ assert_equal 0, Cabbage.count
+ assert_equal 1, Cucumber.count
end
def test_find_first_within_inheritance
- assert_kind_of Firm, Company.scoped(:where => "name = '37signals'").first
- assert_kind_of Firm, Firm.scoped(:where => "name = '37signals'").first
- assert_nil Client.scoped(:where => "name = '37signals'").first
+ assert_kind_of Firm, Company.all.merge!(:where => "name = '37signals'").first
+ assert_kind_of Firm, Firm.all.merge!(:where => "name = '37signals'").first
+ assert_nil Client.all.merge!(:where => "name = '37signals'").first
end
def test_alt_find_first_within_inheritance
- switch_to_alt_inheritance_column
- test_find_first_within_inheritance
- switch_to_default_inheritance_column
+ assert_kind_of Cabbage, Vegetable.all.merge!(:where => "name = 'his cabbage'").first
+ assert_kind_of Cabbage, Cabbage.all.merge!(:where => "name = 'his cabbage'").first
+ assert_nil Cucumber.all.merge!(:where => "name = 'his cabbage'").first
end
def test_complex_inheritance
very_special_client = VerySpecialClient.create("name" => "veryspecial")
assert_equal very_special_client, VerySpecialClient.where("name = 'veryspecial'").first
- assert_equal very_special_client, SpecialClient.scoped(:where => "name = 'veryspecial'").first
- assert_equal very_special_client, Company.scoped(:where => "name = 'veryspecial'").first
- assert_equal very_special_client, Client.scoped(:where => "name = 'veryspecial'").first
- assert_equal 1, Client.scoped(:where => "name = 'Summit'").all.size
+ assert_equal very_special_client, SpecialClient.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal very_special_client, Company.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal very_special_client, Client.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal 1, Client.all.merge!(:where => "name = 'Summit'").to_a.size
assert_equal very_special_client, Client.find(very_special_client.id)
end
def test_alt_complex_inheritance
- switch_to_alt_inheritance_column
- test_complex_inheritance
- switch_to_default_inheritance_column
+ king_cole = KingCole.create("name" => "uniform heads")
+ assert_equal king_cole, KingCole.where("name = 'uniform heads'").first
+ assert_equal king_cole, GreenCabbage.all.merge!(:where => "name = 'uniform heads'").first
+ assert_equal king_cole, Cabbage.all.merge!(:where => "name = 'uniform heads'").first
+ assert_equal king_cole, Vegetable.all.merge!(:where => "name = 'uniform heads'").first
+ assert_equal 1, Cabbage.all.merge!(:where => "name = 'his cabbage'").to_a.size
+ assert_equal king_cole, Cabbage.find(king_cole.id)
end
def test_eager_load_belongs_to_something_inherited
- account = Account.scoped(:includes => :firm).find(1)
+ account = Account.all.merge!(:includes => :firm).find(1)
assert account.association_cache.key?(:firm), "nil proves eager load failed"
end
+ def test_alt_eager_loading
+ cabbage = RedCabbage.all.merge!(:includes => :seller).find(4)
+ assert cabbage.association_cache.key?(:seller), "nil proves eager load failed"
+ end
+
def test_eager_load_belongs_to_primary_key_quoting
con = Account.connection
assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do
- Account.scoped(:includes => :firm).find(1)
+ Account.all.merge!(:includes => :firm).find(1)
end
end
- def test_alt_eager_loading
- switch_to_alt_inheritance_column
- test_eager_load_belongs_to_something_inherited
- switch_to_default_inheritance_column
- end
-
def test_inherits_custom_primary_key
assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
end
@@ -226,21 +269,6 @@ class InheritanceTest < ActiveRecord::TestCase
assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
end
-
- private
- def switch_to_alt_inheritance_column
- # we don't want misleading test results, so get rid of the values in the type column
- Company.scoped(:order => 'id').all.each do |c|
- c['type'] = nil
- c.save
- end
- [ Company, Firm, Client].each { |klass| klass.reset_column_information }
- Company.inheritance_column = 'ruby_type'
- end
- def switch_to_default_inheritance_column
- [ Company, Firm, Client].each { |klass| klass.reset_column_information }
- Company.inheritance_column = 'type'
- end
end
@@ -260,7 +288,7 @@ class InheritanceComputeTypeTest < ActiveRecord::TestCase
def test_instantiation_doesnt_try_to_require_corresponding_file
ActiveRecord::Base.store_full_sti_class = false
foo = Firm.first.clone
- foo.ruby_type = foo.type = 'FirmOnTheFly'
+ foo.type = 'FirmOnTheFly'
foo.save!
# Should fail without FirmOnTheFly in the type condition.
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index afb0bd6fd9..2392516395 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -3,6 +3,7 @@ require "cases/helper"
require 'models/person'
require 'models/job'
require 'models/reader'
+require 'models/ship'
require 'models/legacy_thing'
require 'models/reference'
require 'models/string_key_object'
@@ -18,8 +19,8 @@ class LockWithCustomColumnWithoutDefault < ActiveRecord::Base
self.locking_column = :custom_lock_version
end
-class ReadonlyFirstNamePerson < Person
- attr_readonly :first_name
+class ReadonlyNameShip < Ship
+ attr_readonly :name
end
class OptimisticLockingTest < ActiveRecord::TestCase
@@ -200,15 +201,15 @@ class OptimisticLockingTest < ActiveRecord::TestCase
end
def test_readonly_attributes
- assert_equal Set.new([ 'first_name' ]), ReadonlyFirstNamePerson.readonly_attributes
+ assert_equal Set.new([ 'name' ]), ReadonlyNameShip.readonly_attributes
- p = ReadonlyFirstNamePerson.create(:first_name => "unchangeable name")
- p.reload
- assert_equal "unchangeable name", p.first_name
+ s = ReadonlyNameShip.create(:name => "unchangeable name")
+ s.reload
+ assert_equal "unchangeable name", s.name
- p.update_attributes(:first_name => "changed name")
- p.reload
- assert_equal "unchangeable name", p.first_name
+ s.update_attributes(:name => "changed name")
+ s.reload
+ assert_equal "unchangeable name", s.name
end
def test_quote_table_name
diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb
index acd2fcdad4..70d00aecf9 100644
--- a/activerecord/test/cases/log_subscriber_test.rb
+++ b/activerecord/test/cases/log_subscriber_test.rb
@@ -54,7 +54,7 @@ class LogSubscriberTest < ActiveRecord::TestCase
end
def test_basic_query_logging
- Developer.all
+ Developer.all.load
wait
assert_equal 1, @logger.logged(:debug).size
assert_match(/Developer Load/, @logger.logged(:debug).last)
@@ -71,8 +71,8 @@ class LogSubscriberTest < ActiveRecord::TestCase
def test_cached_queries
ActiveRecord::Base.cache do
- Developer.all
- Developer.all
+ Developer.all.load
+ Developer.all.load
end
wait
assert_equal 2, @logger.logged(:debug).size
@@ -82,7 +82,7 @@ class LogSubscriberTest < ActiveRecord::TestCase
def test_basic_query_doesnt_log_when_level_is_not_debug
@logger.level = INFO
- Developer.all
+ Developer.all.load
wait
assert_equal 0, @logger.logged(:debug).size
end
@@ -90,8 +90,8 @@ class LogSubscriberTest < ActiveRecord::TestCase
def test_cached_queries_doesnt_log_when_level_is_not_debug
@logger.level = INFO
ActiveRecord::Base.cache do
- Developer.all
- Developer.all
+ Developer.all.load
+ Developer.all.load
end
wait
assert_equal 0, @logger.logged(:debug).size
diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb
index 73a01906b9..a36b2c2506 100644
--- a/activerecord/test/cases/mass_assignment_security_test.rb
+++ b/activerecord/test/cases/mass_assignment_security_test.rb
@@ -313,7 +313,7 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
end
-# This class should be deleted when we removed active_record_deprecated_finders as a
+# This class should be deleted when we remove activerecord-deprecated_finders as a
# dependency.
class MassAssignmentSecurityDeprecatedFindersTest < ActiveRecord::TestCase
include MassAssignmentTestHelpers
diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb
index ce9be66069..ec4c554abb 100644
--- a/activerecord/test/cases/migration/change_schema_test.rb
+++ b/activerecord/test/cases/migration/change_schema_test.rb
@@ -141,8 +141,8 @@ module ActiveRecord
created_at_column = created_columns.detect {|c| c.name == 'created_at' }
updated_at_column = created_columns.detect {|c| c.name == 'updated_at' }
- assert !created_at_column.null
- assert !updated_at_column.null
+ assert created_at_column.null
+ assert updated_at_column.null
end
def test_create_table_with_timestamps_should_create_datetime_columns_with_options
diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb
index 3014bbe273..b88db384a0 100644
--- a/activerecord/test/cases/migration/column_attributes_test.rb
+++ b/activerecord/test/cases/migration/column_attributes_test.rb
@@ -7,6 +7,14 @@ module ActiveRecord
self.use_transactional_fixtures = false
+ def test_add_column_newline_default
+ string = "foo\nbar"
+ add_column 'test_models', 'command', :string, :default => string
+ TestModel.reset_column_information
+
+ assert_equal string, TestModel.new.command
+ end
+
def test_add_remove_single_field_using_string_arguments
refute TestModel.column_methods_hash.key?(:last_name)
@@ -54,13 +62,13 @@ module ActiveRecord
# Do a manual insertion
if current_adapter?(:OracleAdapter)
- connection.execute "insert into test_models (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)"
+ connection.execute "insert into test_models (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)"
elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
- connection.execute "insert into test_models (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)"
+ connection.execute "insert into test_models (wealth) values ('12345678901234567890.0123456789')"
elsif current_adapter?(:PostgreSQLAdapter)
- connection.execute "insert into test_models (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())"
+ connection.execute "insert into test_models (wealth) values (12345678901234567890.0123456789)"
else
- connection.execute "insert into test_models (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)"
+ connection.execute "insert into test_models (wealth) values (12345678901234567890.0123456789)"
end
# SELECT
diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb
index 8b91b3bc92..cd1b0e8b47 100644
--- a/activerecord/test/cases/migration/create_join_table_test.rb
+++ b/activerecord/test/cases/migration/create_join_table_test.rb
@@ -42,22 +42,36 @@ module ActiveRecord
end
def test_create_join_table_with_the_table_name
- connection.create_join_table :artists, :musics, :table_name => :catalog
+ connection.create_join_table :artists, :musics, table_name: :catalog
assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort
end
def test_create_join_table_with_the_table_name_as_string
- connection.create_join_table :artists, :musics, :table_name => 'catalog'
+ connection.create_join_table :artists, :musics, table_name: 'catalog'
assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort
end
def test_create_join_table_with_column_options
- connection.create_join_table :artists, :musics, :column_options => {:null => true}
+ connection.create_join_table :artists, :musics, column_options: {null: true}
assert_equal [true, true], connection.columns(:artists_musics).map(&:null)
end
+
+ def test_create_join_table_without_indexes
+ connection.create_join_table :artists, :musics
+
+ assert connection.indexes(:artists_musics).blank?
+ end
+
+ def test_create_join_table_with_index
+ connection.create_join_table :artists, :musics do |t|
+ t.index [:artist_id, :music_id]
+ end
+
+ assert_equal [%w(artist_id music_id)], connection.indexes(:artists_musics).map(&:columns)
+ end
end
end
end
diff --git a/activerecord/test/cases/migration/rename_table_test.rb b/activerecord/test/cases/migration/rename_table_test.rb
index d5ff2c607f..21901bec3c 100644
--- a/activerecord/test/cases/migration/rename_table_test.rb
+++ b/activerecord/test/cases/migration/rename_table_test.rb
@@ -14,6 +14,11 @@ module ActiveRecord
remove_column 'test_models', :updated_at
end
+ def teardown
+ rename_table :octopi, :test_models if connection.table_exists? :octopi
+ super
+ end
+
def test_rename_table_for_sqlite_should_work_with_reserved_words
renamed = false
@@ -26,8 +31,7 @@ module ActiveRecord
renamed = true
# Using explicit id in insert for compatibility across all databases
- con = connection
- con.execute "INSERT INTO 'references' (url, created_at, updated_at) VALUES ('http://rubyonrails.com', 0, 0)"
+ connection.execute "INSERT INTO 'references' (url, created_at, updated_at) VALUES ('http://rubyonrails.com', 0, 0)"
assert_equal 'http://rubyonrails.com', connection.select_value("SELECT url FROM 'references' WHERE id=1")
ensure
return unless renamed
@@ -39,16 +43,13 @@ module ActiveRecord
rename_table :test_models, :octopi
# Using explicit id in insert for compatibility across all databases
- con = connection
- con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
+ connection.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
- con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
+ connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
- con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
+ connection.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1")
-
- rename_table :octopi, :test_models
end
def test_rename_table_with_an_index
@@ -57,15 +58,22 @@ module ActiveRecord
rename_table :test_models, :octopi
# Using explicit id in insert for compatibility across all databases
- con = ActiveRecord::Base.connection
- con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
- con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
- con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
+ connection.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
+ connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
+ connection.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1")
assert connection.indexes(:octopi).first.columns.include?("url")
+ end
+
+ def test_rename_table_for_postgresql_should_also_rename_default_sequence
+ skip 'not supported' unless current_adapter?(:PostgreSQLAdapter)
+
+ rename_table :test_models, :octopi
+
+ pk, seq = connection.pk_and_sequence_for('octopi')
- rename_table :octopi, :test_models
+ assert_equal "octopi_#{pk}_seq", seq
end
end
end
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
index a03c4f552e..08b3408665 100644
--- a/activerecord/test/cases/modules_test.rb
+++ b/activerecord/test/cases/modules_test.rb
@@ -39,7 +39,7 @@ class ModulesTest < ActiveRecord::TestCase
end
def test_associations_spanning_cross_modules
- account = MyApplication::Billing::Account.scoped(:order => 'id').first
+ account = MyApplication::Billing::Account.all.merge!(:order => 'id').first
assert_kind_of MyApplication::Business::Firm, account.firm
assert_kind_of MyApplication::Billing::Firm, account.qualified_billing_firm
assert_kind_of MyApplication::Billing::Firm, account.unqualified_billing_firm
@@ -48,7 +48,7 @@ class ModulesTest < ActiveRecord::TestCase
end
def test_find_account_and_include_company
- account = MyApplication::Billing::Account.scoped(:includes => :firm).find(1)
+ account = MyApplication::Billing::Account.all.merge!(:includes => :firm).find(1)
assert_kind_of MyApplication::Business::Firm, account.firm
end
@@ -72,8 +72,8 @@ class ModulesTest < ActiveRecord::TestCase
clients = []
assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do
- clients << MyApplication::Business::Client.references(:accounts).scoped(:includes => {:firm => :account}, :where => 'accounts.id IS NOT NULL').find(3)
- clients << MyApplication::Business::Client.scoped(:includes => {:firm => :account}).find(3)
+ clients << MyApplication::Business::Client.references(:accounts).merge!(:includes => {:firm => :account}, :where => 'accounts.id IS NOT NULL').find(3)
+ clients << MyApplication::Business::Client.includes(:firm => :account).find(3)
end
clients.each do |client|
diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb
index 06d6596725..42461e8ecb 100644
--- a/activerecord/test/cases/multiple_db_test.rb
+++ b/activerecord/test/cases/multiple_db_test.rb
@@ -1,9 +1,7 @@
require "cases/helper"
require 'models/entrant'
require 'models/bird'
-
-# So we can test whether Course.connection survives a reload.
-require_dependency 'models/course'
+require 'models/course'
class MultipleDbTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index c886160af3..bd121126e7 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -12,10 +12,10 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_implements_enumerable
assert !Topic.all.empty?
- assert_equal Topic.all, Topic.base
- assert_equal Topic.all, Topic.base.to_a
- assert_equal Topic.first, Topic.base.first
- assert_equal Topic.all, Topic.base.map { |i| i }
+ assert_equal Topic.all.to_a, Topic.base
+ assert_equal Topic.all.to_a, Topic.base.to_a
+ assert_equal Topic.first, Topic.base.first
+ assert_equal Topic.all.to_a, Topic.base.map { |i| i }
end
def test_found_items_are_cached
@@ -29,7 +29,7 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_reload_expires_cache_of_found_items
all_posts = Topic.base
- all_posts.all
+ all_posts.to_a
new_post = Topic.create!
assert !all_posts.include?(new_post)
@@ -39,9 +39,9 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_delegates_finds_and_calculations_to_the_base_class
assert !Topic.all.empty?
- assert_equal Topic.all, Topic.base.all
- assert_equal Topic.first, Topic.base.first
- assert_equal Topic.count, Topic.base.count
+ assert_equal Topic.all.to_a, Topic.base.to_a
+ assert_equal Topic.first, Topic.base.first
+ assert_equal Topic.count, Topic.base.count
assert_equal Topic.average(:replies_count), Topic.base.average(:replies_count)
end
@@ -51,7 +51,7 @@ class NamedScopeTest < ActiveRecord::TestCase
scope :since, Proc.new { where('written_on >= ?', Time.now - 1.day) }
scope :to, Proc.new { where('written_on <= ?', Time.now) }
end
- assert_equal klazz.to.since.all, klazz.since.to.all
+ assert_equal klazz.to.since.to_a, klazz.since.to.to_a
end
def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
@@ -66,9 +66,9 @@ class NamedScopeTest < ActiveRecord::TestCase
end
def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
- assert !Topic.scoped(:where => {:approved => true}).all.empty?
+ assert !Topic.all.merge!(:where => {:approved => true}).to_a.empty?
- assert_equal Topic.scoped(:where => {:approved => true}).all, Topic.approved
+ assert_equal Topic.all.merge!(:where => {:approved => true}).to_a, Topic.approved
assert_equal Topic.where(:approved => true).count, Topic.approved.count
end
@@ -79,8 +79,8 @@ class NamedScopeTest < ActiveRecord::TestCase
end
def test_scopes_are_composable
- assert_equal((approved = Topic.scoped(:where => {:approved => true}).all), Topic.approved)
- assert_equal((replied = Topic.scoped(:where => 'replies_count > 0').all), Topic.replied)
+ assert_equal((approved = Topic.all.merge!(:where => {:approved => true}).to_a), Topic.approved)
+ assert_equal((replied = Topic.all.merge!(:where => 'replies_count > 0').to_a), Topic.replied)
assert !(approved == replied)
assert !(approved & replied).empty?
@@ -140,14 +140,14 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_active_records_have_scope_named__all__
assert !Topic.all.empty?
- assert_equal Topic.all, Topic.base
+ assert_equal Topic.all.to_a, Topic.base
end
def test_active_records_have_scope_named__scoped__
scope = Topic.where("content LIKE '%Have%'")
assert !scope.empty?
- assert_equal scope, Topic.scoped(where: "content LIKE '%Have%'")
+ assert_equal scope, Topic.all.merge!(where: "content LIKE '%Have%'")
end
def test_first_and_last_should_allow_integers_for_limit
@@ -325,14 +325,14 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_chaining_should_use_latest_conditions_when_searching
# Normal hash conditions
- assert_equal Topic.where(:approved => true).to_a, Topic.rejected.approved.all
- assert_equal Topic.where(:approved => false).to_a, Topic.approved.rejected.all
+ assert_equal Topic.where(:approved => true).to_a, Topic.rejected.approved.to_a
+ assert_equal Topic.where(:approved => false).to_a, Topic.approved.rejected.to_a
# Nested hash conditions with same keys
- assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.all
+ assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.to_a
# Nested hash conditions with different keys
- assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).all.uniq
+ assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).to_a.uniq
end
def test_scopes_batch_finders
@@ -351,13 +351,13 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_table_names_for_chaining_scopes_with_and_without_table_name_included
assert_nothing_raised do
- Comment.for_first_post.for_first_author.all
+ Comment.for_first_post.for_first_author.to_a
end
end
def test_scopes_on_relations
# Topic.replied
- approved_topics = Topic.scoped.approved.order('id DESC')
+ approved_topics = Topic.all.approved.order('id DESC')
assert_equal topics(:fourth), approved_topics.first
replied_approved_topics = approved_topics.replied
@@ -372,7 +372,7 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_nested_scopes_queries_size
assert_queries(1) do
- Topic.approved.by_lifo.replied.written_before(Time.now).all
+ Topic.approved.by_lifo.replied.written_before(Time.now).to_a
end
end
@@ -383,8 +383,8 @@ class NamedScopeTest < ActiveRecord::TestCase
post = posts(:welcome)
Post.cache do
- assert_queries(1) { post.comments.containing_the_letter_e.all }
- assert_no_queries { post.comments.containing_the_letter_e.all }
+ assert_queries(1) { post.comments.containing_the_letter_e.to_a }
+ assert_no_queries { post.comments.containing_the_letter_e.to_a }
end
end
@@ -392,14 +392,14 @@ class NamedScopeTest < ActiveRecord::TestCase
post = posts(:welcome)
Post.cache do
- one = assert_queries(1) { post.comments.limit_by(1).all }
+ one = assert_queries(1) { post.comments.limit_by(1).to_a }
assert_equal 1, one.size
- two = assert_queries(1) { post.comments.limit_by(2).all }
+ two = assert_queries(1) { post.comments.limit_by(2).to_a }
assert_equal 2, two.size
- assert_no_queries { post.comments.limit_by(1).all }
- assert_no_queries { post.comments.limit_by(2).all }
+ assert_no_queries { post.comments.limit_by(1).to_a }
+ assert_no_queries { post.comments.limit_by(2).to_a }
end
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 3a234f0cc1..07862ca4ca 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -771,9 +771,9 @@ module NestedAttributesOnACollectionAssociationTests
assert !man.errors[:"interests.man"].empty?
end
end
- # restore :inverse_of
+ ensure
Man.reflect_on_association(:interests).options[:inverse_of] = :man
- Interest.reflect_on_association(:man).options[:inverse_of] = :interests
+ Interest.reflect_on_association(:man).options[:inverse_of] = :interests
end
def test_can_use_symbols_as_object_identifier
@@ -783,12 +783,14 @@ module NestedAttributesOnACollectionAssociationTests
def test_numeric_colum_changes_from_zero_to_no_empty_string
Man.accepts_nested_attributes_for(:interests)
- Interest.validates_numericality_of(:zine_id)
- man = Man.create(:name => 'John')
- interest = man.interests.create(:topic=>'bar',:zine_id => 0)
- assert interest.save
- assert !man.update_attributes({:interests_attributes => { :id => interest.id, :zine_id => 'foo' }})
+ repair_validations(Interest) do
+ Interest.validates_numericality_of(:zine_id)
+ man = Man.create(name: 'John')
+ interest = man.interests.create(topic: 'bar', zine_id: 0)
+ assert interest.save
+ assert !man.update_attributes({interests_attributes: { id: interest.id, zine_id: 'foo' }})
+ end
end
private
@@ -846,13 +848,7 @@ class TestNestedAttributesOnAHasAndBelongsToManyAssociation < ActiveRecord::Test
include NestedAttributesOnACollectionAssociationTests
end
-class TestNestedAttributesLimit < ActiveRecord::TestCase
- def setup
- Pirate.accepts_nested_attributes_for :parrots, :limit => 2
-
- @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
- end
-
+module NestedAttributesLimitTests
def teardown
Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
end
@@ -876,6 +872,36 @@ class TestNestedAttributesLimit < ActiveRecord::TestCase
end
end
+class TestNestedAttributesLimitNumeric < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => 2
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ include NestedAttributesLimitTests
+end
+
+class TestNestedAttributesLimitSymbol < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => :parrots_limit
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?", :parrots_limit => 2)
+ end
+
+ include NestedAttributesLimitTests
+end
+
+class TestNestedAttributesLimitProc < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => proc { 2 }
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ include NestedAttributesLimitTests
+end
+
class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase
fixtures :owners, :pets
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index b7b77b24af..4ffa4836e0 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -55,7 +55,7 @@ class PersistencesTest < ActiveRecord::TestCase
author = authors(:david)
assert_nothing_raised do
assert_equal 1, author.posts_sorted_by_id_limited.size
- assert_equal 2, author.posts_sorted_by_id_limited.scoped(:limit => 2).all.size
+ assert_equal 2, author.posts_sorted_by_id_limited.limit(2).to_a.size
assert_equal 1, author.posts_sorted_by_id_limited.update_all([ "body = ?", "bulk update!" ])
assert_equal "bulk update!", posts(:welcome).body
assert_not_equal "bulk update!", posts(:thinking).body
@@ -120,7 +120,7 @@ class PersistencesTest < ActiveRecord::TestCase
def test_destroy_all
conditions = "author_name = 'Mary'"
- topics_by_mary = Topic.scoped(:where => conditions, :order => 'id').to_a
+ topics_by_mary = Topic.all.merge!(:where => conditions, :order => 'id').to_a
assert ! topics_by_mary.empty?
assert_difference('Topic.count', -topics_by_mary.size) do
@@ -131,7 +131,7 @@ class PersistencesTest < ActiveRecord::TestCase
end
def test_destroy_many
- clients = Client.scoped(:order => 'id').find([2, 3])
+ clients = Client.all.merge!(:order => 'id').find([2, 3])
assert_difference('Client.count', -2) do
destroyed = Client.destroy([2, 3]).sort_by(&:id)
@@ -371,10 +371,50 @@ class PersistencesTest < ActiveRecord::TestCase
assert_raise(ActiveSupport::FrozenObjectError) { client.name = "something else" }
end
+ def test_update_attribute
+ assert !Topic.find(1).approved?
+ Topic.find(1).update_attribute("approved", true)
+ assert Topic.find(1).approved?
+
+ Topic.find(1).update_attribute(:approved, false)
+ assert !Topic.find(1).approved?
+ end
+
def test_update_attribute_does_not_choke_on_nil
assert Topic.find(1).update_attributes(nil)
end
+ def test_update_attribute_for_readonly_attribute
+ minivan = Minivan.find('m1')
+ assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, 'black') }
+ end
+
+ def test_update_attribute_with_one_updated
+ t = Topic.first
+ t.update_attribute(:title, 'super_title')
+ assert_equal 'super_title', t.title
+ assert !t.changed?, "topic should not have changed"
+ assert !t.title_changed?, "title should not have changed"
+ assert_nil t.title_change, 'title change should be nil'
+
+ t.reload
+ assert_equal 'super_title', t.title
+ end
+
+ def test_update_attribute_for_updated_at_on
+ developer = Developer.find(1)
+ prev_month = Time.now.prev_month
+
+ developer.update_attribute(:updated_at, prev_month)
+ assert_equal prev_month, developer.updated_at
+
+ developer.update_attribute(:salary, 80001)
+ assert_not_equal prev_month, developer.updated_at
+
+ developer.reload
+ assert_not_equal prev_month, developer.updated_at
+ end
+
def test_update_column
topic = Topic.find(1)
topic.update_column("approved", true)
@@ -461,6 +501,97 @@ class PersistencesTest < ActiveRecord::TestCase
assert_equal 'super_title', t.title
end
+ def test_update_columns
+ topic = Topic.find(1)
+ topic.update_columns({ "approved" => true, title: "Sebastian Topic" })
+ assert topic.approved?
+ assert_equal "Sebastian Topic", topic.title
+ topic.reload
+ assert topic.approved?
+ assert_equal "Sebastian Topic", topic.title
+ end
+
+ def test_update_columns_should_not_use_setter_method
+ dev = Developer.find(1)
+ dev.instance_eval { def salary=(value); write_attribute(:salary, value * 2); end }
+
+ dev.update_columns(salary: 80000)
+ assert_equal 80000, dev.salary
+
+ dev.reload
+ assert_equal 80000, dev.salary
+ end
+
+ def test_update_columns_should_raise_exception_if_new_record
+ topic = Topic.new
+ assert_raises(ActiveRecord::ActiveRecordError) { topic.update_columns({ approved: false }) }
+ end
+
+ def test_update_columns_should_not_leave_the_object_dirty
+ topic = Topic.find(1)
+ topic.update_attributes({ "content" => "Have a nice day", :author_name => "Jose" })
+
+ topic.reload
+ topic.update_columns({ content: "You too", "author_name" => "Sebastian" })
+ assert_equal [], topic.changed
+
+ topic.reload
+ topic.update_columns({ content: "Have a nice day", author_name: "Jose" })
+ assert_equal [], topic.changed
+ end
+
+ def test_update_columns_with_model_having_primary_key_other_than_id
+ minivan = Minivan.find('m1')
+ new_name = 'sebavan'
+
+ minivan.update_columns(name: new_name)
+ assert_equal new_name, minivan.name
+ end
+
+ def test_update_columns_with_one_readonly_attribute
+ minivan = Minivan.find('m1')
+ prev_color = minivan.color
+ prev_name = minivan.name
+ assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_columns({ name: "My old minivan", color: 'black' }) }
+ assert_equal prev_color, minivan.color
+ assert_equal prev_name, minivan.name
+
+ minivan.reload
+ assert_equal prev_color, minivan.color
+ assert_equal prev_name, minivan.name
+ end
+
+ def test_update_columns_should_not_modify_updated_at
+ developer = Developer.find(1)
+ prev_month = Time.now.prev_month
+
+ developer.update_columns(updated_at: prev_month)
+ assert_equal prev_month, developer.updated_at
+
+ developer.update_columns(salary: 80000)
+ assert_equal prev_month, developer.updated_at
+ assert_equal 80000, developer.salary
+
+ developer.reload
+ assert_equal prev_month.to_i, developer.updated_at.to_i
+ assert_equal 80000, developer.salary
+ end
+
+ def test_update_columns_with_one_changed_and_one_updated
+ t = Topic.order('id').limit(1).first
+ author_name = t.author_name
+ t.author_name = 'John'
+ t.update_columns(title: 'super_title')
+ assert_equal 'John', t.author_name
+ assert_equal 'super_title', t.title
+ assert t.changed?, "topic should have changed"
+ assert t.author_name_changed?, "author_name should have changed"
+
+ t.reload
+ assert_equal author_name, t.author_name
+ assert_equal 'super_title', t.title
+ end
+
def test_update_attributes
topic = Topic.find(1)
assert !topic.approved?
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index 0153e74604..2d778e9e90 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -39,6 +39,18 @@ class QueryCacheTest < ActiveRecord::TestCase
assert ActiveRecord::Base.connection.query_cache_enabled, 'cache on'
end
+ def test_exceptional_middleware_assigns_original_connection_id_on_error
+ connection_id = ActiveRecord::Base.connection_id
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ ActiveRecord::Base.connection_id = self.object_id
+ raise "lol borked"
+ }
+ assert_raises(RuntimeError) { mw.call({}) }
+
+ assert_equal connection_id, ActiveRecord::Base.connection_id
+ end
+
def test_middleware_delegates
called = false
mw = ActiveRecord::QueryCache.new lambda { |env|
@@ -155,7 +167,7 @@ class QueryCacheTest < ActiveRecord::TestCase
# Oracle adapter returns count() as Fixnum or Float
if current_adapter?(:OracleAdapter)
assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
- elsif current_adapter?(:SQLite3Adapter) || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
+ elsif current_adapter?(:SQLite3Adapter) || current_adapter?(:Mysql2Adapter)
# Future versions of the sqlite3 adapter will return numeric
assert_instance_of Fixnum,
Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index df0399f548..df076c97b4 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -49,7 +49,7 @@ class ReadOnlyTest < ActiveRecord::TestCase
post = Post.find(1)
assert !post.comments.empty?
assert !post.comments.any?(&:readonly?)
- assert !post.comments.all.any?(&:readonly?)
+ assert !post.comments.to_a.any?(&:readonly?)
assert post.comments.readonly(true).all?(&:readonly?)
end
@@ -71,13 +71,13 @@ class ReadOnlyTest < ActiveRecord::TestCase
end
def test_readonly_scoping
- Post.where('1=1').scoped do
+ Post.where('1=1').scoping do
assert !Post.find(1).readonly?
assert Post.readonly(true).find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
end
- Post.joins(' ').scoped do
+ Post.joins(' ').scoping do
assert !Post.find(1).readonly?
assert Post.readonly.find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
@@ -86,14 +86,14 @@ class ReadOnlyTest < ActiveRecord::TestCase
# Oracle barfs on this because the join includes unqualified and
# conflicting column names
unless current_adapter?(:OracleAdapter)
- Post.joins(', developers').scoped do
+ Post.joins(', developers').scoping do
assert Post.find(1).readonly?
assert Post.readonly.find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
end
end
- Post.readonly(true).scoped do
+ Post.readonly(true).scoping do
assert Post.find(1).readonly?
assert Post.readonly.find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index 6631dce08f..588da68ec1 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -77,12 +77,36 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_reflection_klass_for_nested_class_name
- reflection = MacroReflection.new(:company, nil, { :class_name => 'MyApplication::Business::Company' }, ActiveRecord::Base)
+ reflection = MacroReflection.new(:company, nil, nil, { :class_name => 'MyApplication::Business::Company' }, ActiveRecord::Base)
assert_nothing_raised do
assert_equal MyApplication::Business::Company, reflection.klass
end
end
+ def test_aggregation_reflection
+ reflection_for_address = AggregateReflection.new(
+ :composed_of, :address, nil, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer
+ )
+
+ reflection_for_balance = AggregateReflection.new(
+ :composed_of, :balance, nil, { :class_name => "Money", :mapping => %w(balance amount) }, Customer
+ )
+
+ reflection_for_gps_location = AggregateReflection.new(
+ :composed_of, :gps_location, nil, { }, Customer
+ )
+
+ assert Customer.reflect_on_all_aggregations.include?(reflection_for_gps_location)
+ assert Customer.reflect_on_all_aggregations.include?(reflection_for_balance)
+ assert Customer.reflect_on_all_aggregations.include?(reflection_for_address)
+
+ assert_equal reflection_for_address, Customer.reflect_on_aggregation(:address)
+
+ assert_equal Address, Customer.reflect_on_aggregation(:address).klass
+
+ assert_equal Money, Customer.reflect_on_aggregation(:balance).klass
+ end
+
def test_reflect_on_all_autosave_associations
expected = Pirate.reflect_on_all_associations.select { |r| r.options[:autosave] }
received = Pirate.reflect_on_all_autosave_associations
@@ -93,7 +117,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_has_many_reflection
- reflection_for_clients = AssociationReflection.new(:has_many, :clients, { :order => "id", :dependent => :destroy }, Firm)
+ reflection_for_clients = AssociationReflection.new(:has_many, :clients, nil, { :order => "id", :dependent => :destroy }, Firm)
assert_equal reflection_for_clients, Firm.reflect_on_association(:clients)
@@ -105,7 +129,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_has_one_reflection
- reflection_for_account = AssociationReflection.new(:has_one, :account, { :foreign_key => "firm_id", :dependent => :destroy }, Firm)
+ reflection_for_account = AssociationReflection.new(:has_one, :account, nil, { :foreign_key => "firm_id", :dependent => :destroy }, Firm)
assert_equal reflection_for_account, Firm.reflect_on_association(:account)
assert_equal Account, Firm.reflect_on_association(:account).klass
@@ -190,21 +214,25 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal expected, actual
end
- def test_conditions
+ def test_scope_chain
expected = [
- [{ :tags => { :name => 'Blue' } }],
- [{ :taggings => { :comment => 'first' } }],
- [{ :posts => { :title => ['misc post by bob', 'misc post by mary'] } }]
+ [Tagging.reflect_on_association(:tag).scope, Post.reflect_on_association(:first_blue_tags).scope],
+ [Post.reflect_on_association(:first_taggings).scope],
+ [Author.reflect_on_association(:misc_posts).scope]
]
- actual = Author.reflect_on_association(:misc_post_first_blue_tags).conditions
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags).scope_chain
assert_equal expected, actual
expected = [
- [{ :tags => { :name => 'Blue' } }, { :taggings => { :comment => 'first' } }, { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }],
+ [
+ Tagging.reflect_on_association(:blue_tag).scope,
+ Post.reflect_on_association(:first_blue_tags_2).scope,
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).scope
+ ],
[],
[]
]
- actual = Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags_2).scope_chain
assert_equal expected, actual
end
@@ -230,10 +258,10 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_association_primary_key_raises_when_missing_primary_key
- reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, {}, Author)
+ reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, nil, {}, Author)
assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.association_primary_key }
- through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, {}, Author)
+ through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, nil, {}, Author)
through.stubs(:source_reflection).returns(stub_everything(:options => {}, :class_name => 'Edge'))
assert_raises(ActiveRecord::UnknownPrimaryKey) { through.association_primary_key }
end
@@ -244,7 +272,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_active_record_primary_key_raises_when_missing_primary_key
- reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, {}, Edge)
+ reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, nil, {}, Edge)
assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.active_record_primary_key }
end
@@ -262,32 +290,32 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_default_association_validation
- assert AssociationReflection.new(:has_many, :clients, {}, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, {}, Firm).validate?
- assert !AssociationReflection.new(:has_one, :client, {}, Firm).validate?
- assert !AssociationReflection.new(:belongs_to, :client, {}, Firm).validate?
- assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, {}, Firm).validate?
+ assert !AssociationReflection.new(:has_one, :client, nil, {}, Firm).validate?
+ assert !AssociationReflection.new(:belongs_to, :client, nil, {}, Firm).validate?
+ assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, {}, Firm).validate?
end
def test_always_validate_association_if_explicit
- assert AssociationReflection.new(:has_one, :client, { :validate => true }, Firm).validate?
- assert AssociationReflection.new(:belongs_to, :client, { :validate => true }, Firm).validate?
- assert AssociationReflection.new(:has_many, :clients, { :validate => true }, Firm).validate?
- assert AssociationReflection.new(:has_and_belongs_to_many, :clients, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_one, :client, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:belongs_to, :client, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :validate => true }, Firm).validate?
end
def test_validate_association_if_autosave
- assert AssociationReflection.new(:has_one, :client, { :autosave => true }, Firm).validate?
- assert AssociationReflection.new(:belongs_to, :client, { :autosave => true }, Firm).validate?
- assert AssociationReflection.new(:has_many, :clients, { :autosave => true }, Firm).validate?
- assert AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_one, :client, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:belongs_to, :client, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :autosave => true }, Firm).validate?
end
def test_never_validate_association_if_explicit
- assert !AssociationReflection.new(:has_one, :client, { :autosave => true, :validate => false }, Firm).validate?
- assert !AssociationReflection.new(:belongs_to, :client, { :autosave => true, :validate => false }, Firm).validate?
- assert !AssociationReflection.new(:has_many, :clients, { :autosave => true, :validate => false }, Firm).validate?
- assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_one, :client, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:belongs_to, :client, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate?
end
def test_foreign_key
@@ -295,10 +323,10 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s
end
- def test_through_reflection_conditions_do_not_modify_other_reflections
- orig_conds = Post.reflect_on_association(:first_blue_tags_2).conditions.inspect
- Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions
- assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).conditions.inspect
+ def test_through_reflection_scope_chain_does_not_modify_other_reflections
+ orig_conds = Post.reflect_on_association(:first_blue_tags_2).scope_chain.inspect
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).scope_chain
+ assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).scope_chain.inspect
end
def test_symbol_for_class_name
@@ -309,11 +337,11 @@ class ReflectionTest < ActiveRecord::TestCase
category = Struct.new(:table_name, :pluralize_table_names).new('categories', true)
product = Struct.new(:table_name, :pluralize_table_names).new('products', true)
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, {}, product)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, product)
reflection.stubs(:klass).returns(category)
assert_equal 'categories_products', reflection.join_table
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, {}, category)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, {}, category)
reflection.stubs(:klass).returns(product)
assert_equal 'categories_products', reflection.join_table
end
@@ -322,11 +350,11 @@ class ReflectionTest < ActiveRecord::TestCase
category = Struct.new(:table_name, :pluralize_table_names).new('catalog_categories', true)
product = Struct.new(:table_name, :pluralize_table_names).new('catalog_products', true)
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, {}, product)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, product)
reflection.stubs(:klass).returns(category)
assert_equal 'catalog_categories_products', reflection.join_table
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, {}, category)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, {}, category)
reflection.stubs(:klass).returns(product)
assert_equal 'catalog_categories_products', reflection.join_table
end
@@ -335,11 +363,11 @@ class ReflectionTest < ActiveRecord::TestCase
category = Struct.new(:table_name, :pluralize_table_names).new('catalog_categories', true)
page = Struct.new(:table_name, :pluralize_table_names).new('content_pages', true)
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, {}, page)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, page)
reflection.stubs(:klass).returns(category)
assert_equal 'catalog_categories_content_pages', reflection.join_table
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :pages, {}, category)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :pages, nil, {}, category)
reflection.stubs(:klass).returns(page)
assert_equal 'catalog_categories_content_pages', reflection.join_table
end
@@ -348,11 +376,11 @@ class ReflectionTest < ActiveRecord::TestCase
category = Struct.new(:table_name, :pluralize_table_names).new('categories', true)
product = Struct.new(:table_name, :pluralize_table_names).new('products', true)
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, { :join_table => 'product_categories' }, product)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, { :join_table => 'product_categories' }, product)
reflection.stubs(:klass).returns(category)
assert_equal 'product_categories', reflection.join_table
- reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, { :join_table => 'product_categories' }, category)
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, { :join_table => 'product_categories' }, category)
reflection.stubs(:klass).returns(product)
assert_equal 'product_categories', reflection.join_table
end
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index cf367242f2..d318dab1e1 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -106,7 +106,7 @@ class RelationScopingTest < ActiveRecord::TestCase
def test_scoped_find_include
# with the include, will retrieve only developers for the given project
scoped_developers = Developer.includes(:projects).scoping do
- Developer.where('projects.id' => 2).all
+ Developer.where('projects.id' => 2).to_a
end
assert scoped_developers.include?(developers(:david))
assert !scoped_developers.include?(developers(:jamis))
@@ -115,7 +115,7 @@ class RelationScopingTest < ActiveRecord::TestCase
def test_scoped_find_joins
scoped_developers = Developer.joins('JOIN developers_projects ON id = developer_id').scoping do
- Developer.where('developers_projects.project_id = 2').all
+ Developer.where('developers_projects.project_id = 2').to_a
end
assert scoped_developers.include?(developers(:david))
@@ -159,7 +159,7 @@ class RelationScopingTest < ActiveRecord::TestCase
rescue
end
- assert !Developer.scoped.where_values.include?("name = 'Jamis'")
+ assert !Developer.all.where_values.include?("name = 'Jamis'")
end
end
@@ -169,7 +169,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
def test_merge_options
Developer.where('salary = 80000').scoping do
Developer.limit(10).scoping do
- devs = Developer.scoped
+ devs = Developer.all
assert_match '(salary = 80000)', devs.to_sql
assert_equal 10, devs.taken
end
@@ -312,7 +312,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
fixtures :developers, :posts
def test_default_scope
- expected = Developer.scoped(:order => 'salary DESC').all.collect { |dev| dev.salary }
+ expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.all.collect { |dev| dev.salary }
assert_equal expected, received
end
@@ -362,31 +362,31 @@ class DefaultScopingTest < ActiveRecord::TestCase
def test_default_scoping_with_threads
2.times do
- Thread.new { assert DeveloperOrderedBySalary.scoped.to_sql.include?('salary DESC') }.join
+ Thread.new { assert DeveloperOrderedBySalary.all.to_sql.include?('salary DESC') }.join
end
end
def test_default_scope_with_inheritance
- wheres = InheritedPoorDeveloperCalledJamis.scoped.where_values_hash
+ wheres = InheritedPoorDeveloperCalledJamis.all.where_values_hash
assert_equal "Jamis", wheres[:name]
assert_equal 50000, wheres[:salary]
end
def test_default_scope_with_module_includes
- wheres = ModuleIncludedPoorDeveloperCalledJamis.scoped.where_values_hash
+ wheres = ModuleIncludedPoorDeveloperCalledJamis.all.where_values_hash
assert_equal "Jamis", wheres[:name]
assert_equal 50000, wheres[:salary]
end
def test_default_scope_with_multiple_calls
- wheres = MultiplePoorDeveloperCalledJamis.scoped.where_values_hash
+ wheres = MultiplePoorDeveloperCalledJamis.all.where_values_hash
assert_equal "Jamis", wheres[:name]
assert_equal 50000, wheres[:salary]
end
def test_scope_overwrites_default
- expected = Developer.scoped(:order => 'salary DESC, name DESC').all.collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.by_name.all.collect { |dev| dev.name }
+ expected = Developer.all.merge!(:order => ' name DESC, salary DESC').to_a.collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.by_name.to_a.collect { |dev| dev.name }
assert_equal expected, received
end
@@ -397,14 +397,14 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_order_after_reorder_combines_orders
- expected = Developer.order('name DESC, id DESC').collect { |dev| [dev.name, dev.id] }
+ expected = Developer.order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
received = Developer.order('name ASC').reorder('name DESC').order('id DESC').collect { |dev| [dev.name, dev.id] }
assert_equal expected, received
end
- def test_order_in_default_scope_should_prevail
- expected = Developer.scoped(:order => 'salary desc').all.collect { |dev| dev.salary }
- received = DeveloperOrderedBySalary.scoped(:order => 'salary').all.collect { |dev| dev.salary }
+ def test_order_in_default_scope_should_not_prevail
+ expected = Developer.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
assert_equal expected, received
end
@@ -472,7 +472,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_default_scope_select_ignored_by_aggregations
- assert_equal DeveloperWithSelect.all.count, DeveloperWithSelect.count
+ assert_equal DeveloperWithSelect.all.to_a.count, DeveloperWithSelect.count
end
def test_default_scope_select_ignored_by_grouped_aggregations
@@ -508,10 +508,10 @@ class DefaultScopingTest < ActiveRecord::TestCase
threads << Thread.new do
Thread.current[:long_default_scope] = true
- assert_equal 1, ThreadsafeDeveloper.all.count
+ assert_equal 1, ThreadsafeDeveloper.all.to_a.count
end
threads << Thread.new do
- assert_equal 1, ThreadsafeDeveloper.all.count
+ assert_equal 1, ThreadsafeDeveloper.all.to_a.count
end
threads.each(&:join)
end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index 89f818a689..6399111be6 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -19,6 +19,11 @@ module ActiveRecord
assert !relation.loaded, 'relation is not loaded'
end
+ def test_responds_to_model_and_returns_klass
+ relation = Relation.new :a, :b
+ assert_equal :a, relation.model
+ end
+
def test_initialize_single_values
relation = Relation.new :a, :b
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |method|
@@ -191,11 +196,14 @@ module ActiveRecord
end
test 'extending!' do
- mod = Module.new
+ mod, mod2 = Module.new, Module.new
assert relation.extending!(mod).equal?(relation)
- assert [mod], relation.extending_values
+ assert_equal [mod], relation.extending_values
assert relation.is_a?(mod)
+
+ relation.extending!(mod2)
+ assert_equal [mod, mod2], relation.extending_values
end
test 'extending! with empty args' do
@@ -244,5 +252,9 @@ module ActiveRecord
assert relation.merge!(where: :foo).equal?(relation)
assert_equal [:foo], relation.where_values
end
+
+ test 'merge with a proc' do
+ assert_equal [:foo], relation.merge(-> { where(:foo) }).where_values
+ end
end
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 8713b8d5e4..b91423351e 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -34,7 +34,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_bind_values
- relation = Post.scoped
+ relation = Post.all
assert_equal [], relation.bind_values
relation2 = relation.bind 'foo'
@@ -59,44 +59,44 @@ class RelationTest < ActiveRecord::TestCase
end
def test_scoped
- topics = Topic.scoped
+ topics = Topic.all
assert_kind_of ActiveRecord::Relation, topics
assert_equal 4, topics.size
end
def test_to_json
- assert_nothing_raised { Bird.scoped.to_json }
- assert_nothing_raised { Bird.scoped.all.to_json }
+ assert_nothing_raised { Bird.all.to_json }
+ assert_nothing_raised { Bird.all.to_a.to_json }
end
def test_to_yaml
- assert_nothing_raised { Bird.scoped.to_yaml }
- assert_nothing_raised { Bird.scoped.all.to_yaml }
+ assert_nothing_raised { Bird.all.to_yaml }
+ assert_nothing_raised { Bird.all.to_a.to_yaml }
end
def test_to_xml
- assert_nothing_raised { Bird.scoped.to_xml }
- assert_nothing_raised { Bird.scoped.all.to_xml }
+ assert_nothing_raised { Bird.all.to_xml }
+ assert_nothing_raised { Bird.all.to_a.to_xml }
end
def test_scoped_all
- topics = Topic.scoped.all
+ topics = Topic.all.to_a
assert_kind_of Array, topics
assert_no_queries { assert_equal 4, topics.size }
end
def test_loaded_all
- topics = Topic.scoped
+ topics = Topic.all
assert_queries(1) do
- 2.times { assert_equal 4, topics.all.size }
+ 2.times { assert_equal 4, topics.to_a.size }
end
assert topics.loaded?
end
def test_scoped_first
- topics = Topic.scoped.order('id ASC')
+ topics = Topic.all.order('id ASC')
assert_queries(1) do
2.times { assert_equal "The First Topic", topics.first.title }
@@ -106,10 +106,10 @@ class RelationTest < ActiveRecord::TestCase
end
def test_loaded_first
- topics = Topic.scoped.order('id ASC')
+ topics = Topic.all.order('id ASC')
assert_queries(1) do
- topics.all # force load
+ topics.to_a # force load
2.times { assert_equal "The First Topic", topics.first.title }
end
@@ -117,7 +117,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_reload
- topics = Topic.scoped
+ topics = Topic.all
assert_queries(1) do
2.times { topics.to_a }
@@ -165,13 +165,13 @@ class RelationTest < ActiveRecord::TestCase
end
def test_finding_with_order_concatenated
- topics = Topic.order('author_name').order('title')
+ topics = Topic.order('title').order('author_name')
assert_equal 4, topics.to_a.size
assert_equal topics(:fourth).title, topics.first.title
end
def test_finding_with_reorder
- topics = Topic.order('author_name').order('title').reorder('id').all
+ topics = Topic.order('author_name').order('title').reorder('id').to_a
topics_titles = topics.map{ |t| t.title }
assert_equal ['The First Topic', 'The Second Topic of the day', 'The Third Topic of the day', 'The Fourth Topic of the day'], topics_titles
end
@@ -218,14 +218,14 @@ class RelationTest < ActiveRecord::TestCase
end
def test_select_with_block
- even_ids = Developer.scoped.select {|d| d.id % 2 == 0 }.map(&:id)
+ even_ids = Developer.all.select {|d| d.id % 2 == 0 }.map(&:id)
assert_equal [2, 4, 6, 8, 10], even_ids.sort
end
def test_none
assert_no_queries do
assert_equal [], Developer.none
- assert_equal [], Developer.scoped.none
+ assert_equal [], Developer.all.none
end
end
@@ -294,7 +294,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_find_on_hash_conditions
- assert_equal Topic.scoped(:where => {:approved => false}).all, Topic.where({ :approved => false }).to_a
+ assert_equal Topic.all.merge!(:where => {:approved => false}).to_a, Topic.where({ :approved => false }).to_a
end
def test_joins_with_string_array
@@ -307,15 +307,15 @@ class RelationTest < ActiveRecord::TestCase
end
def test_scoped_responds_to_delegated_methods
- relation = Topic.scoped
+ relation = Topic.all
["map", "uniq", "sort", "insert", "delete", "update"].each do |method|
- assert_respond_to relation, method, "Topic.scoped should respond to #{method.inspect}"
+ assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}"
end
end
def test_respond_to_delegates_to_relation
- relation = Topic.scoped
+ relation = Topic.all
fake_arel = Struct.new(:responds) {
def respond_to? method, access = false
responds << [method, access]
@@ -334,20 +334,20 @@ class RelationTest < ActiveRecord::TestCase
end
def test_respond_to_dynamic_finders
- relation = Topic.scoped
+ relation = Topic.all
["find_by_title", "find_by_title_and_author_name", "find_or_create_by_title", "find_or_initialize_by_title_and_author_name"].each do |method|
- assert_respond_to relation, method, "Topic.scoped should respond to #{method.inspect}"
+ assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}"
end
end
def test_respond_to_class_methods_and_scopes
- assert Topic.scoped.respond_to?(:by_lifo)
+ assert Topic.all.respond_to?(:by_lifo)
end
def test_find_with_readonly_option
- Developer.scoped.each { |d| assert !d.readonly? }
- Developer.scoped.readonly.each { |d| assert d.readonly? }
+ Developer.all.each { |d| assert !d.readonly? }
+ Developer.all.readonly.each { |d| assert d.readonly? }
end
def test_eager_association_loading_of_stis_with_multiple_references
@@ -396,7 +396,7 @@ class RelationTest < ActiveRecord::TestCase
end
assert_queries(2) do
- posts = Post.scoped.includes(:comments).order('posts.id')
+ posts = Post.all.includes(:comments).order('posts.id')
assert posts.first.comments.first
end
@@ -413,12 +413,12 @@ class RelationTest < ActiveRecord::TestCase
end
def test_default_scope_with_conditions_string
- assert_equal Developer.where(name: 'David').map(&:id).sort, DeveloperCalledDavid.scoped.map(&:id).sort
+ assert_equal Developer.where(name: 'David').map(&:id).sort, DeveloperCalledDavid.all.map(&:id).sort
assert_nil DeveloperCalledDavid.create!.name
end
def test_default_scope_with_conditions_hash
- assert_equal Developer.where(name: 'Jamis').map(&:id).sort, DeveloperCalledJamis.scoped.map(&:id).sort
+ assert_equal Developer.where(name: 'Jamis').map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
assert_equal 'Jamis', DeveloperCalledJamis.create!.name
end
@@ -457,20 +457,20 @@ class RelationTest < ActiveRecord::TestCase
assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
end
- authors = Author.scoped
+ authors = Author.all
assert_equal david, authors.find_by_id_and_name(david.id, david.name)
assert_equal david, authors.find_by_id_and_name!(david.id, david.name)
end
def test_dynamic_find_by_attributes_bang
- author = Author.scoped.find_by_id!(authors(:david).id)
+ author = Author.all.find_by_id!(authors(:david).id)
assert_equal "David", author.name
- assert_raises(ActiveRecord::RecordNotFound) { Author.scoped.find_by_id_and_name!(20, 'invalid') }
+ assert_raises(ActiveRecord::RecordNotFound) { Author.all.find_by_id_and_name!(20, 'invalid') }
end
def test_find_id
- authors = Author.scoped
+ authors = Author.all
david = authors.find(authors(:david).id)
assert_equal 'David', david.name
@@ -493,14 +493,14 @@ class RelationTest < ActiveRecord::TestCase
end
def test_find_in_empty_array
- authors = Author.scoped.where(:id => [])
- assert_blank authors.all
+ authors = Author.all.where(:id => [])
+ assert_blank authors.to_a
end
def test_where_with_ar_object
author = Author.first
- authors = Author.scoped.where(:id => author)
- assert_equal 1, authors.all.length
+ authors = Author.all.where(:id => author)
+ assert_equal 1, authors.to_a.length
end
def test_find_with_list_of_ar
@@ -528,7 +528,7 @@ class RelationTest < ActiveRecord::TestCase
relation = relation.where(:name => david.name)
relation = relation.where(:name => 'Santiago')
relation = relation.where(:id => david.id)
- assert_equal [], relation.all
+ assert_equal [], relation.to_a
end
def test_multi_where_ands_queries
@@ -547,7 +547,7 @@ class RelationTest < ActiveRecord::TestCase
].inject(Author.unscoped) do |memo, param|
memo.where(param)
end
- assert_equal [], relation.all
+ assert_equal [], relation.to_a
end
def test_find_all_using_where_with_relation
@@ -556,7 +556,7 @@ class RelationTest < ActiveRecord::TestCase
# assert_queries(2) {
assert_queries(1) {
relation = Author.where(:id => Author.where(:id => david.id))
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
end
@@ -566,7 +566,7 @@ class RelationTest < ActiveRecord::TestCase
# assert_queries(2) {
assert_queries(1) {
relation = Minivan.where(:minivan_id => Minivan.where(:name => cool_first.name))
- assert_equal [cool_first], relation.all
+ assert_equal [cool_first], relation.to_a
}
end
@@ -577,7 +577,7 @@ class RelationTest < ActiveRecord::TestCase
assert_queries(1) {
relation = Author.where(:id => subquery)
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
assert_equal 0, subquery.select_values.size
@@ -587,7 +587,7 @@ class RelationTest < ActiveRecord::TestCase
david = authors(:david)
assert_queries(1) {
relation = Author.where(:id => Author.joins(:posts).where(:id => david.id))
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
end
@@ -596,7 +596,7 @@ class RelationTest < ActiveRecord::TestCase
david = authors(:david)
assert_queries(1) {
relation = Author.where(:name => Author.where(:id => david.id).select(:name))
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
end
@@ -615,7 +615,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_last
- authors = Author.scoped
+ authors = Author.all
assert_equal authors(:bob), authors.last
end
@@ -656,6 +656,14 @@ class RelationTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::ActiveRecordError) { Author.limit(10).delete_all }
end
+ def test_select_takes_a_variable_list_of_args
+ david = developers(:david)
+
+ developer = Developer.where(id: david.id).select(:name, :salary).first
+ assert_equal david.name, developer.name
+ assert_equal david.salary, developer.salary
+ end
+
def test_select_argument_error
assert_raises(ArgumentError) { Developer.select }
end
@@ -668,10 +676,29 @@ class RelationTest < ActiveRecord::TestCase
assert_equal [developers(:poor_jamis)], dev_with_count.to_a
end
+ def test_relation_merging_with_arel_equalities_keeps_last_equality
+ devs = Developer.where(Developer.arel_table[:salary].eq(80000)).merge(
+ Developer.where(Developer.arel_table[:salary].eq(9000))
+ )
+ assert_equal [developers(:poor_jamis)], devs.to_a
+ end
+
+ def test_relation_merging_with_arel_equalities_keeps_last_equality_with_non_attribute_left_hand
+ salary_attr = Developer.arel_table[:salary]
+ devs = Developer.where(
+ Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(80000)
+ ).merge(
+ Developer.where(
+ Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(9000)
+ )
+ )
+ assert_equal [developers(:poor_jamis)], devs.to_a
+ end
+
def test_relation_merging_with_eager_load
relations = []
- relations << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.scoped)
- relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.scoped)
+ relations << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.all)
+ relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.all)
relations.each do |posts|
post = posts.find { |p| p.id == 1 }
@@ -685,7 +712,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_relation_merging_with_preload
- [Post.scoped.merge(Post.preload(:author)), Post.preload(:author).merge(Post.scoped)].each do |posts|
+ [Post.all.merge(Post.preload(:author)), Post.preload(:author).merge(Post.all)].each do |posts|
assert_queries(2) { assert posts.first.author }
end
end
@@ -704,7 +731,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_count
- posts = Post.scoped
+ posts = Post.all
assert_equal 11, posts.count
assert_equal 11, posts.count(:all)
@@ -715,7 +742,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_count_with_distinct
- posts = Post.scoped
+ posts = Post.all
assert_equal 3, posts.count(:comments_count, :distinct => true)
assert_equal 11, posts.count(:comments_count, :distinct => false)
@@ -726,7 +753,7 @@ class RelationTest < ActiveRecord::TestCase
def test_count_explicit_columns
Post.update_all(:comments_count => nil)
- posts = Post.scoped
+ posts = Post.all
assert_equal [0], posts.select('comments_count').where('id is not null').group('id').order('id').count.values.uniq
assert_equal 0, posts.where('id is not null').select('comments_count').count
@@ -738,13 +765,13 @@ class RelationTest < ActiveRecord::TestCase
end
def test_multiple_selects
- post = Post.scoped.select('comments_count').select('title').order("id ASC").first
+ post = Post.all.select('comments_count').select('title').order("id ASC").first
assert_equal "Welcome to the weblog", post.title
assert_equal 2, post.comments_count
end
def test_size
- posts = Post.scoped
+ posts = Post.all
assert_queries(1) { assert_equal 11, posts.size }
assert ! posts.loaded?
@@ -790,7 +817,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_empty
- posts = Post.scoped
+ posts = Post.all
assert_queries(1) { assert_equal false, posts.empty? }
assert ! posts.loaded?
@@ -816,7 +843,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_any
- posts = Post.scoped
+ posts = Post.all
# This test was failing when run on its own (as opposed to running the entire suite).
# The second line in the assert_queries block was causing visit_Arel_Attributes_Attribute
@@ -838,7 +865,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_many
- posts = Post.scoped
+ posts = Post.all
assert_queries(2) do
assert posts.many? # Uses COUNT()
@@ -850,14 +877,14 @@ class RelationTest < ActiveRecord::TestCase
end
def test_many_with_limits
- posts = Post.scoped
+ posts = Post.all
assert posts.many?
assert ! posts.limit(1).many?
end
def test_build
- posts = Post.scoped
+ posts = Post.all
post = posts.new
assert_kind_of Post, post
@@ -872,7 +899,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_create
- birds = Bird.scoped
+ birds = Bird.all
sparrow = birds.create
assert_kind_of Bird, sparrow
@@ -884,7 +911,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_create_bang
- birds = Bird.scoped
+ birds = Bird.all
assert_raises(ActiveRecord::RecordInvalid) { birds.create! }
@@ -1026,24 +1053,24 @@ class RelationTest < ActiveRecord::TestCase
def test_except
relation = Post.where(:author_id => 1).order('id ASC').limit(1)
- assert_equal [posts(:welcome)], relation.all
+ assert_equal [posts(:welcome)], relation.to_a
author_posts = relation.except(:order, :limit)
- assert_equal Post.where(:author_id => 1).all, author_posts.all
+ assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a
all_posts = relation.except(:where, :order, :limit)
- assert_equal Post.all, all_posts.all
+ assert_equal Post.all, all_posts
end
def test_only
relation = Post.where(:author_id => 1).order('id ASC').limit(1)
- assert_equal [posts(:welcome)], relation.all
+ assert_equal [posts(:welcome)], relation.to_a
author_posts = relation.only(:where)
- assert_equal Post.where(:author_id => 1).all, author_posts.all
+ assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a
all_posts = relation.only(:limit)
- assert_equal Post.limit(1).all.first, all_posts.first
+ assert_equal Post.limit(1).to_a.first, all_posts.first
end
def test_anonymous_extension
@@ -1064,24 +1091,24 @@ class RelationTest < ActiveRecord::TestCase
end
def test_order_by_relation_attribute
- assert_equal Post.order(Post.arel_table[:title]).all, Post.order("title").all
+ assert_equal Post.order(Post.arel_table[:title]).to_a, Post.order("title").to_a
end
def test_default_scope_order_with_scope_order
- assert_equal 'zyke', CoolCar.order_using_new_style.limit(1).first.name
- assert_equal 'zyke', FastCar.order_using_new_style.limit(1).first.name
+ assert_equal 'honda', CoolCar.order_using_new_style.limit(1).first.name
+ assert_equal 'honda', FastCar.order_using_new_style.limit(1).first.name
end
def test_order_using_scoping
car1 = CoolCar.order('id DESC').scoping do
- CoolCar.scoped(:order => 'id asc').first
+ CoolCar.all.merge!(:order => 'id asc').first
end
- assert_equal 'zyke', car1.name
+ assert_equal 'honda', car1.name
car2 = FastCar.order('id DESC').scoping do
- FastCar.scoped(:order => 'id asc').first
+ FastCar.all.merge!(:order => 'id asc').first
end
- assert_equal 'zyke', car2.name
+ assert_equal 'honda', car2.name
end
def test_unscoped_block_style
@@ -1098,7 +1125,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_primary_key
- assert_equal "id", Post.scoped.primary_key
+ assert_equal "id", Post.all.primary_key
end
def test_eager_loading_with_conditions_on_joins
@@ -1122,6 +1149,10 @@ class RelationTest < ActiveRecord::TestCase
assert_equal authors(:david), Author.order('id DESC , name DESC').last
end
+ def test_update_all_with_blank_argument
+ assert_raises(ArgumentError) { Comment.update_all({}) }
+ end
+
def test_update_all_with_joins
comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id)
count = comments.count
@@ -1222,7 +1253,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_presence
- topics = Topic.scoped
+ topics = Topic.all
# the first query is triggered because there are no topics yet.
assert_queries(1) { assert topics.present? }
@@ -1256,7 +1287,7 @@ class RelationTest < ActiveRecord::TestCase
end
test "find_by returns nil if the record is missing" do
- assert_equal nil, Post.scoped.find_by("1 = 0")
+ assert_equal nil, Post.all.find_by("1 = 0")
end
test "find_by doesn't have implicit ordering" do
@@ -1281,12 +1312,12 @@ class RelationTest < ActiveRecord::TestCase
test "find_by! raises RecordNotFound if the record is missing" do
assert_raises(ActiveRecord::RecordNotFound) do
- Post.scoped.find_by!("1 = 0")
+ Post.all.find_by!("1 = 0")
end
end
test "loaded relations cannot be mutated by multi value methods" do
- relation = Post.scoped
+ relation = Post.all
relation.to_a
assert_raises(ActiveRecord::ImmutableRelation) do
@@ -1295,7 +1326,7 @@ class RelationTest < ActiveRecord::TestCase
end
test "loaded relations cannot be mutated by single value methods" do
- relation = Post.scoped
+ relation = Post.all
relation.to_a
assert_raises(ActiveRecord::ImmutableRelation) do
@@ -1304,7 +1335,7 @@ class RelationTest < ActiveRecord::TestCase
end
test "loaded relations cannot be mutated by merge!" do
- relation = Post.scoped
+ relation = Post.all
relation.to_a
assert_raises(ActiveRecord::ImmutableRelation) do
@@ -1332,4 +1363,22 @@ class RelationTest < ActiveRecord::TestCase
assert_equal expected, relation.inspect
end
end
+
+ test 'using a custom table affects the wheres' do
+ table_alias = Post.arel_table.alias('omg_posts')
+
+ relation = ActiveRecord::Relation.new Post, table_alias
+ relation.where!(:foo => "bar")
+
+ node = relation.arel.constraints.first.grep(Arel::Attributes::Attribute).first
+ assert_equal table_alias, node.relation
+ end
+
+ test '#load' do
+ relation = Post.all
+ assert_queries(1) do
+ assert_equal relation, relation.load
+ end
+ assert_no_queries { relation.to_a }
+ end
end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 01dd25a9df..92084d3eb6 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -182,7 +182,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_schema_dumps_index_columns_in_right_order
index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip
- assert_equal 'add_index "companies", ["firm_id", "type", "rating", "ruby_type"], :name => "company_index"', index_definition
+ assert_equal 'add_index "companies", ["firm_id", "type", "rating"], :name => "company_index"', index_definition
end
def test_schema_dumps_partial_indices
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
index ce167509c1..25b860878a 100644
--- a/activerecord/test/cases/serialization_test.rb
+++ b/activerecord/test/cases/serialization_test.rb
@@ -18,12 +18,6 @@ class SerializationTest < ActiveRecord::TestCase
}
end
- def test_serialized_init_with
- topic = Topic.allocate
- topic.init_with('attributes' => { 'content' => '--- foo' })
- assert_equal 'foo', topic.content
- end
-
def test_serialize_should_be_reversible
FORMATS.each do |format|
@serialized = Contact.new.send("to_#{format}")
@@ -51,11 +45,4 @@ class SerializationTest < ActiveRecord::TestCase
assert_equal @contact_attributes[:awesome], contact.awesome, "For #{format}"
end
end
-
- def test_serialized_attributes_are_class_level_settings
- assert_raise NoMethodError do
- topic = Topic.new
- topic.serialized_attributes = []
- end
- end
end
diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb
new file mode 100644
index 0000000000..f24ee54cd2
--- /dev/null
+++ b/activerecord/test/cases/serialized_attribute_test.rb
@@ -0,0 +1,205 @@
+require "cases/helper"
+require 'models/topic'
+require 'bcrypt'
+
+class SerializedAttributeTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ MyObject = Struct.new :attribute1, :attribute2
+
+ def teardown
+ super
+ Topic.serialize("content")
+ end
+
+ def test_list_of_serialized_attributes
+ assert_equal %w(content), Topic.serialized_attributes.keys
+ end
+
+ def test_serialized_attributes_are_class_level_settings
+ topic = Topic.new
+ assert_raise(NoMethodError) { topic.serialized_attributes = [] }
+ assert_deprecated { topic.serialized_attributes }
+ end
+
+ def test_serialized_attribute
+ Topic.serialize("content", MyObject)
+
+ myobj = MyObject.new('value1', 'value2')
+ topic = Topic.create("content" => myobj)
+ assert_equal(myobj, topic.content)
+
+ topic.reload
+ assert_equal(myobj, topic.content)
+ end
+
+ def test_serialized_attribute_init_with
+ topic = Topic.allocate
+ topic.init_with('attributes' => { 'content' => '--- foo' })
+ assert_equal 'foo', topic.content
+ end
+
+ def test_serialized_attribute_in_base_class
+ Topic.serialize("content", Hash)
+
+ hash = { 'content1' => 'value1', 'content2' => 'value2' }
+ important_topic = ImportantTopic.create("content" => hash)
+ assert_equal(hash, important_topic.content)
+
+ important_topic.reload
+ assert_equal(hash, important_topic.content)
+ end
+
+ # This test was added to fix GH #4004. Obviously the value returned
+ # is not really the value 'before type cast' so we should maybe think
+ # about changing that in the future.
+ def test_serialized_attribute_before_type_cast_returns_unserialized_value
+ Topic.serialize :content, Hash
+
+ t = Topic.new(:content => { :foo => :bar })
+ assert_equal({ :foo => :bar }, t.content_before_type_cast)
+ t.save!
+ t.reload
+ assert_equal({ :foo => :bar }, t.content_before_type_cast)
+ end
+
+ def test_serialized_attribute_calling_dup_method
+ Topic.serialize :content, JSON
+
+ t = Topic.new(:content => { :foo => :bar }).dup
+ assert_equal({ :foo => :bar }, t.content_before_type_cast)
+ end
+
+ def test_serialized_attribute_declared_in_subclass
+ hash = { 'important1' => 'value1', 'important2' => 'value2' }
+ important_topic = ImportantTopic.create("important" => hash)
+ assert_equal(hash, important_topic.important)
+
+ important_topic.reload
+ assert_equal(hash, important_topic.important)
+ assert_equal(hash, important_topic.read_attribute(:important))
+ end
+
+ def test_serialized_time_attribute
+ myobj = Time.local(2008,1,1,1,0)
+ topic = Topic.create("content" => myobj).reload
+ assert_equal(myobj, topic.content)
+ end
+
+ def test_serialized_string_attribute
+ myobj = "Yes"
+ topic = Topic.create("content" => myobj).reload
+ assert_equal(myobj, topic.content)
+ end
+
+ def test_nil_serialized_attribute_without_class_constraint
+ topic = Topic.new
+ assert_nil topic.content
+ end
+
+ def test_nil_not_serialized_without_class_constraint
+ assert Topic.new(:content => nil).save
+ assert_equal 1, Topic.where(:content => nil).count
+ end
+
+ def test_nil_not_serialized_with_class_constraint
+ Topic.serialize :content, Hash
+ assert Topic.new(:content => nil).save
+ assert_equal 1, Topic.where(:content => nil).count
+ end
+
+ def test_serialized_attribute_should_raise_exception_on_save_with_wrong_type
+ Topic.serialize(:content, Hash)
+ topic = Topic.new(:content => "string")
+ assert_raise(ActiveRecord::SerializationTypeMismatch) { topic.save }
+ end
+
+ def test_should_raise_exception_on_serialized_attribute_with_type_mismatch
+ myobj = MyObject.new('value1', 'value2')
+ topic = Topic.new(:content => myobj)
+ assert topic.save
+ Topic.serialize(:content, Hash)
+ assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content }
+ end
+
+ def test_serialized_attribute_with_class_constraint
+ settings = { "color" => "blue" }
+ Topic.serialize(:content, Hash)
+ topic = Topic.new(:content => settings)
+ assert topic.save
+ assert_equal(settings, Topic.find(topic.id).content)
+ end
+
+ def test_serialized_default_class
+ Topic.serialize(:content, Hash)
+ topic = Topic.new
+ assert_equal Hash, topic.content.class
+ assert_equal Hash, topic.read_attribute(:content).class
+ topic.content["beer"] = "MadridRb"
+ assert topic.save
+ topic.reload
+ assert_equal Hash, topic.content.class
+ assert_equal "MadridRb", topic.content["beer"]
+ end
+
+ def test_serialized_no_default_class_for_object
+ topic = Topic.new
+ assert_nil topic.content
+ end
+
+ def test_serialized_boolean_value_true
+ topic = Topic.new(:content => true)
+ assert topic.save
+ topic = topic.reload
+ assert_equal topic.content, true
+ end
+
+ def test_serialized_boolean_value_false
+ topic = Topic.new(:content => false)
+ assert topic.save
+ topic = topic.reload
+ assert_equal topic.content, false
+ end
+
+ def test_serialize_with_coder
+ coder = Class.new {
+ # Identity
+ def load(thing)
+ thing
+ end
+
+ # base 64
+ def dump(thing)
+ [thing].pack('m')
+ end
+ }.new
+
+ Topic.serialize(:content, coder)
+ s = 'hello world'
+ topic = Topic.new(:content => s)
+ assert topic.save
+ topic = topic.reload
+ assert_equal [s].pack('m'), topic.content
+ end
+
+ def test_serialize_with_bcrypt_coder
+ crypt_coder = Class.new {
+ def load(thing)
+ return unless thing
+ BCrypt::Password.new thing
+ end
+
+ def dump(thing)
+ BCrypt::Password.create(thing).to_s
+ end
+ }.new
+
+ Topic.serialize(:content, crypt_coder)
+ password = 'password'
+ topic = Topic.new(:content => password)
+ assert topic.save
+ topic = topic.reload
+ assert_kind_of BCrypt::Password, topic.content
+ assert_equal(true, topic.content == password, 'password should equal')
+ end
+end
diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb
deleted file mode 100644
index a3b8ab74d9..0000000000
--- a/activerecord/test/cases/session_store/session_test.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-require 'cases/helper'
-require 'action_dispatch'
-require 'active_record/session_store'
-
-module ActiveRecord
- class SessionStore
- class SessionTest < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
-
- attr_reader :session_klass
-
- def setup
- super
- ActiveRecord::Base.connection.schema_cache.clear!
- Session.drop_table! if Session.table_exists?
- @session_klass = Class.new(Session)
- end
-
- def test_data_column_name
- # default column name is 'data'
- assert_equal 'data', Session.data_column_name
- end
-
- def test_table_name
- assert_equal 'sessions', Session.table_name
- end
-
- def test_accessible_attributes
- assert Session.accessible_attributes.include?(:session_id)
- assert Session.accessible_attributes.include?(:data)
- assert Session.accessible_attributes.include?(:marshaled_data)
- end
-
- def test_create_table!
- assert !Session.table_exists?
- Session.create_table!
- assert Session.table_exists?
- Session.drop_table!
- assert !Session.table_exists?
- end
-
- def test_find_by_sess_id_compat
- Session.reset_column_information
- klass = Class.new(Session) do
- def self.session_id_column
- 'sessid'
- end
- end
- klass.create_table!
-
- assert klass.columns_hash['sessid'], 'sessid column exists'
- session = klass.new(:data => 'hello')
- session.sessid = "100"
- session.save!
-
- found = klass.find_by_session_id("100")
- assert_equal session, found
- assert_equal session.sessid, found.session_id
- ensure
- klass.drop_table!
- Session.reset_column_information
- end
-
- def test_find_by_session_id
- Session.create_table!
- session_id = "10"
- s = session_klass.create!(:data => 'world', :session_id => session_id)
- t = session_klass.find_by_session_id(session_id)
- assert_equal s, t
- assert_equal s.data, t.data
- Session.drop_table!
- end
-
- def test_loaded?
- Session.create_table!
- s = Session.new
- assert !s.loaded?, 'session is not loaded'
- end
- end
- end
-end
diff --git a/activerecord/test/cases/session_store/sql_bypass_test.rb b/activerecord/test/cases/session_store/sql_bypass_test.rb
deleted file mode 100644
index 6749d4ce98..0000000000
--- a/activerecord/test/cases/session_store/sql_bypass_test.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-require 'cases/helper'
-require 'action_dispatch'
-require 'active_record/session_store'
-
-module ActiveRecord
- class SessionStore
- class SqlBypassTest < ActiveRecord::TestCase
- def setup
- super
- Session.drop_table! if Session.table_exists?
- end
-
- def test_create_table
- assert !Session.table_exists?
- SqlBypass.create_table!
- assert Session.table_exists?
- SqlBypass.drop_table!
- assert !Session.table_exists?
- end
-
- def test_new_record?
- s = SqlBypass.new :data => 'foo', :session_id => 10
- assert s.new_record?, 'this is a new record!'
- end
-
- def test_persisted?
- s = SqlBypass.new :data => 'foo', :session_id => 10
- assert !s.persisted?, 'this is a new record!'
- end
-
- def test_not_loaded?
- s = SqlBypass.new({})
- assert !s.loaded?, 'it is not loaded'
- end
-
- def test_loaded?
- s = SqlBypass.new :data => 'hello'
- assert s.loaded?, 'it is loaded'
- end
-
- def test_save
- SqlBypass.create_table! unless Session.table_exists?
- session_id = 20
- s = SqlBypass.new :data => 'hello', :session_id => session_id
- s.save
- t = SqlBypass.find_by_session_id session_id
- assert_equal s.session_id, t.session_id
- assert_equal s.data, t.data
- end
-
- def test_destroy
- SqlBypass.create_table! unless Session.table_exists?
- session_id = 20
- s = SqlBypass.new :data => 'hello', :session_id => session_id
- s.save
- s.destroy
- assert_nil SqlBypass.find_by_session_id session_id
- end
- end
- end
-end
diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb
index 3e60b62fd5..fb0d116c08 100644
--- a/activerecord/test/cases/store_test.rb
+++ b/activerecord/test/cases/store_test.rb
@@ -122,9 +122,8 @@ class StoreTest < ActiveRecord::TestCase
end
test "stores_attributes are class level settings" do
- assert_raise NoMethodError do
- @john.stored_attributes = {}
- end
+ assert_raise(NoMethodError) { @john.stored_attributes = Hash.new }
+ assert_raise(NoMethodError) { @john.stored_attributes }
end
end
diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb
index 8c96a8aaa1..4f3489b7a5 100644
--- a/activerecord/test/cases/tasks/database_tasks_test.rb
+++ b/activerecord/test/cases/tasks/database_tasks_test.rb
@@ -16,6 +16,22 @@ module ActiveRecord
:postgresql => :postgresql_tasks,
:sqlite3 => :sqlite_tasks
}
+
+ class DatabaseTasksRegisterTask < ActiveRecord::TestCase
+ def test_register_task
+ klazz = Class.new do
+ def initialize(*arguments); end
+ def structure_dump(filename); end
+ end
+ instance = klazz.new
+
+ klazz.stubs(:new).returns instance
+ instance.expects(:structure_dump).with("awesome-file.sql")
+
+ ActiveRecord::Tasks::DatabaseTasks.register_task(/foo/, klazz)
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => :foo}, "awesome-file.sql")
+ end
+ end
class DatabaseTasksCreateTest < ActiveRecord::TestCase
include DatabaseTasksSetupper
diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb
index 9a0eb423bd..b49561d858 100644
--- a/activerecord/test/cases/tasks/mysql_rake_test.rb
+++ b/activerecord/test/cases/tasks/mysql_rake_test.rb
@@ -1,5 +1,4 @@
require 'cases/helper'
-require 'mysql'
module ActiveRecord
class MysqlDBCreateTest < ActiveRecord::TestCase
@@ -46,6 +45,10 @@ module ActiveRecord
class MysqlDBCreateAsRootTest < ActiveRecord::TestCase
def setup
+ unless current_adapter?(:MysqlAdapter)
+ return skip("only tested on mysql")
+ end
+
@connection = stub(:create_database => true, :execute => true)
@error = Mysql::Error.new "Invalid permissions"
@configuration = {
@@ -64,6 +67,7 @@ module ActiveRecord
end
def test_root_password_is_requested
+ skip "only if mysql is available" unless defined?(::Mysql)
$stdin.expects(:gets).returns("secret\n")
ActiveRecord::Tasks::DatabaseTasks.create @configuration
diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb
index 06a1d0ffc2..7209c0f14d 100644
--- a/activerecord/test/cases/tasks/sqlite_rake_test.rb
+++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb
@@ -162,8 +162,8 @@ module ActiveRecord
assert File.exists?(dbfile)
assert File.exists?(filename)
ensure
- FileUtils.rm(filename)
- FileUtils.rm(dbfile)
+ FileUtils.rm_f(filename)
+ FileUtils.rm_f(dbfile)
end
end
@@ -184,8 +184,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, '/rails/root'
assert File.exists?(dbfile)
ensure
- FileUtils.rm(filename)
- FileUtils.rm(dbfile)
+ FileUtils.rm_f(filename)
+ FileUtils.rm_f(dbfile)
end
end
end
diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb
index 94a13d386c..f3f7054794 100644
--- a/activerecord/test/cases/test_case.rb
+++ b/activerecord/test/cases/test_case.rb
@@ -1,4 +1,3 @@
-require 'active_support/deprecation'
ActiveSupport::Deprecation.silence do
require 'active_record/test_case'
end
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 7df6993b30..bb034848e1 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -11,7 +11,7 @@ class TimestampTest < ActiveRecord::TestCase
def setup
@developer = Developer.first
- @developer.update_column(:updated_at, Time.now.prev_month)
+ @developer.update_columns(updated_at: Time.now.prev_month)
@previously_updated_at = @developer.updated_at
end
@@ -114,9 +114,12 @@ class TimestampTest < ActiveRecord::TestCase
end
def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute
- Pet.belongs_to :owner, :touch => :happy_at
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Pet'; end
+ belongs_to :owner, :touch => :happy_at
+ end
- pet = Pet.first
+ pet = klass.first
owner = pet.owner
previously_owner_happy_at = owner.happy_at
@@ -124,42 +127,41 @@ class TimestampTest < ActiveRecord::TestCase
pet.save
assert_not_equal previously_owner_happy_at, pet.owner.happy_at
- ensure
- Pet.belongs_to :owner, :touch => true
end
def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent
- Pet.belongs_to :owner, :counter_cache => :use_count, :touch => true
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Pet'; end
+ belongs_to :owner, :counter_cache => :use_count, :touch => true
+ end
- pet = Pet.first
+ pet = klass.first
owner = pet.owner
- owner.update_column(:happy_at, 3.days.ago)
+ owner.update_columns(happy_at: 3.days.ago)
previously_owner_updated_at = owner.updated_at
pet.name = "I'm a parrot"
pet.save
assert_not_equal previously_owner_updated_at, pet.owner.updated_at
- ensure
- Pet.belongs_to :owner, :touch => true
end
def test_touching_a_record_touches_parent_record_and_grandparent_record
- Toy.belongs_to :pet, :touch => true
- Pet.belongs_to :owner, :touch => true
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ belongs_to :pet, :touch => true
+ end
- toy = Toy.first
+ toy = klass.first
pet = toy.pet
owner = pet.owner
time = 3.days.ago
- owner.update_column(:updated_at, time)
+ owner.update_columns(updated_at: time)
toy.touch
owner.reload
assert_not_equal time, owner.updated_at
- ensure
- Toy.belongs_to :pet
end
def test_timestamp_attributes_for_create
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index a9ccd00fac..0d0de455b3 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -91,18 +91,14 @@ class TransactionTest < ActiveRecord::TestCase
end
def test_raising_exception_in_callback_rollbacks_in_save
- add_exception_raising_after_save_callback_to_topic
-
- begin
- @first.approved = true
- @first.save
- flunk
- rescue => e
- assert_equal "Make the transaction rollback", e.message
- assert !Topic.find(1).approved?
- ensure
- remove_exception_raising_after_save_callback_to_topic
+ def @first.after_save_for_transaction
+ raise 'Make the transaction rollback'
end
+
+ @first.approved = true
+ e = assert_raises(RuntimeError) { @first.save }
+ assert_equal "Make the transaction rollback", e.message
+ assert !Topic.find(1).approved?
end
def test_update_attributes_should_rollback_on_failure
@@ -125,85 +121,85 @@ class TransactionTest < ActiveRecord::TestCase
end
def test_cancellation_from_before_destroy_rollbacks_in_destroy
- add_cancelling_before_destroy_with_db_side_effect_to_topic
- begin
- nbooks_before_destroy = Book.count
- status = @first.destroy
- assert !status
- assert_nothing_raised(ActiveRecord::RecordNotFound) { @first.reload }
- assert_equal nbooks_before_destroy, Book.count
- ensure
- remove_cancelling_before_destroy_with_db_side_effect_to_topic
- end
+ add_cancelling_before_destroy_with_db_side_effect_to_topic @first
+ nbooks_before_destroy = Book.count
+ status = @first.destroy
+ assert !status
+ @first.reload
+ assert_equal nbooks_before_destroy, Book.count
end
- def test_cancellation_from_before_filters_rollbacks_in_save
- %w(validation save).each do |filter|
- send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic")
- begin
- nbooks_before_save = Book.count
- original_author_name = @first.author_name
- @first.author_name += '_this_should_not_end_up_in_the_db'
- status = @first.save
- assert !status
- assert_equal original_author_name, @first.reload.author_name
- assert_equal nbooks_before_save, Book.count
- ensure
- send("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic")
- end
+ %w(validation save).each do |filter|
+ define_method("test_cancellation_from_before_filters_rollbacks_in_#{filter}") do
+ send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic", @first)
+ nbooks_before_save = Book.count
+ original_author_name = @first.author_name
+ @first.author_name += '_this_should_not_end_up_in_the_db'
+ status = @first.save
+ assert !status
+ assert_equal original_author_name, @first.reload.author_name
+ assert_equal nbooks_before_save, Book.count
end
- end
- def test_cancellation_from_before_filters_rollbacks_in_save!
- %w(validation save).each do |filter|
- send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic")
+ define_method("test_cancellation_from_before_filters_rollbacks_in_#{filter}!") do
+ send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic", @first)
+ nbooks_before_save = Book.count
+ original_author_name = @first.author_name
+ @first.author_name += '_this_should_not_end_up_in_the_db'
+
begin
- nbooks_before_save = Book.count
- original_author_name = @first.author_name
- @first.author_name += '_this_should_not_end_up_in_the_db'
@first.save!
- flunk
- rescue
- assert_equal original_author_name, @first.reload.author_name
- assert_equal nbooks_before_save, Book.count
- ensure
- send("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic")
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved
end
+
+ assert_equal original_author_name, @first.reload.author_name
+ assert_equal nbooks_before_save, Book.count
end
end
def test_callback_rollback_in_create
- new_topic = Topic.new(
- :title => "A new topic",
- :author_name => "Ben",
- :author_email_address => "ben@example.com",
- :written_on => "2003-07-16t15:28:11.2233+01:00",
- :last_read => "2004-04-15",
- :bonus_time => "2005-01-30t15:28:00.00+01:00",
- :content => "Have a nice day",
- :approved => false)
+ topic = Class.new(Topic) {
+ def after_create_for_transaction
+ raise 'Make the transaction rollback'
+ end
+ }
+
+ new_topic = topic.new(:title => "A new topic",
+ :author_name => "Ben",
+ :author_email_address => "ben@example.com",
+ :written_on => "2003-07-16t15:28:11.2233+01:00",
+ :last_read => "2004-04-15",
+ :bonus_time => "2005-01-30t15:28:00.00+01:00",
+ :content => "Have a nice day",
+ :approved => false)
+
new_record_snapshot = !new_topic.persisted?
id_present = new_topic.has_attribute?(Topic.primary_key)
id_snapshot = new_topic.id
# Make sure the second save gets the after_create callback called.
2.times do
- begin
- add_exception_raising_after_create_callback_to_topic
- new_topic.approved = true
- new_topic.save
- flunk
- rescue => e
- assert_equal "Make the transaction rollback", e.message
- assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
- assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
- assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
- ensure
- remove_exception_raising_after_create_callback_to_topic
- end
+ new_topic.approved = true
+ e = assert_raises(RuntimeError) { new_topic.save }
+ assert_equal "Make the transaction rollback", e.message
+ assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
+ assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
+ assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
end
end
+ def test_callback_rollback_in_create_with_record_invalid_exception
+ topic = Class.new(Topic) {
+ def after_create_for_transaction
+ raise ActiveRecord::RecordInvalid.new(Author.new)
+ end
+ }
+
+ new_topic = topic.create(:title => "A new topic")
+ assert !new_topic.persisted?, "The topic should not be persisted"
+ assert_nil new_topic.id, "The topic should not have an ID"
+ end
+
def test_nested_explicit_transactions
Topic.transaction do
Topic.transaction do
@@ -461,62 +457,16 @@ class TransactionTest < ActiveRecord::TestCase
end
private
- def define_callback_method(callback_method)
- define_method(callback_method) do
- self.history << [callback_method, :method]
- end
- end
- def add_exception_raising_after_save_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method(:after_save_for_transaction)
- def after_save_for_transaction
- raise 'Make the transaction rollback'
- end
- eoruby
- end
-
- def remove_exception_raising_after_save_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :after_save_for_transaction
- def after_save_for_transaction; end
- eoruby
- end
-
- def add_exception_raising_after_create_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method(:after_create_for_transaction)
- def after_create_for_transaction
- raise 'Make the transaction rollback'
- end
- eoruby
- end
-
- def remove_exception_raising_after_create_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :after_create_for_transaction
- def after_create_for_transaction; end
- eoruby
- end
-
- %w(validation save destroy).each do |filter|
- define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :before_#{filter}_for_transaction
- def before_#{filter}_for_transaction
- Book.create
- false
- end
- eoruby
- end
-
- define_method("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic") do
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :before_#{filter}_for_transaction
- def before_#{filter}_for_transaction; end
- eoruby
+ %w(validation save destroy).each do |filter|
+ define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic|
+ meta = class << topic; self; end
+ meta.send("define_method", "before_#{filter}_for_transaction") do
+ Book.create
+ false
end
end
+ end
end
class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/validations/presence_validation_test.rb b/activerecord/test/cases/validations/presence_validation_test.rb
new file mode 100644
index 0000000000..cd9175f454
--- /dev/null
+++ b/activerecord/test/cases/validations/presence_validation_test.rb
@@ -0,0 +1,44 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/man'
+require 'models/face'
+require 'models/interest'
+
+class PresenceValidationTest < ActiveRecord::TestCase
+ class Boy < Man; end
+
+ repair_validations(Boy)
+
+ def test_validates_presence_of_non_association
+ Boy.validates_presence_of(:name)
+ b = Boy.new
+ assert b.invalid?
+
+ b.name = "Alex"
+ assert b.valid?
+ end
+
+ def test_validates_presence_of_has_one_marked_for_destruction
+ Boy.validates_presence_of(:face)
+ b = Boy.new
+ f = Face.new
+ b.face = f
+ assert b.valid?
+
+ f.mark_for_destruction
+ assert b.invalid?
+ end
+
+ def test_validates_presence_of_has_many_marked_for_destruction
+ Boy.validates_presence_of(:interests)
+ b = Boy.new
+ b.interests << [i1 = Interest.new, i2 = Interest.new]
+ assert b.valid?
+
+ i1.mark_for_destruction
+ assert b.valid?
+
+ i2.mark_for_destruction
+ assert b.invalid?
+ end
+end
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index c173ee9a15..46212e49b6 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -22,6 +22,14 @@ end
class Thaumaturgist < IneptWizard
end
+class ReplyTitle; end
+
+class ReplyWithTitleObject < Reply
+ validates_uniqueness_of :content, :scope => :title
+
+ def title; ReplyTitle.new; end
+end
+
class UniquenessValidationTest < ActiveRecord::TestCase
fixtures :topics, 'warehouse-things', :developers
@@ -104,6 +112,14 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert !r2.valid?, "Saving r2 first time"
end
+ def test_validate_uniqueness_with_composed_attribute_scope
+ r1 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+ end
+
def test_validate_uniqueness_with_object_arg
Reply.validates_uniqueness_of(:topic)
@@ -189,7 +205,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert t_utf8.save, "Should save t_utf8 as unique"
# If database hasn't UTF-8 character set, this test fails
- if Topic.scoped(:select => 'LOWER(title) AS title').find(t_utf8).title == "я тоже уникальный!"
+ if Topic.all.merge!(:select => 'LOWER(title) AS title').find(t_utf8).title == "я тоже уникальный!"
t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!")
assert !t2_utf8.valid?, "Shouldn't be valid"
assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique"
diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml
index f450efd839..479b8c050d 100644
--- a/activerecord/test/config.example.yml
+++ b/activerecord/test/config.example.yml
@@ -1,5 +1,7 @@
default_connection: <%= defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' %>
+with_manual_interventions: false
+
connections:
jdbcderby:
arunit: activerecord_unittest
diff --git a/activerecord/test/fixtures/companies.yml b/activerecord/test/fixtures/companies.yml
index a982d3921d..0766e92027 100644
--- a/activerecord/test/fixtures/companies.yml
+++ b/activerecord/test/fixtures/companies.yml
@@ -4,14 +4,12 @@ first_client:
firm_id: 1
client_of: 2
name: Summit
- ruby_type: Client
firm_name: 37signals
first_firm:
id: 1
type: Firm
name: 37signals
- ruby_type: Firm
firm_id: 1
second_client:
@@ -20,13 +18,11 @@ second_client:
firm_id: 1
client_of: 1
name: Microsoft
- ruby_type: Client
another_firm:
id: 4
type: Firm
name: Flamboyant Software
- ruby_type: Firm
another_client:
id: 5
@@ -34,7 +30,6 @@ another_client:
firm_id: 4
client_of: 4
name: Ex Nihilo
- ruby_type: Client
a_third_client:
id: 10
@@ -42,7 +37,6 @@ a_third_client:
firm_id: 4
client_of: 4
name: Ex Nihilo Part Deux
- ruby_type: Client
rails_core:
id: 6
diff --git a/activerecord/test/fixtures/friendships.yml b/activerecord/test/fixtures/friendships.yml
new file mode 100644
index 0000000000..1ee09175bf
--- /dev/null
+++ b/activerecord/test/fixtures/friendships.yml
@@ -0,0 +1,4 @@
+Connection 1:
+ id: 1
+ person_id: 1
+ friend_id: 2 \ No newline at end of file
diff --git a/activerecord/test/fixtures/people.yml b/activerecord/test/fixtures/people.yml
index 123673a2af..e640a38f1f 100644
--- a/activerecord/test/fixtures/people.yml
+++ b/activerecord/test/fixtures/people.yml
@@ -4,15 +4,18 @@ michael:
primary_contact_id: 2
number1_fan_id: 3
gender: M
+ followers_count: 1
david:
id: 2
first_name: David
primary_contact_id: 3
number1_fan_id: 1
gender: M
+ followers_count: 1
susan:
id: 3
first_name: Susan
primary_contact_id: 2
number1_fan_id: 1
gender: F
+ followers_count: 1
diff --git a/activerecord/test/fixtures/topics.yml b/activerecord/test/fixtures/topics.yml
index 93f48aedc4..2b042bd135 100644
--- a/activerecord/test/fixtures/topics.yml
+++ b/activerecord/test/fixtures/topics.yml
@@ -25,7 +25,7 @@ third:
id: 3
title: The Third Topic of the day
author_name: Carl
- written_on: 2005-07-15t15:28:00.0099+01:00
+ written_on: 2012-08-12t20:24:22.129346+00:00
content: I'm a troll
approved: true
replies_count: 1
diff --git a/activerecord/test/fixtures/vegetables.yml b/activerecord/test/fixtures/vegetables.yml
new file mode 100644
index 0000000000..b9afbfbb05
--- /dev/null
+++ b/activerecord/test/fixtures/vegetables.yml
@@ -0,0 +1,20 @@
+first_cucumber:
+ id: 1
+ custom_type: Cucumber
+ name: 'my cucumber'
+
+first_cabbage:
+ id: 2
+ custom_type: Cabbage
+ name: 'my cabbage'
+
+second_cabbage:
+ id: 3
+ custom_type: Cabbage
+ name: 'his cabbage'
+
+red_cabbage:
+ id: 4
+ custom_type: RedCabbage
+ name: 'red cabbage'
+ seller_id: 3 \ No newline at end of file
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index 14444a0092..77f4a2ec87 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -1,12 +1,12 @@
class Author < ActiveRecord::Base
has_many :posts
has_many :very_special_comments, :through => :posts
- has_many :posts_with_comments, :include => :comments, :class_name => "Post"
- has_many :popular_grouped_posts, :include => :comments, :class_name => "Post", :group => "type", :having => "SUM(comments_count) > 1", :select => "type"
- has_many :posts_with_comments_sorted_by_comment_id, :include => :comments, :class_name => "Post", :order => 'comments.id'
- has_many :posts_sorted_by_id_limited, :class_name => "Post", :order => 'posts.id', :limit => 1
- has_many :posts_with_categories, :include => :categories, :class_name => "Post"
- has_many :posts_with_comments_and_categories, :include => [ :comments, :categories ], :order => "posts.id", :class_name => "Post"
+ has_many :posts_with_comments, -> { includes(:comments) }, :class_name => "Post"
+ has_many :popular_grouped_posts, -> { includes(:comments).group("type").having("SUM(comments_count) > 1").select("type") }, :class_name => "Post"
+ has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order('comments.id') }, :class_name => "Post"
+ has_many :posts_sorted_by_id_limited, -> { order('posts.id').limit(1) }, :class_name => "Post"
+ has_many :posts_with_categories, -> { includes(:categories) }, :class_name => "Post"
+ has_many :posts_with_comments_and_categories, -> { includes(:comments, :categories).order("posts.id") }, :class_name => "Post"
has_many :posts_containing_the_letter_a, :class_name => "Post"
has_many :posts_with_extension, :class_name => "Post" do #, :extend => ProxyTestExtension
def testing_proxy_owner
@@ -19,28 +19,28 @@ class Author < ActiveRecord::Base
proxy_target
end
end
- has_one :post_about_thinking, :class_name => 'Post', :conditions => "posts.title like '%thinking%'"
- has_one :post_about_thinking_with_last_comment, :class_name => 'Post', :conditions => "posts.title like '%thinking%'", :include => :last_comment
+ has_one :post_about_thinking, -> { where("posts.title like '%thinking%'") }, :class_name => 'Post'
+ has_one :post_about_thinking_with_last_comment, -> { where("posts.title like '%thinking%'").includes(:last_comment) }, :class_name => 'Post'
has_many :comments, :through => :posts
has_many :comments_containing_the_letter_e, :through => :posts, :source => :comments
- has_many :comments_with_order_and_conditions, :through => :posts, :source => :comments, :order => 'comments.body', :conditions => "comments.body like 'Thank%'"
- has_many :comments_with_include, :through => :posts, :source => :comments, :include => :post
+ has_many :comments_with_order_and_conditions, -> { order('comments.body').where("comments.body like 'Thank%'") }, :through => :posts, :source => :comments
+ has_many :comments_with_include, -> { includes(:post) }, :through => :posts, :source => :comments
has_many :first_posts
- has_many :comments_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc'
+ has_many :comments_on_first_posts, -> { order('posts.id desc, comments.id asc') }, :through => :first_posts, :source => :comments
has_one :first_post
- has_one :comment_on_first_post, :through => :first_post, :source => :comments, :order => 'posts.id desc, comments.id asc'
+ has_one :comment_on_first_post, -> { order('posts.id desc, comments.id asc') }, :through => :first_post, :source => :comments
- has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }, :dependent => :delete_all
- has_many :welcome_posts, :class_name => 'Post', :conditions => { :title => 'Welcome to the weblog' }
+ has_many :thinking_posts, -> { where(:title => 'So I was thinking') }, :dependent => :delete_all, :class_name => 'Post'
+ has_many :welcome_posts, -> { where(:title => 'Welcome to the weblog') }, :class_name => 'Post'
- has_many :comments_desc, :through => :posts, :source => :comments, :order => 'comments.id DESC'
- has_many :limited_comments, :through => :posts, :source => :comments, :limit => 1
+ has_many :comments_desc, -> { order('comments.id DESC') }, :through => :posts, :source => :comments
+ has_many :limited_comments, -> { limit(1) }, :through => :posts, :source => :comments
has_many :funky_comments, :through => :posts, :source => :comments
- has_many :ordered_uniq_comments, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id'
- has_many :ordered_uniq_comments_desc, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id DESC'
- has_many :readonly_comments, :through => :posts, :source => :comments, :readonly => true
+ has_many :ordered_uniq_comments, -> { uniq.order('comments.id') }, :through => :posts, :source => :comments
+ has_many :ordered_uniq_comments_desc, -> { uniq.order('comments.id DESC') }, :through => :posts, :source => :comments
+ has_many :readonly_comments, -> { readonly }, :through => :posts, :source => :comments
has_many :special_posts
has_many :special_post_comments, :through => :special_posts, :source => :comments
@@ -48,16 +48,15 @@ class Author < ActiveRecord::Base
has_many :sti_posts, :class_name => 'StiPost'
has_many :sti_post_comments, :through => :sti_posts, :source => :comments
- has_many :special_nonexistant_posts, :class_name => "SpecialPost", :conditions => "posts.body = 'nonexistant'"
- has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => { 'comments.post_id' => 0 }
+ has_many :special_nonexistant_posts, -> { where("posts.body = 'nonexistant'") }, :class_name => "SpecialPost"
+ has_many :special_nonexistant_post_comments, -> { where('comments.post_id' => 0) }, :through => :special_nonexistant_posts, :source => :comments
has_many :nonexistant_comments, :through => :posts
- has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'"
+ has_many :hello_posts, -> { where "posts.body = 'hello'" }, :class_name => "Post"
has_many :hello_post_comments, :through => :hello_posts, :source => :comments
- has_many :posts_with_no_comments, :class_name => 'Post', :conditions => { 'comments.id' => nil }, :include => :comments
+ has_many :posts_with_no_comments, -> { where('comments.id' => nil).includes(:comments) }, :class_name => 'Post'
- has_many :hello_posts_with_hash_conditions, :class_name => "Post",
-:conditions => {:body => 'hello'}
+ has_many :hello_posts_with_hash_conditions, -> { where(:body => 'hello') }, :class_name => "Post"
has_many :hello_post_comments_with_hash_conditions, :through =>
:hello_posts_with_hash_conditions, :source => :comments
@@ -84,29 +83,31 @@ class Author < ActiveRecord::Base
has_many :special_categories, :through => :special_categorizations, :source => :category
has_one :special_category, :through => :special_categorizations, :source => :category
- has_many :categories_like_general, :through => :categorizations, :source => :category, :class_name => 'Category', :conditions => { :name => 'General' }
+ has_many :categories_like_general, -> { where(:name => 'General') }, :through => :categorizations, :source => :category, :class_name => 'Category'
has_many :categorized_posts, :through => :categorizations, :source => :post
- has_many :unique_categorized_posts, :through => :categorizations, :source => :post, :uniq => true
+ has_many :unique_categorized_posts, -> { uniq }, :through => :categorizations, :source => :post
has_many :nothings, :through => :kateggorisatons, :class_name => 'Category'
has_many :author_favorites
- has_many :favorite_authors, :through => :author_favorites, :order => 'name'
+ has_many :favorite_authors, -> { order('name') }, :through => :author_favorites
- has_many :tagging, :through => :posts
has_many :taggings, :through => :posts
+ has_many :taggings_2, :through => :posts, :source => :tagging
has_many :tags, :through => :posts
- has_many :similar_posts, :through => :tags, :source => :tagged_posts, :uniq => true
- has_many :distinct_tags, :through => :posts, :source => :tags, :select => "DISTINCT tags.*", :order => "tags.name"
has_many :post_categories, :through => :posts, :source => :categories
has_many :tagging_tags, :through => :taggings, :source => :tag
+
+ has_many :similar_posts, -> { uniq }, :through => :tags, :source => :tagged_posts
+ has_many :distinct_tags, -> { select("DISTINCT tags.*").order("tags.name") }, :through => :posts, :source => :tags
+
has_many :tags_with_primary_key, :through => :posts
has_many :books
has_many :subscriptions, :through => :books
- has_many :subscribers, :through => :subscriptions, :order => "subscribers.nick" # through has_many :through (on through reflection)
- has_many :distinct_subscribers, :through => :subscriptions, :source => :subscriber, :select => "DISTINCT subscribers.*", :order => "subscribers.nick"
+ has_many :subscribers, -> { order("subscribers.nick") }, :through => :subscriptions
+ has_many :distinct_subscribers, -> { select("DISTINCT subscribers.*").order("subscribers.nick") }, :through => :subscriptions, :source => :subscriber
has_one :essay, :primary_key => :name, :as => :writer
has_one :essay_category, :through => :essay, :source => :category
@@ -130,12 +131,11 @@ class Author < ActiveRecord::Base
has_many :category_post_comments, :through => :categories, :source => :post_comments
- has_many :misc_posts, :class_name => 'Post',
- :conditions => { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }
+ has_many :misc_posts, -> { where(:posts => { :title => ['misc post by bob', 'misc post by mary'] }) }, :class_name => 'Post'
has_many :misc_post_first_blue_tags, :through => :misc_posts, :source => :first_blue_tags
- has_many :misc_post_first_blue_tags_2, :through => :posts, :source => :first_blue_tags_2,
- :conditions => { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }
+ has_many :misc_post_first_blue_tags_2, -> { where(:posts => { :title => ['misc post by bob', 'misc post by mary'] }) },
+ :through => :posts, :source => :first_blue_tags_2
has_many :posts_with_default_include, :class_name => 'PostWithDefaultInclude'
has_many :comments_on_posts_with_default_include, :through => :posts_with_default_include, :source => :comments
diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb
index d27d0af77c..ce81a37966 100644
--- a/activerecord/test/models/book.rb
+++ b/activerecord/test/models/book.rb
@@ -2,7 +2,7 @@ class Book < ActiveRecord::Base
has_many :authors
has_many :citations, :foreign_key => 'book1_id'
- has_many :references, :through => :citations, :source => :reference_of, :uniq => true
+ has_many :references, -> { uniq }, :through => :citations, :source => :reference_of
has_many :subscriptions
has_many :subscribers, :through => :subscriptions
diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb
index 640e57555d..0dc2fdd8ae 100644
--- a/activerecord/test/models/bulb.rb
+++ b/activerecord/test/models/bulb.rb
@@ -8,7 +8,7 @@ class Bulb < ActiveRecord::Base
after_initialize :record_scope_after_initialize
def record_scope_after_initialize
- @scope_after_initialize = self.class.scoped
+ @scope_after_initialize = self.class.all
end
after_initialize :record_attributes_after_initialize
diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb
index b4bc0ad5fa..ac42f444e1 100644
--- a/activerecord/test/models/car.rb
+++ b/activerecord/test/models/car.rb
@@ -1,11 +1,11 @@
class Car < ActiveRecord::Base
has_many :bulbs
- has_many :foo_bulbs, :class_name => "Bulb", :conditions => { :name => 'foo' }
- has_many :frickinawesome_bulbs, :class_name => "Bulb", :conditions => { :frickinawesome => true }
+ has_many :foo_bulbs, -> { where(:name => 'foo') }, :class_name => "Bulb"
+ has_many :frickinawesome_bulbs, -> { where :frickinawesome => true }, :class_name => "Bulb"
has_one :bulb
- has_one :frickinawesome_bulb, :class_name => "Bulb", :conditions => { :frickinawesome => true }
+ has_one :frickinawesome_bulb, -> { where :frickinawesome => true }, :class_name => "Bulb"
has_many :tyres
has_many :engines, :dependent => :destroy
diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb
index ab3139680c..f8c8ebb70c 100644
--- a/activerecord/test/models/category.rb
+++ b/activerecord/test/models/category.rb
@@ -2,20 +2,20 @@ class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
has_and_belongs_to_many :special_posts, :class_name => "Post"
has_and_belongs_to_many :other_posts, :class_name => "Post"
- has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, :class_name => "Post", :include => :authors, :order => "authors.id"
+ has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, -> { includes(:authors).order("authors.id") }, :class_name => "Post"
- has_and_belongs_to_many(:select_testing_posts,
+ has_and_belongs_to_many :select_testing_posts,
+ -> { select 'posts.*, 1 as correctness_marker' },
:class_name => 'Post',
:foreign_key => 'category_id',
- :association_foreign_key => 'post_id',
- :select => 'posts.*, 1 as correctness_marker')
+ :association_foreign_key => 'post_id'
has_and_belongs_to_many :post_with_conditions,
- :class_name => 'Post',
- :conditions => { :title => 'Yet Another Testing Title' }
+ -> { where :title => 'Yet Another Testing Title' },
+ :class_name => 'Post'
- has_and_belongs_to_many :popular_grouped_posts, :class_name => "Post", :group => "posts.type", :having => "sum(comments.post_id) > 2", :include => :comments
- has_and_belongs_to_many :posts_grouped_by_title, :class_name => "Post", :group => "title", :select => "title"
+ has_and_belongs_to_many :popular_grouped_posts, -> { group("posts.type").having("sum(comments.post_id) > 2").includes(:comments) }, :class_name => "Post"
+ has_and_belongs_to_many :posts_grouped_by_title, -> { group("title").select("title") }, :class_name => "Post"
def self.what_are_you
'a category...'
@@ -25,7 +25,7 @@ class Category < ActiveRecord::Base
has_many :post_comments, :through => :posts, :source => :comments
has_many :authors, :through => :categorizations
- has_many :authors_with_select, :through => :categorizations, :source => :author, :select => 'authors.*, categorizations.post_id'
+ has_many :authors_with_select, -> { select 'authors.*, categorizations.post_id' }, :through => :categorizations, :source => :author
scope :general, -> { where(:name => 'General') }
end
diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb
index 3e9f1b0635..4b2015fe01 100644
--- a/activerecord/test/models/comment.rb
+++ b/activerecord/test/models/comment.rb
@@ -4,7 +4,7 @@ class Comment < ActiveRecord::Base
scope :not_again, -> { where("comments.body NOT LIKE '%again%'") }
scope :for_first_post, -> { where(:post_id => 1) }
scope :for_first_author, -> { joins(:post).where("posts.author_id" => 1) }
- scope :created, -> { scoped }
+ scope :created, -> { all }
belongs_to :post, :counter_cache => true
has_many :ratings
@@ -19,13 +19,13 @@ class Comment < ActiveRecord::Base
end
def self.search_by_type(q)
- self.scoped(:where => ["#{QUOTED_TYPE} = ?", q]).all
+ where("#{QUOTED_TYPE} = ?", q)
end
def self.all_as_method
all
end
- scope :all_as_scope, -> { scoped }
+ scope :all_as_scope, -> { all }
end
class SpecialComment < Comment
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index 7b993d5a2c..9bdce6e729 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -36,60 +36,64 @@ module Namespaced
end
class Firm < Company
- has_many :clients, :order => "id", :dependent => :destroy, :counter_sql =>
- "SELECT COUNT(*) FROM companies WHERE firm_id = 1 " +
- "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )",
- :before_remove => :log_before_remove,
- :after_remove => :log_after_remove
+ ActiveSupport::Deprecation.silence do
+ has_many :clients, -> { order "id" }, :dependent => :destroy, :counter_sql =>
+ "SELECT COUNT(*) FROM companies WHERE firm_id = 1 " +
+ "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )",
+ :before_remove => :log_before_remove,
+ :after_remove => :log_after_remove
+ end
has_many :unsorted_clients, :class_name => "Client"
has_many :unsorted_clients_with_symbol, :class_name => :Client
- has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC"
- has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id"
- has_many :clients_ordered_by_name, :order => "name", :class_name => "Client"
+ has_many :clients_sorted_desc, -> { order "id DESC" }, :class_name => "Client"
+ has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client"
+ has_many :clients_ordered_by_name, -> { order "name" }, :class_name => "Client"
has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false
- has_many :dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :destroy
- has_many :exclusively_dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all
- has_many :limited_clients, :class_name => "Client", :limit => 1
- has_many :clients_with_interpolated_conditions, :class_name => "Client", :conditions => proc { "rating > #{rating}" }
- has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id"
- has_many :clients_like_ms_with_hash_conditions, :conditions => { :name => 'Microsoft' }, :class_name => "Client", :order => "id"
- has_many :clients_using_sql, :class_name => "Client", :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" }
- has_many :clients_using_counter_sql, :class_name => "Client",
- :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id} " },
- :counter_sql => proc { "SELECT COUNT(*) FROM companies WHERE client_of = #{id}" }
- has_many :clients_using_zero_counter_sql, :class_name => "Client",
- :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" },
- :counter_sql => proc { "SELECT 0 FROM companies WHERE client_of = #{id}" }
- has_many :no_clients_using_counter_sql, :class_name => "Client",
- :finder_sql => 'SELECT * FROM companies WHERE client_of = 1000',
- :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000'
- has_many :clients_using_finder_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE 1=1'
+ has_many :dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :destroy
+ has_many :exclusively_dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+ has_many :limited_clients, -> { limit 1 }, :class_name => "Client"
+ has_many :clients_with_interpolated_conditions, ->(firm) { where "rating > #{firm.rating}" }, :class_name => "Client"
+ has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, :class_name => "Client"
+ has_many :clients_like_ms_with_hash_conditions, -> { where(:name => 'Microsoft').order("id") }, :class_name => "Client"
+ ActiveSupport::Deprecation.silence do
+ has_many :clients_using_sql, :class_name => "Client", :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" }
+ has_many :clients_using_counter_sql, :class_name => "Client",
+ :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id} " },
+ :counter_sql => proc { "SELECT COUNT(*) FROM companies WHERE client_of = #{id}" }
+ has_many :clients_using_zero_counter_sql, :class_name => "Client",
+ :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" },
+ :counter_sql => proc { "SELECT 0 FROM companies WHERE client_of = #{id}" }
+ has_many :no_clients_using_counter_sql, :class_name => "Client",
+ :finder_sql => 'SELECT * FROM companies WHERE client_of = 1000',
+ :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000'
+ has_many :clients_using_finder_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE 1=1'
+ end
has_many :plain_clients, :class_name => 'Client'
- has_many :readonly_clients, :class_name => 'Client', :readonly => true
+ has_many :readonly_clients, -> { readonly }, :class_name => 'Client'
has_many :clients_using_primary_key, :class_name => 'Client',
:primary_key => 'name', :foreign_key => 'firm_name'
has_many :clients_using_primary_key_with_delete_all, :class_name => 'Client',
:primary_key => 'name', :foreign_key => 'firm_name', :dependent => :delete_all
- has_many :clients_grouped_by_firm_id, :class_name => "Client", :group => "firm_id", :select => "firm_id"
- has_many :clients_grouped_by_name, :class_name => "Client", :group => "name", :select => "name"
+ has_many :clients_grouped_by_firm_id, -> { group("firm_id").select("firm_id") }, :class_name => "Client"
+ has_many :clients_grouped_by_name, -> { group("name").select("name") }, :class_name => "Client"
has_one :account, :foreign_key => "firm_id", :dependent => :destroy, :validate => true
has_one :unvalidated_account, :foreign_key => "firm_id", :class_name => 'Account', :validate => false
- has_one :account_with_select, :foreign_key => "firm_id", :select => "id, firm_id", :class_name=>'Account'
- has_one :readonly_account, :foreign_key => "firm_id", :class_name => "Account", :readonly => true
+ has_one :account_with_select, -> { select("id, firm_id") }, :foreign_key => "firm_id", :class_name=>'Account'
+ has_one :readonly_account, -> { readonly }, :foreign_key => "firm_id", :class_name => "Account"
# added order by id as in fixtures there are two accounts for Rails Core
# Oracle tests were failing because of that as the second fixture was selected
- has_one :account_using_primary_key, :primary_key => "firm_id", :class_name => "Account", :order => "id"
+ has_one :account_using_primary_key, -> { order('id') }, :primary_key => "firm_id", :class_name => "Account"
has_one :account_using_foreign_and_primary_keys, :foreign_key => "firm_name", :primary_key => "name", :class_name => "Account"
has_one :deletable_account, :foreign_key => "firm_id", :class_name => "Account", :dependent => :delete
- has_one :account_limit_500_with_hash_conditions, :foreign_key => "firm_id", :class_name => "Account", :conditions => { :credit_limit => 500 }
+ has_one :account_limit_500_with_hash_conditions, -> { where :credit_limit => 500 }, :foreign_key => "firm_id", :class_name => "Account"
has_one :unautosaved_account, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false
has_many :accounts
has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false
- has_many :association_with_references, :class_name => 'Client', :references => :foo
+ has_many :association_with_references, -> { references(:foo) }, :class_name => 'Client'
def log
@log ||= []
@@ -111,20 +115,32 @@ class DependentFirm < Company
end
class RestrictedFirm < Company
- has_one :account, :foreign_key => "firm_id", :dependent => :restrict, :order => "id"
- has_many :companies, :foreign_key => 'client_of', :order => "id", :dependent => :restrict
+ ActiveSupport::Deprecation.silence do
+ has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict
+ has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict
+ end
+end
+
+class RestrictedWithExceptionFirm < Company
+ has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_exception
+ has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict_with_exception
+end
+
+class RestrictedWithErrorFirm < Company
+ has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_error
+ has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict_with_error
end
class Client < Company
belongs_to :firm, :foreign_key => "client_of"
belongs_to :firm_with_basic_id, :class_name => "Firm", :foreign_key => "firm_id"
- belongs_to :firm_with_select, :class_name => "Firm", :foreign_key => "firm_id", :select => "id"
+ belongs_to :firm_with_select, -> { select("id") }, :class_name => "Firm", :foreign_key => "firm_id"
belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of"
- belongs_to :firm_with_condition, :class_name => "Firm", :foreign_key => "client_of", :conditions => ["1 = ?", 1]
+ belongs_to :firm_with_condition, -> { where "1 = ?", 1 }, :class_name => "Firm", :foreign_key => "client_of"
belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name"
belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name
- belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true
- belongs_to :bob_firm, :class_name => "Firm", :foreign_key => "client_of", :conditions => { :name => "Bob" }
+ belongs_to :readonly_firm, -> { readonly }, :class_name => "Firm", :foreign_key => "firm_id"
+ belongs_to :bob_firm, -> { where :name => "Bob" }, :class_name => "Firm", :foreign_key => "client_of"
has_many :accounts, :through => :firm
belongs_to :account
@@ -157,10 +173,6 @@ class Client < Company
before_destroy :overwrite_to_raise
# Used to test that read and question methods are not generated for these attributes
- def ruby_type
- read_attribute :ruby_type
- end
-
def rating?
query_attribute :rating
end
@@ -179,9 +191,9 @@ end
class ExclusivelyDependentFirm < Company
has_one :account, :foreign_key => "firm_id", :dependent => :delete
- has_many :dependent_sanitized_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => "name = 'BigShot Inc.'"
- has_many :dependent_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => ["name = ?", 'BigShot Inc.']
- has_many :dependent_hash_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => {:name => 'BigShot Inc.'}
+ has_many :dependent_sanitized_conditional_clients_of_firm, -> { order("id").where("name = 'BigShot Inc.'") }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+ has_many :dependent_conditional_clients_of_firm, -> { order("id").where("name = ?", 'BigShot Inc.') }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+ has_many :dependent_hash_conditional_clients_of_firm, -> { order("id").where(:name => 'BigShot Inc.') }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
end
class SpecialClient < Client
diff --git a/activerecord/test/models/company_in_module.rb b/activerecord/test/models/company_in_module.rb
index 2c8c30efb4..eb2aedc425 100644
--- a/activerecord/test/models/company_in_module.rb
+++ b/activerecord/test/models/company_in_module.rb
@@ -7,11 +7,13 @@ module MyApplication
end
class Firm < Company
- has_many :clients, :order => "id", :dependent => :destroy
- has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC"
- has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id"
- has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id"
- has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}'
+ has_many :clients, -> { order("id") }, :dependent => :destroy
+ has_many :clients_sorted_desc, -> { order("id DESC") }, :class_name => "Client"
+ has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client"
+ has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, :class_name => "Client"
+ ActiveSupport::Deprecation.silence do
+ has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}'
+ end
has_one :account, :class_name => 'MyApplication::Billing::Account', :dependent => :destroy
end
diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb
index 594c484f20..7e8e82542f 100644
--- a/activerecord/test/models/customer.rb
+++ b/activerecord/test/models/customer.rb
@@ -1,5 +1,12 @@
class Customer < ActiveRecord::Base
cattr_accessor :gps_conversion_was_run
+
+ composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true
+ composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money }
+ composed_of :gps_location, :allow_nil => true
+ composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location),
+ :converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)}
+ composed_of :fullname, :mapping => %w(name to_s), :constructor => Proc.new { |name| Fullname.parse(name) }, :converter => :parse
end
class Address
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index 43cde4ab73..622dd75aeb 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -2,42 +2,42 @@ require 'ostruct'
module DeveloperProjectsAssociationExtension
def find_most_recent
- scoped(:order => "id DESC").first
+ order("id DESC").first
end
end
module DeveloperProjectsAssociationExtension2
def find_least_recent
- scoped(:order => "id ASC").first
+ order("id ASC").first
end
end
class Developer < ActiveRecord::Base
has_and_belongs_to_many :projects do
def find_most_recent
- scoped(:order => "id DESC").first
+ order("id DESC").first
end
end
has_and_belongs_to_many :projects_extended_by_name,
+ -> { extending(DeveloperProjectsAssociationExtension) },
:class_name => "Project",
:join_table => "developers_projects",
- :association_foreign_key => "project_id",
- :extend => DeveloperProjectsAssociationExtension
+ :association_foreign_key => "project_id"
has_and_belongs_to_many :projects_extended_by_name_twice,
+ -> { extending(DeveloperProjectsAssociationExtension, DeveloperProjectsAssociationExtension2) },
:class_name => "Project",
:join_table => "developers_projects",
- :association_foreign_key => "project_id",
- :extend => [DeveloperProjectsAssociationExtension, DeveloperProjectsAssociationExtension2]
+ :association_foreign_key => "project_id"
has_and_belongs_to_many :projects_extended_by_name_and_block,
+ -> { extending(DeveloperProjectsAssociationExtension) },
:class_name => "Project",
:join_table => "developers_projects",
- :association_foreign_key => "project_id",
- :extend => DeveloperProjectsAssociationExtension do
+ :association_foreign_key => "project_id" do
def find_least_recent
- scoped(:order => "id ASC").first
+ order("id ASC").first
end
end
@@ -64,6 +64,12 @@ class AuditLog < ActiveRecord::Base
belongs_to :unvalidated_developer, :class_name => 'Developer'
end
+DeveloperSalary = Struct.new(:amount)
+class DeveloperWithAggregate < ActiveRecord::Base
+ self.table_name = 'developers'
+ composed_of :salary, :class_name => 'DeveloperSalary', :mapping => [%w(salary amount)]
+end
+
class DeveloperWithBeforeDestroyRaise < ActiveRecord::Base
self.table_name = 'developers'
has_and_belongs_to_many :projects, :join_table => 'developers_projects', :foreign_key => 'developer_id'
@@ -175,14 +181,14 @@ end
class EagerDeveloperWithDefaultScope < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects, :foreign_key => 'developer_id', :join_table => 'developers_projects', :order => 'projects.id'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
default_scope { includes(:projects) }
end
class EagerDeveloperWithClassMethodDefaultScope < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects, :foreign_key => 'developer_id', :join_table => 'developers_projects', :order => 'projects.id'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
def self.default_scope
includes(:projects)
@@ -191,21 +197,21 @@ end
class EagerDeveloperWithLambdaDefaultScope < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects, :foreign_key => 'developer_id', :join_table => 'developers_projects', :order => 'projects.id'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
default_scope lambda { includes(:projects) }
end
class EagerDeveloperWithBlockDefaultScope < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects, :foreign_key => 'developer_id', :join_table => 'developers_projects', :order => 'projects.id'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
default_scope { includes(:projects) }
end
class EagerDeveloperWithCallableDefaultScope < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects, :foreign_key => 'developer_id', :join_table => 'developers_projects', :order => 'projects.id'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
default_scope OpenStruct.new(:call => includes(:projects))
end
diff --git a/activerecord/test/models/friendship.rb b/activerecord/test/models/friendship.rb
new file mode 100644
index 0000000000..6b4f7acc38
--- /dev/null
+++ b/activerecord/test/models/friendship.rb
@@ -0,0 +1,4 @@
+class Friendship < ActiveRecord::Base
+ belongs_to :friend, class_name: 'Person'
+ belongs_to :follower, foreign_key: 'friend_id', class_name: 'Person', counter_cache: :followers_count
+end
diff --git a/activerecord/test/models/liquid.rb b/activerecord/test/models/liquid.rb
index 3fcd5e4b69..6cfd443e75 100644
--- a/activerecord/test/models/liquid.rb
+++ b/activerecord/test/models/liquid.rb
@@ -1,5 +1,5 @@
class Liquid < ActiveRecord::Base
self.table_name = :liquid
- has_many :molecules, :uniq => true
+ has_many :molecules, -> { uniq }
end
diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb
index 1f719b0858..1134b09d8b 100644
--- a/activerecord/test/models/member.rb
+++ b/activerecord/test/models/member.rb
@@ -5,8 +5,8 @@ class Member < ActiveRecord::Base
has_many :fellow_members, :through => :club, :source => :members
has_one :club, :through => :current_membership
has_one :selected_club, :through => :selected_membership, :source => :club
- has_one :favourite_club, :through => :membership, :conditions => ["memberships.favourite = ?", true], :source => :club
- has_one :hairy_club, :through => :membership, :conditions => {:clubs => {:name => "Moustache and Eyebrow Fancier Club"}}, :source => :club
+ has_one :favourite_club, -> { where "memberships.favourite = ?", true }, :through => :membership, :source => :club
+ has_one :hairy_club, -> { where :clubs => {:name => "Moustache and Eyebrow Fancier Club"} }, :through => :membership, :source => :club
has_one :sponsor, :as => :sponsorable
has_one :sponsor_club, :through => :sponsor
has_one :member_detail
@@ -24,11 +24,10 @@ class Member < ActiveRecord::Base
has_one :club_category, :through => :club, :source => :category
- has_many :current_memberships
- has_one :club_through_many, :through => :current_memberships, :source => :club
-
- has_many :current_memberships, :conditions => { :favourite => true }
+ has_many :current_memberships, -> { where :favourite => true }
has_many :clubs, :through => :current_memberships
+
+ has_one :club_through_many, :through => :current_memberships, :source => :club
end
class SelfMember < ActiveRecord::Base
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index 33cd6020a1..6e6ff29f77 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -5,14 +5,16 @@ class Person < ActiveRecord::Base
has_many :posts, :through => :readers
has_many :secure_posts, :through => :secure_readers
- has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments,
- :conditions => 'comments.id is null', :references => :comments
+ has_many :posts_with_no_comments, -> { includes(:comments).where('comments.id is null').references(:comments) },
+ :through => :readers, :source => :post
+
+ has_many :followers, foreign_key: 'friend_id', class_name: 'Friendship'
has_many :references
has_many :bad_references
- has_many :fixed_bad_references, :conditions => { :favourite => true }, :class_name => 'BadReference'
- has_one :favourite_reference, :class_name => 'Reference', :conditions => ['favourite=?', true]
- has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :include => :comments, :order => 'comments.id'
+ has_many :fixed_bad_references, -> { where :favourite => true }, :class_name => 'BadReference'
+ has_one :favourite_reference, -> { where 'favourite=?', true }, :class_name => 'Reference'
+ has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order('comments.id') }, :through => :readers, :source => :post
has_many :jobs, :through => :references
has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy
@@ -109,4 +111,4 @@ class NestedPerson < ActiveRecord::Base
def best_friend_first_name=(new_name)
assign_attributes({ :best_friend_attributes => { :first_name => new_name } })
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index 5e0f5323e6..170fc2ffe3 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -1,7 +1,7 @@
class Pirate < ActiveRecord::Base
belongs_to :parrot, :validate => true
belongs_to :non_validated_parrot, :class_name => 'Parrot'
- has_and_belongs_to_many :parrots, :validate => true, :order => 'parrots.id ASC'
+ has_and_belongs_to_many :parrots, -> { order('parrots.id ASC') }, :validate => true
has_and_belongs_to_many :non_validated_parrots, :class_name => 'Parrot'
has_and_belongs_to_many :parrots_with_method_callbacks, :class_name => "Parrot",
:before_add => :log_before_add,
@@ -21,7 +21,7 @@ class Pirate < ActiveRecord::Base
has_one :ship
has_one :update_only_ship, :class_name => 'Ship'
has_one :non_validated_ship, :class_name => 'Ship'
- has_many :birds, :order => 'birds.id ASC'
+ has_many :birds, -> { order('birds.id ASC') }
has_many :birds_with_method_callbacks, :class_name => "Bird",
:before_add => :log_before_add,
:after_add => :log_after_add,
@@ -34,7 +34,7 @@ class Pirate < ActiveRecord::Base
:after_remove => proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"}
has_many :birds_with_reject_all_blank, :class_name => "Bird"
- has_one :foo_bulb, :foreign_key => :car_id, :class_name => "Bulb", :conditions => { :name => 'foo' }
+ has_one :foo_bulb, -> { where :name => 'foo' }, :foreign_key => :car_id, :class_name => "Bulb"
accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
@@ -53,7 +53,7 @@ class Pirate < ActiveRecord::Base
attributes.delete('_reject_me_if_new').present? && !persisted?
end
- attr_accessor :cancel_save_from_callback
+ attr_accessor :cancel_save_from_callback, :parrots_limit
before_save :cancel_save_callback_method, :if => :cancel_save_from_callback
def cancel_save_callback_method
false
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index 1aaf9a1b82..c995f59a15 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -16,14 +16,14 @@ class Post < ActiveRecord::Base
end
end
- belongs_to :author_with_posts, :class_name => "Author", :foreign_key => :author_id, :include => :posts
- belongs_to :author_with_address, :class_name => "Author", :foreign_key => :author_id, :include => :author_address
+ belongs_to :author_with_posts, -> { includes(:posts) }, :class_name => "Author", :foreign_key => :author_id
+ belongs_to :author_with_address, -> { includes(:author_address) }, :class_name => "Author", :foreign_key => :author_id
def first_comment
super.body
end
- has_one :first_comment, :class_name => 'Comment', :order => 'id ASC'
- has_one :last_comment, :class_name => 'Comment', :order => 'id desc'
+ has_one :first_comment, -> { order('id ASC') }, :class_name => 'Comment'
+ has_one :last_comment, -> { order('id desc') }, :class_name => 'Comment'
scope :with_special_comments, -> { joins(:comments).where(:comments => {:type => 'SpecialComment'}) }
scope :with_very_special_comments, -> { joins(:comments).where(:comments => {:type => 'VerySpecialComment'}) }
@@ -31,7 +31,7 @@ class Post < ActiveRecord::Base
has_many :comments do
def find_most_recent
- scoped(:order => "id DESC").first
+ order("id DESC").first
end
def newest
@@ -47,13 +47,14 @@ class Post < ActiveRecord::Base
has_many :author_categorizations, :through => :author, :source => :categorizations
has_many :author_addresses, :through => :author
- has_many :comments_with_interpolated_conditions, :class_name => 'Comment',
- :conditions => proc { ["#{"#{aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome'] }
+ has_many :comments_with_interpolated_conditions,
+ ->(p) { where "#{"#{p.aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome' },
+ :class_name => 'Comment'
has_one :very_special_comment
- has_one :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post
+ has_one :very_special_comment_with_post, -> { includes(:post) }, :class_name => "VerySpecialComment"
has_many :special_comments
- has_many :nonexistant_comments, :class_name => 'Comment', :conditions => 'comments.id < 0'
+ has_many :nonexistant_comments, -> { where 'comments.id < 0' }, :class_name => 'Comment'
has_many :special_comments_ratings, :through => :special_comments, :source => :ratings
has_many :special_comments_ratings_taggings, :through => :special_comments_ratings, :source => :taggings
@@ -64,33 +65,30 @@ class Post < ActiveRecord::Base
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings do
def add_joins_and_select
- scoped(:select => 'tags.*, authors.id as author_id',
- :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id').all
+ select('tags.*, authors.id as author_id')
+ .joins('left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id')
+ .to_a
end
end
- has_many :interpolated_taggings, :class_name => 'Tagging', :as => :taggable, :conditions => proc { "1 = #{1}" }
- has_many :interpolated_tags, :through => :taggings
- has_many :interpolated_tags_2, :through => :interpolated_taggings, :source => :tag
-
has_many :taggings_with_delete_all, :class_name => 'Tagging', :as => :taggable, :dependent => :delete_all
has_many :taggings_with_destroy, :class_name => 'Tagging', :as => :taggable, :dependent => :destroy
has_many :tags_with_destroy, :through => :taggings, :source => :tag, :dependent => :destroy
has_many :tags_with_nullify, :through => :taggings, :source => :tag, :dependent => :nullify
- has_many :misc_tags, :through => :taggings, :source => :tag, :conditions => { :tags => { :name => 'Misc' } }
+ has_many :misc_tags, -> { where :tags => { :name => 'Misc' } }, :through => :taggings, :source => :tag
has_many :funky_tags, :through => :taggings, :source => :tag
has_many :super_tags, :through => :taggings
has_many :tags_with_primary_key, :through => :taggings, :source => :tag_with_primary_key
has_one :tagging, :as => :taggable
- has_many :first_taggings, :as => :taggable, :class_name => 'Tagging', :conditions => { :taggings => { :comment => 'first' } }
- has_many :first_blue_tags, :through => :first_taggings, :source => :tag, :conditions => { :tags => { :name => 'Blue' } }
+ has_many :first_taggings, -> { where :taggings => { :comment => 'first' } }, :as => :taggable, :class_name => 'Tagging'
+ has_many :first_blue_tags, -> { where :tags => { :name => 'Blue' } }, :through => :first_taggings, :source => :tag
- has_many :first_blue_tags_2, :through => :taggings, :source => :blue_tag, :conditions => { :taggings => { :comment => 'first' } }
+ has_many :first_blue_tags_2, -> { where :taggings => { :comment => 'first' } }, :through => :taggings, :source => :blue_tag
- has_many :invalid_taggings, :as => :taggable, :class_name => "Tagging", :conditions => 'taggings.id < 0'
+ has_many :invalid_taggings, -> { where 'taggings.id < 0' }, :as => :taggable, :class_name => "Tagging"
has_many :invalid_tags, :through => :invalid_taggings, :source => :tag
has_many :categorizations, :foreign_key => :category_id
@@ -109,7 +107,7 @@ class Post < ActiveRecord::Base
has_many :readers
has_many :secure_readers
- has_many :readers_with_person, :include => :person, :class_name => "Reader"
+ has_many :readers_with_person, -> { includes(:person) }, :class_name => "Reader"
has_many :people, :through => :readers
has_many :secure_people, :through => :secure_readers
has_many :single_people, :through => :readers
@@ -118,9 +116,12 @@ class Post < ActiveRecord::Base
:after_add => lambda {|owner, reader| log(:added, :after, reader.first_name) },
:before_remove => lambda {|owner, reader| log(:removed, :before, reader.first_name) },
:after_remove => lambda {|owner, reader| log(:removed, :after, reader.first_name) }
- has_many :skimmers, :class_name => 'Reader', :conditions => { :skimmer => true }
+ has_many :skimmers, -> { where :skimmer => true }, :class_name => 'Reader'
has_many :impatient_people, :through => :skimmers, :source => :person
+ has_many :lazy_readers
+ has_many :lazy_readers_skimmers_or_not, -> { where(skimmer: [ true, false ]) }, :class_name => 'LazyReader'
+
def self.top(limit)
ranked_by_comments.limit_by(limit)
end
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 32ce164995..af3ec4be83 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -1,26 +1,30 @@
class Project < ActiveRecord::Base
- has_and_belongs_to_many :developers, :uniq => true, :order => 'developers.name desc, developers.id desc'
- has_and_belongs_to_many :readonly_developers, :class_name => "Developer", :readonly => true
- has_and_belongs_to_many :selected_developers, :class_name => "Developer", :select => "developers.*", :uniq => true
- has_and_belongs_to_many :non_unique_developers, :order => 'developers.name desc, developers.id desc', :class_name => 'Developer'
- has_and_belongs_to_many :limited_developers, :class_name => "Developer", :limit => 1
- has_and_belongs_to_many :developers_named_david, :class_name => "Developer", :conditions => "name = 'David'", :uniq => true
- has_and_belongs_to_many :developers_named_david_with_hash_conditions, :class_name => "Developer", :conditions => { :name => 'David' }, :uniq => true
- has_and_belongs_to_many :salaried_developers, :class_name => "Developer", :conditions => "salary > 0"
- has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => proc { "SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id" }
- has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => proc {
- "SELECT
- t.*, j.*
- FROM
- developers_projects j,
- developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id"
- }
- has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => proc { |record| "DELETE FROM developers_projects WHERE project_id = #{id} AND developer_id = #{record.id}" }
+ has_and_belongs_to_many :developers, -> { uniq.order 'developers.name desc, developers.id desc' }
+ has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer"
+ has_and_belongs_to_many :selected_developers, -> { uniq.select "developers.*" }, :class_name => "Developer"
+ has_and_belongs_to_many :non_unique_developers, -> { order 'developers.name desc, developers.id desc' }, :class_name => 'Developer'
+ has_and_belongs_to_many :limited_developers, -> { limit 1 }, :class_name => "Developer"
+ has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").uniq }, :class_name => "Developer"
+ has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(:name => 'David').uniq }, :class_name => "Developer"
+ has_and_belongs_to_many :salaried_developers, -> { where "salary > 0" }, :class_name => "Developer"
+
+ ActiveSupport::Deprecation.silence do
+ has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => proc { "SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id" }
+ has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => proc {
+ "SELECT
+ t.*, j.*
+ FROM
+ developers_projects j,
+ developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id"
+ }
+ has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => proc { |record| "DELETE FROM developers_projects WHERE project_id = #{id} AND developer_id = #{record.id}" }
+ end
+
has_and_belongs_to_many :developers_with_callbacks, :class_name => "Developer", :before_add => Proc.new {|o, r| o.developers_log << "before_adding#{r.id || '<new>'}"},
:after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || '<new>'}"},
:before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"},
:after_remove => Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"}
- has_and_belongs_to_many :well_payed_salary_groups, :class_name => "Developer", :group => "developers.salary", :having => "SUM(salary) > 10000", :select => "SUM(salary) as salary"
+ has_and_belongs_to_many :well_payed_salary_groups, -> { group("developers.salary").having("SUM(salary) > 10000").select("SUM(salary) as salary") }, :class_name => "Developer"
attr_accessor :developers_log
after_initialize :set_developers_log
@@ -32,7 +36,7 @@ class Project < ActiveRecord::Base
def self.all_as_method
all
end
- scope :all_as_scope, -> { scoped }
+ scope :all_as_scope, -> { all }
end
class SpecialProject < Project
diff --git a/activerecord/test/models/reader.rb b/activerecord/test/models/reader.rb
index 59005ac604..f5b6079bd2 100644
--- a/activerecord/test/models/reader.rb
+++ b/activerecord/test/models/reader.rb
@@ -12,3 +12,11 @@ class SecureReader < ActiveRecord::Base
attr_accessible nil
end
+
+class LazyReader < ActiveRecord::Base
+ self.table_name = "readers"
+ default_scope -> { where(skimmer: true) }
+
+ belongs_to :post
+ belongs_to :person
+end
diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb
index aa4a3638fd..ec3dcf8a97 100644
--- a/activerecord/test/models/sponsor.rb
+++ b/activerecord/test/models/sponsor.rb
@@ -2,6 +2,6 @@ class Sponsor < ActiveRecord::Base
belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id"
belongs_to :sponsorable, :polymorphic => true
belongs_to :thing, :polymorphic => true, :foreign_type => :sponsorable_type, :foreign_key => :sponsorable_id
- belongs_to :sponsorable_with_conditions, :polymorphic => true,
- :foreign_type => 'sponsorable_type', :foreign_key => 'sponsorable_id', :conditions => {:name => 'Ernie'}
+ belongs_to :sponsorable_with_conditions, -> { where :name => 'Ernie'}, :polymorphic => true,
+ :foreign_type => 'sponsorable_type', :foreign_key => 'sponsorable_id'
end
diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb
index ef323df158..f91f2ad2e9 100644
--- a/activerecord/test/models/tagging.rb
+++ b/activerecord/test/models/tagging.rb
@@ -3,12 +3,11 @@ module Taggable
end
class Tagging < ActiveRecord::Base
- belongs_to :tag, :include => :tagging
+ belongs_to :tag, -> { includes(:tagging) }
belongs_to :super_tag, :class_name => 'Tag', :foreign_key => 'super_tag_id'
belongs_to :invalid_tag, :class_name => 'Tag', :foreign_key => 'tag_id'
- belongs_to :blue_tag, :class_name => 'Tag', :foreign_key => :tag_id, :conditions => { :tags => { :name => 'Blue' } }
+ belongs_to :blue_tag, -> { where :tags => { :name => 'Blue' } }, :class_name => 'Tag', :foreign_key => :tag_id
belongs_to :tag_with_primary_key, :class_name => 'Tag', :foreign_key => :tag_id, :primary_key => :custom_primary_key
- belongs_to :interpolated_tag, :class_name => 'Tag', :foreign_key => :tag_id, :conditions => proc { "1 = #{1}" }
belongs_to :taggable, :polymorphic => true, :counter_cache => true
has_many :things, :through => :taggable
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index fb27c9d4f0..4b27c16681 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -1,5 +1,5 @@
class Topic < ActiveRecord::Base
- scope :base, -> { scoped }
+ scope :base, -> { all }
scope :written_before, lambda { |time|
if time
where 'written_on < ?', time
@@ -8,13 +8,13 @@ class Topic < ActiveRecord::Base
scope :approved, -> { where(:approved => true) }
scope :rejected, -> { where(:approved => false) }
- scope :scope_with_lambda, lambda { scoped }
+ scope :scope_with_lambda, lambda { all }
scope :by_lifo, -> { where(:author_name => 'lifo') }
scope :replied, -> { where 'replies_count > 0' }
scope 'approved_as_string', -> { where(:approved => true) }
- scope :anonymous_extension, -> { scoped } do
+ scope :anonymous_extension, -> { all } do
def one
1
end
diff --git a/activerecord/test/models/vegetables.rb b/activerecord/test/models/vegetables.rb
new file mode 100644
index 0000000000..1f41cde3a5
--- /dev/null
+++ b/activerecord/test/models/vegetables.rb
@@ -0,0 +1,24 @@
+class Vegetable < ActiveRecord::Base
+
+ validates_presence_of :name
+
+ def self.inheritance_column
+ 'custom_type'
+ end
+end
+
+class Cucumber < Vegetable
+end
+
+class Cabbage < Vegetable
+end
+
+class GreenCabbage < Cabbage
+end
+
+class KingCole < GreenCabbage
+end
+
+class RedCabbage < Cabbage
+ belongs_to :seller, :class_name => 'Company'
+end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 00688eab37..007349ea87 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -37,12 +37,12 @@ ActiveRecord::Schema.define do
create_table :admin_users, :force => true do |t|
t.string :name
- t.text :settings, :null => true
+ t.string :settings, :null => true, :limit => 1024
# MySQL does not allow default values for blobs. Fake it out with a
# big varchar below.
- t.string :preferences, :null => false, :default => '', :limit => 1024
+ t.string :preferences, :null => true, :default => '', :limit => 1024
t.string :json_data, :null => true, :limit => 1024
- t.string :json_data_empty, :null => false, :default => "", :limit => 1024
+ t.string :json_data_empty, :null => true, :default => "", :limit => 1024
t.references :account
end
@@ -171,19 +171,24 @@ ActiveRecord::Schema.define do
create_table :companies, :force => true do |t|
t.string :type
- t.string :ruby_type
t.integer :firm_id
t.string :firm_name
t.string :name
t.integer :client_of
t.integer :rating, :default => 1
t.integer :account_id
- t.string :description, :null => false, :default => ""
+ t.string :description, :default => ""
end
- add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index"
+ add_index :companies, [:firm_id, :type, :rating], :name => "company_index"
add_index :companies, [:firm_id, :type], :name => "company_partial_index", :where => "rating > 10"
+ create_table :vegetables, :force => true do |t|
+ t.string :name
+ t.integer :seller_id
+ t.string :custom_type
+ end
+
create_table :computers, :force => true do |t|
t.integer :developer, :null => false
t.integer :extendedWarranty, :null => false
@@ -270,6 +275,11 @@ ActiveRecord::Schema.define do
t.string :name
end
+ create_table :friendships, :force => true do |t|
+ t.integer :friend_id
+ t.integer :person_id
+ end
+
create_table :goofy_string_id, :force => true, :id => false do |t|
t.string :id, :null => false
t.string :info
@@ -476,6 +486,7 @@ ActiveRecord::Schema.define do
t.references :number1_fan
t.integer :lock_version, :null => false, :default => 0
t.string :comments
+ t.integer :followers_count, :default => 0
t.references :best_friend
t.references :best_friend_of
t.timestamps
diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb
index c176316a05..92736e0ca9 100644
--- a/activerecord/test/support/connection.rb
+++ b/activerecord/test/support/connection.rb
@@ -1,6 +1,6 @@
require 'active_support/logger'
-require_dependency 'models/college'
-require_dependency 'models/course'
+require 'models/college'
+require 'models/course'
module ARTest
def self.connection_name
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index df144dd00b..761780fb8b 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,5 +1,46 @@
## Rails 4.0.0 (unreleased) ##
+* An optional block can be passed to `HashWithIndifferentAccess#update` and `#merge`.
+ The block will be invoked for each duplicated key, and used to resolve the conflict,
+ thus replicating the behaviour of the corresponding methods on the `Hash` class.
+
+ *Leo Cassarani*
+
+* Remove `j` alias for `ERB::Util#json_escape`.
+ The `j` alias is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`
+ and both modules are included in the view context that would confuse the developers.
+
+ *Akira Matsuda*
+
+* Replace deprecated `memcache-client` gem with `dalli` in ActiveSupport::Cache::MemCacheStore
+
+ *Guillermo Iguaran*
+
+* Add default values to all `ActiveSupport::NumberHelper` methods, to avoid
+ errors with empty locales or missing values.
+
+ *Carlos Antonio da Silva*
+
+* ActiveSupport::JSON::Variable is deprecated. Define your own #as_json and
+ #encode_json methods for custom JSON string literals.
+
+ *Erich Menge*
+
+* Add String#indent. *fxn & Ace Suares*
+
+* Inflections can now be defined per locale. `singularize` and `pluralize`
+ accept locale as an extra argument.
+
+ *David Celis*
+
+* `Object#try` will now return nil instead of raise a NoMethodError if the
+ receiving object does not implement the method, but you can still get the
+ old behavior by using the new `Object#try!`.
+
+ *DHH*
+
+* `ERB::Util.html_escape` now escapes single quotes. *Santiago Pastorino*
+
* `Time#change` now works with time values with offsets other than UTC or the local time zone. *Andrew White*
* `ActiveSupport::Callbacks`: deprecate usage of filter object with `#before` and `#after` methods as `around` callback. *Bogdan Gusiev*
@@ -79,1700 +120,4 @@
* Remove deprecated ActiveSupport::JSON::Variable. *Erich Menge*
-
-## Rails 3.2.5 (Jun 1, 2012) ##
-
-* ActiveSupport::JSON::Variable is deprecated. Define your own #as_json and #encode_json methods
- for custom JSON string literals. *Erich Menge*
-
-
-## Rails 3.2.4 (May 31, 2012) ##
-
-* Added #beginning_of_hour and #end_of_hour to Time and DateTime core
- extensions. *Mark J. Titorenko*
-
-
-## Rails 3.2.3 (March 30, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.2 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.1 (January 26, 2012) ##
-
-* Documentation fixes and improvements.
-
-* Update time zone offset information. *Ravil Bayramgalin*
-
-* The deprecated `ActiveSupport::Base64.decode64` calls `::Base64.decode64`
- now. *Jonathan Viney*
-
-* Fixes uninitialized constant `ActiveSupport::TaggedLogging::ERROR`. *kennyj*
-
-
-## Rails 3.2.0 (January 20, 2012) ##
-
-* ActiveSupport::Base64 is deprecated in favor of ::Base64. *Sergey Nartimov*
-
-* Module#synchronize is deprecated with no replacement. Please use `monitor`
- from ruby's standard library.
-
-* (Date|DateTime|Time)#beginning_of_week accept an optional argument to
- be able to set the day at which weeks are assumed to start.
-
-* Deprecated ActiveSupport::MessageEncryptor#encrypt and decrypt. *José Valim*
-
-* ActiveSupport::Notifications.subscribed provides subscriptions to events while a block runs. *fxn*
-
-* Module#qualified_const_(defined?|get|set) are analogous to the corresponding methods
- in the standard API, but accept qualified constant names. *fxn*
-
-* Added inflection #deconstantize which complements #demodulize. This inflection
- removes the righmost segment in a qualified constant name. *fxn*
-
-* Added ActiveSupport:TaggedLogging that can wrap any standard Logger class to provide tagging capabilities *DHH*
-
- Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
- Logger.tagged("BCX") { Logger.info "Stuff" } # Logs "[BCX] Stuff"
- Logger.tagged("BCX", "Jason") { Logger.info "Stuff" } # Logs "[BCX] [Jason] Stuff"
- Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
-
-* Added safe_constantize that constantizes a string but returns nil instead of an exception if the constant (or part of it) does not exist *Ryan Oblak*
-
-* ActiveSupport::OrderedHash is now marked as extractable when using Array#extract_options! *Prem Sichanugrist*
-
-* Added Array#prepend as an alias for Array#unshift and Array#append as an alias for Array#<< *DHH*
-
-* The definition of blank string for Ruby 1.9 has been extended to Unicode whitespace.
- Also, in 1.8 the ideographic space U+3000 is considered to be whitespace. *Akira Matsuda, Damien Mathieu*
-
-* The inflector understands acronyms. *dlee*
-
-* Deprecated ActiveSupport::Memoizable in favor of Ruby memoization pattern *José Valim*
-
-* Added Time#all_day/week/quarter/year as a way of generating ranges (example: Event.where(created_at: Time.now.all_week)) *DHH*
-
-* Added instance_accessor: false as an option to Class#cattr_accessor and friends *DHH*
-
-* Removed ActiveSupport::SecureRandom in favor of SecureRandom from the standard library *Jon Leighton*
-
-* ActiveSupport::OrderedHash now has different behavior for #each and
- \#each_pair when given a block accepting its parameters with a splat. *Andrew Radev*
-
-* ActiveSupport::BufferedLogger#silence is deprecated. If you want to squelch
- logs for a certain block, change the log level for that block.
-
-* ActiveSupport::BufferedLogger#open_log is deprecated. This method should
- not have been public in the first place.
-
-* ActiveSupport::BufferedLogger's behavior of automatically creating the
- directory for your log file is deprecated. Please make sure to create the
- directory for your log file before instantiating.
-
-* ActiveSupport::BufferedLogger#auto_flushing is deprecated. Either set the
- sync level on the underlying file handle like this:
-
- f = File.open('foo.log', 'w')
- f.sync = true
- ActiveSupport::BufferedLogger.new f
-
- Or tune your filesystem. The FS cache is now what controls flushing.
-
-* ActiveSupport::BufferedLogger#flush is deprecated. Set sync on your
- filehandle, or tune your filesystem.
-
-
-## Rails 3.1.4 (March 1, 2012) ##
-
-* No changes
-
-
-## Rails 3.1.3 (November 20, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.2 (November 18, 2011) ##
-
-* No changes
-
-
-## Rails 3.1.1 (October 7, 2011) ##
-
-* ruby193: String#prepend is also unsafe *Akira Matsuda*
-
-* Fix obviously breakage of Time.=== for Time subclasses *jeremyevans*
-
-* Added fix so that file store does not raise an exception when cache dir does
- not exist yet. This can happen if a delete_matched is called before anything
- is saved in the cache. *Philippe Huibonhoa*
-
-* Fixed performance issue where TimeZone lookups would require tzinfo each time *Tim Lucas*
-
-* ActiveSupport::OrderedHash is now marked as extractable when using Array#extract_options! *Prem Sichanugrist*
-
-
-## Rails 3.1.0 (August 30, 2011) ##
-
-* ActiveSupport::Dependencies#load and ActiveSupport::Dependencies#require now
- return the value from `super` *Aaron Patterson*
-
-* Fixed ActiveSupport::Gzip to work properly in Ruby 1.8 *Guillermo Iguaran*
-
-* Kernel.require_library_or_gem was deprecated and will be removed in Rails 3.2.0 *Josh Kalderimis*
-
-* ActiveSupport::Duration#duplicable? was fixed for Ruby 1.8 *thedarkone*
-
-* ActiveSupport::BufferedLogger set log encoding to BINARY, but still use text
- mode to output portable newlines. *fxn*
-
-* ActiveSupport::Dependencies now raises NameError if it finds an existing constant in load_missing_constant. This better reflects the nature of the error which is usually caused by calling constantize on a nested constant. *Andrew White*
-
-* Deprecated ActiveSupport::SecureRandom in favour of SecureRandom from the standard library *Jon Leighton*
-
-* New reporting method Kernel#quietly. *fxn*
-
-* Add String#inquiry as a convenience method for turning a string into a StringInquirer object *DHH*
-
-* Add Object#in? to test if an object is included in another object *Prem Sichanugrist, Brian Morearty, John Reitano*
-
-* LocalCache strategy is now a real middleware class, not an anonymous class
- posing for pictures.
-
-* ActiveSupport::Dependencies::ClassCache class has been introduced for
- holding references to reloadable classes.
-
-* ActiveSupport::Dependencies::Reference has been refactored to take direct
- advantage of the new ClassCache.
-
-* Backports Range#cover? as an alias for Range#include? in Ruby 1.8 *Diego Carrion, fxn*
-
-* Added weeks_ago and prev_week to Date/DateTime/Time. *Rob Zolkos, fxn*
-
-* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! *Andrew White*
-
-* JSON decoding now uses the multi_json gem which also vendors a json engine called OkJson. The yaml backend has been removed in favor of OkJson as a default engine for 1.8.x, while the built in 1.9.x json implementation will be used by default. *Josh Kalderimis*
-
-
-## Rails 3.0.12 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.0.11 (November 18, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.10 (August 16, 2011) ##
-
-* Delayed backtrace scrubbing in `load_missing_constant` until we actually
- raise the exception
-
-
-## Rails 3.0.9 (June 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.8 (June 7, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.7 (April 18, 2011) ##
-
-* Hash.from_xml no longer loses attributes on tags containing only whitespace *André Arko*
-
-
-## Rails 3.0.6 (April 5, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.5 (February 26, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.4 (February 8, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.3 (November 16, 2010) ##
-
-* No changes.
-
-
-## Rails 3.0.2 (November 15, 2010) ##
-
-* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! *Andrew White*
-
-
-## Rails 3.0.1 (October 15, 2010) ##
-
-* No Changes, just a version bump.
-
-
-## Rails 3.0.0 (August 29, 2010) ##
-
-* Implemented String#strip_heredoc. *fxn*
-
-* Pluggable cache stores: setting config.cache_store = "custom_store" will require 'active_support/cache/custom_store' and look for the CustomStore constant. #5486 *Mike Perham*
-
-* Removed Object#returning, Object#tap should be used instead. *Santiago Pastorino*
-
-* Deprecation behavior is no longer hardcoded to the name of the environment.
- Instead, it is set via config.active_support.deprecation and can be one
- of :log, :stderr or :notify. :notify is a new style that sends the warning
- via ActiveSupport::Notifications, and is the new default for production
- *Yehuda Katz*
-
-* Renamed ActiveSupport::Dependecies.load_(once_)paths to autoload_(once_)paths. *fxn*
-
-* Added ActiveSupport::FileUpdateChecker to execute a block only if a set of files changed, used by Router and I18n locale files. *José Valim*
-
-* Added ActiveSupport::DescendantsTracker to track descendants with support to constants reloading. *José Valim*
-
-* ActiveSupport::OrderedHash#merge and #merge! accept a block. #4838 *Paul Mucur, fxn*
-
-* Date#since, #ago, #beginning_of_day, #end_of_day, and #xmlschema honor now the user time zone if set. *Geoff Buesing*
-
-* Extracted String#truncate from TextHelper#truncate *DHH*
-
-* Ruby 1.9: support UTF-8 case folding. #4595 *Norman Clarke*
-
-* Removes Array#rand and backports Array#sample from Ruby 1.9, thanks to Marc-Andre Lafortune. *fxn*
-
-* Ruby 1.9: Renames last_(month|year) to prev_(month|year) in Date and Time. *fxn*
-
-* Aliases Date#sunday to Date#end_of_week. *fxn*
-
-* Backports Date#>> from 1.9 so that calculations do the right thing around the calendar reform. *fxn*
-
-* Date#to_time handles properly years in the range 0..138. *fxn*
-
-* Deprecate {{}} as interpolation syntax for I18n in favor of %{} *José Valim*
-
-* Array#to_xml is more powerful and able to handle the same types as Hash#to_xml #4490 *Neeraj Singh*
-
-* Harmonize the caching API and refactor the backends. #4452 *Brian Durand*
- All caches:
- * Add default options to initializer that will be sent to all read, write, fetch, exist?, increment, and decrement
- * Add support for the :expires_in option to fetch and write for all caches. Cache entries are stored with the create timestamp and a ttl so that expiration can be handled independently of the implementation.
- * Add support for a :namespace option. This can be used to set a global prefix for cache entries.
- * Deprecate expand_cache_key on ActiveSupport::Cache and move it to ActionController::Caching and ActionDispatch::Http::Cache since the logic in the method used some Rails specific environment variables and was only used by ActionPack classes. Not very DRY but there didn't seem to be a good shared spot and ActiveSupport really shouldn't be Rails specific.
- * Add support for :race_condition_ttl to fetch. This setting can prevent race conditions on fetch calls where several processes try to regenerate a recently expired entry at once.
- * Add support for :compress option to fetch and write which will compress any data over a configurable threshold.
- * Nil values can now be stored in the cache and are distinct from cache misses for fetch.
- * Easier API to create new implementations. Just need to implement the methods read_entry, write_entry, and delete_entry instead of overwriting existing methods.
- * Since all cache implementations support storing objects, update the docs to state that ActiveCache::Cache::Store implementations should store objects. Keys, however, must be strings since some implementations require that.
- * Increase test coverage.
- * Document methods which are provided as convenience but which may not be universally available.
-
- MemoryStore:
- * MemoryStore can now safely be used as the cache for single server sites.
- * Make thread safe so that the default cache implementation used by Rails is thread safe. The overhead is minimal and it is still the fastest store available.
- * Provide :size initialization option indicating the maximum size of the cache in memory (defaults to 32Mb).
- * Add prune logic that removes the least recently used cache entries to keep the cache size from exceeding the max.
- * Deprecated SynchronizedMemoryStore since it isn't needed anymore.
-
- FileStore:
- * Escape key values so they will work as file names on all file systems, be consistent, and case sensitive
- * Use a hash algorithm to segment the cache into sub directories so that a large cache doesn't exceed file system limits.
- * FileStore can be slow so implement the LocalCache strategy to cache reads for the duration of a request.
- * Add cleanup method to keep the disk from filling up with expired entries.
- * Fix increment and decrement to use file system locks so they are consistent between processes.
-
- MemCacheStore:
- * Support all keys. Previously keys with spaces in them would fail
- * Deprecate CompressedMemCacheStore since it isn't needed anymore (use :compress => true)
-
-* JSON: encode objects that don't have a native JSON representation using to_hash, if available, instead of instance_values (the old fallback) or to_s (other encoders' default). Encode BigDecimal and Regexp encode as strings to conform with other encoders. Try to transcode non-UTF-8 strings. *Jeremy Kemper*
-
-* HashWithIndifferentAccess: remove inherited symbolize_keys! since its keys are always strings. *Santiago Pastorino*
-
-* Improve transliteration quality. #4374 *Norman Clarke*
-
-* Speed up and add Ruby 1.9 support for ActiveSupport::Multibyte::Chars#tidy_bytes. #4350 *Norman Clarke*
-
-* Reduced load time by deferring configuration of classes using
- ActiveSupport::on_load(:component_name) *YK*
-
-* Rename #metaclass to #singleton_class now that ruby-core has decided *JK*
-
-* New assertions assert_blank and assert_present. #4299 *Juanjo Bazan*
-
-* Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. *Jeremy Kemper*
-
-* JSON backend for YAJL. Preferred if available. #2666 *Brian Lopez*
-
-* Introduce class_attribute to declare inheritable class attributes. Writing an attribute on a subclass behaves just like overriding the superclass reader method. Unifies and replaces most usage of cattr_accessor, class_inheritable_attribute, superclass_delegating_attribute, and extlib_inheritable_attribute. *Jeremy Kemper, Yehuda Katz*
-
-* Time#- with a DateTime argument behaves the same as with a Time argument, i.e. returns the difference between self and arg as a Float #3476 *Geoff Buesing*
-
-* YAML serialization for OrderedHash. #3608 *Gregor Schmidt*
-
-* Update bundled TZInfo to v0.3.16 *Geoff Buesing*
-
-* Georgetown TimeZone is now mapped to "America/Guyana" instead of "America/Argentina/San_Juan" #1821 *Geoff Buesing, Reuben Sivan*
-
-* Changed the default ActiveSupport.use_standard_json_time_format from false to true and
- ActiveSupport.escape_html_entities_in_json from true to false to match previously announced Rails 3 defaults *DHH*
-
-* Added Object#presence that returns the object if it's #present? otherwise returns nil *DHH/Colin Kelley*
-
-* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls *DHH*
-
-* Update Edinburgh TimeZone to use "Europe/London" instead of "Europe/Dublin" #3310 *Phil Ross*
-
-* Update bundled TZInfo to v0.3.15 *Geoff Buesing*
-
-* JSON: +Object#to_json+ calls +as_json+ to coerce itself into something natively encodable like +Hash+, +Integer+, or +String+. Override +as_json+ instead of +to_json+ so you're JSON library agnostic. *Jeremy Kemper*
-
-* String #to_time and #to_datetime: handle fractional seconds #864 *Jason Frey*
-
-* Update bundled TZInfo to v0.3.13 *Geoff Buesing*
-
-* Allow MemCacheStore to be initialized with a MemCache-like object instead of addresses and options *Bryan Helmkamp*
-
-* Change spelling of Kyev timezone to Kyiv #2613 *Alexander Dymo*
-
-* Add ActiveSupport.parse_json_times to disable time parsing in JSON backends that don't support it or don't need it. *rick*
-
-* Add pluggable JSON backends with support for the JSON gem. *rick*
- Example: ActiveSupport::JSON.backend = "JSONGem"
-
- All internal Rails JSON encoding is now handled by ActiveSupport::JSON.encode(). Use of #to_json is not recommended, as it may clash with other libraries that overwrite it. However, you can recover Rails specific functionality
- if you really want to use #to_json.
-
- gem 'json'
- ActiveSupport::JSON.backend = "JSONGem"
-
- class ActiveRecord::Base
- alias to_json rails_to_json
- end
-
-* require 'active_support' no longer orders the whole menu of core extensions. Ask for just what you need: e.g. require 'active_support/core/time' to use timezones, durations, and stdlib date/time extensions. *Jeremy Kemper*
-
-* Removed rarely-used DRb cache store. *Jeremy Kemper*
-
-* TimeWithZone.name returns 'Time', to further thwart type checking *Geoff Buesing*
-
-* Time.local instances: Adding 24.hours across the DST boundary adds 24 hours instead of one day #2066 *Michael Curtis*
-
-
-## 2.3.2 Final (March 15, 2009) ##
-
-* XmlMini supports LibXML and Nokogiri backends. #2084, #2190 *Bart ten Brinke, Aaron Patterson*
- Example: XmlMini.backend = 'Nokogiri'
-
-* Vendorize i18n 0.1.3 gem (fixes issues with incompatible character encodings in Ruby 1.9) #2038 *Akira Matsuda*
-
-* Update bundled memcache-client from 1.5.0.5 to 1.6.4.99. See http://www.mikeperham.com/2009/02/15/memcache-client-performance/ *Mike Perham*
-
-* Ruby 1.9.1p0 fix: URI.unescape can decode multibyte chars. #2033 *MOROHASHI Kyosuke*
-
-* Time#to_s(:rfc822) uses #formatted_offset instead of unreliable and non-standard %z directive #1899 *Zachary Zolton*
-
-* Make TimeWithZone#to_formatted_s an alias to TimeWithZone#to_s #1796 *Levin Alexander*
-
-* Introduce Array.wrap(foo) to wrap the argument in an array unless it's already an array. Wraps nil as an empty array. Use instead of Array(foo) and foo.to_a since they treat String as Enumerable. *Jeremy Kemper*
-
-* TimeWithZone#xmlschema accepts optional fraction_digits argument [#1725 state:resolved] *Nicholas Dainty*
-
-* Object#tap shim for Ruby < 1.8.7. Similar to Object#returning, tap yields self then returns self. *Jeremy Kemper*
- array.select { ... }.tap(&:inspect).map { ... }
-
-* TimeWithZone#- gives correct result with wrapped DateTime, and with DateTime argument *Geoff Buesing*
-
-* Updated i18n gem to version 0.1.1 #1635 *Yaroslav Markin*
-
-* Add :allow_nil option to delegate. #1127 *Sergio Gil*
-
-* Add Benchmark.ms convenience method to benchmark realtime in milliseconds. *Jeremy Kemper*
-
-* Updated included memcache-client to the 1.5.0.5 version which includes fixes from fiveruns and 37signals to deal with failover and timeouts #1535 *Joshua Sierles*
-
-* Multibyte: add multibyte-safe Chars#ord rather than falling back to String#ord. #1483 *Jason Cheow*
-
-* I18n support for Array#to_sentence. Introduces support.array.words_connector, .two_words_connector, and .last_word_connector translation keys. #1397 *Akira Matsuda*
-
-* Added ActiveSupport::OrderedHash#each_key and ActiveSupport::OrderedHash#each_value #1410 *Christoffer Sawicki*
-
-* Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. *Michael Koziarski*
-
-* Added ActiveSupport::BacktraceCleaner to cut down on backtrace noise according to filters and silencers *David Heinemeier Hansson*
-
-* Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) *Chris Wanstrath*
-
-* Added Enumerable#none? to check that none of the elements match the block #1408 *Damian Janowski*
-
-* TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date *Geoff Buesing*
-
-* Update bundled TZInfo to 0.3.12 *Geoff Buesing*
-
-* Added lambda merging to OptionMerger (especially useful with named_scope and with_options) #726 *Paweł Kondzior*
-
-
-## 2.2.1 RC2 (November 14th, 2008) ##
-
-* Increment the version of our altered memcache-client to prevent confusion caused when the 1.5.0 gem is installed.
-
-* Fixed the option merging in Array#to_xml #1126 *Rudolf Gavlas*
-
-* Make I18n::Backend::Simple reload its translations in development mode *David Heinemeier Hansson/Sven Fuchs*
-
-
-## 2.2.0 RC1 (October 24th, 2008) ##
-
-* TimeWithZone#freeze: preload instance variables so that we can actually freeze *Geoff Buesing*
-
-* Fix Brasilia timezone #1180 *Marcus Derencius, Kane*
-
-* Time#advance recognizes fractional days and weeks. Deprecate Durations of fractional months and years #970 *Tom Lea*
-
-* Add ActiveSupport::Rescuable module abstracting ActionController::Base rescue_from features. *Norbert Crombach, Pratik Naik*
-
-* Switch from String#chars to String#mb_chars for the unicode proxy. *Manfred Stienstra*
-
- This helps with 1.8.7 compatibility and also improves performance for some operations by reducing indirection.
-
-* TimeWithZone #wday, #yday and #to_date avoid trip through #method_missing *Geoff Buesing*
-
-* Added Time, Date, DateTime and TimeWithZone #past?, #future? and #today? #720 *Clemens Kofler, Geoff Buesing*
-
-* Fixed Sri Jayawardenepura time zone to map to Asia/Colombo *Jamis Buck*
-
-* Added Inflector#parameterize for easy slug generation ("Donald E. Knuth".parameterize => "donald-e-knuth") #713 *Matt Darby*
-
-* Changed cache benchmarking to be reported in milliseconds *David Heinemeier Hansson*
-
-* Fix Ruby's Time marshaling bug in pre-1.9 versions of Ruby: utc instances are now correctly unmarshaled with a utc zone instead of the system local zone [#900 state:resolved] *Luca Guidi, Geoff Buesing*
-
-* Add Array#in_groups which splits or iterates over the array in specified number of groups. #579. [Adrian Mugnolo] Example:
-
- a = (1..10).to_a
- a.in_groups(3) # => [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
- a.in_groups(3, false) # => [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
-
-* Fix TimeWithZone unmarshaling: coerce unmarshaled Time instances to utc, because Ruby's marshaling of Time instances doesn't respect the zone *Geoff Buesing*
-
-* Added Memoizable mixin for caching simple lazy loaded attributes *Josh Peek*
-
-* Move the test related core_ext stuff out of core_ext so it's only loaded by the test helpers. *Michael Koziarski*
-
-* Add Inflection rules for String#humanize. #535 *Dan Manges*
-
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.human(/_cnt$/i, '\1_count')
- end
-
- 'jargon_cnt'.humanize # => 'Jargon count'
-
-* TimeWithZone: when crossing DST boundary, treat Durations of days, months or years as variable-length, and all other values as absolute length. A time + 24.hours will advance exactly 24 hours, but a time + 1.day will advance 23-25 hours, depending on the day. Ensure consistent behavior across all advancing methods *Geoff Buesing*
-
-* Added TimeZone #=~, to support matching zones by regex in time_zone_select. #195 *Ernie Miller*
-
-* Added Array#second through Array#fifth as aliases for Array#[1] through Array#[4] + Array#forty_two as alias for Array[41] *David Heinemeier Hansson*
-
-* Added test/do declaration style testing to ActiveSupport::TestCase *DHH via Jay Fields*
-
-* Added Object#present? which is equivalent to !Object#blank? *David Heinemeier Hansson*
-
-* Added Enumberable#many? to encapsulate collection.size > 1 *David Heinemeier Hansson/Damian Janowski*
-
-* Add more standard Hash methods to ActiveSupport::OrderedHash *Steve Purcell*
-
-* Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under ActiveSupport *Josh Peek*
-
-* Added StringInquirer for doing things like StringInquirer.new("production").production? # => true and StringInquirer.new("production").development? # => false *David Heinemeier Hansson*
-
-* Fixed Date#end_of_quarter to not blow up on May 31st [#289 state:resolved] (Danger)
-
-
-## 2.1.0 (May 31st, 2008) ##
-
-* TimeZone#to_s shows offset as GMT instead of UTC, because GMT will be more familiar to end users (see time zone selects used by Windows OS, google.com and yahoo.com.) Reverts [8370] *Geoff Buesing*
-
-* Hash.from_xml: datetime xml types overflow to Ruby DateTime class when out of range of Time. Adding tests for utc offsets *Geoff Buesing*
-
-* TimeWithZone #+ and #- : ensure overflow to DateTime with Numeric arg *Geoff Buesing*
-
-* Time#to_json: don't convert to utc before encoding. References #175 *Geoff Buesing*
-
-* Remove unused JSON::RESERVED_WORDS, JSON.valid_identifier? and JSON.reserved_word? methods. Resolves #164. *Cheah Chu Yeow*
-
-* Adding Date.current, which returns Time.zone.today if config.time_zone is set; otherwise returns Date.today *Geoff Buesing*
-
-* TimeWithZone: date part getter methods (#year #mon #day etc) are defined on class; no longer relying on method_missing *Geoff Buesing*
-
-* Time.zone.parse return nil for strings with no date information *Geoff Buesing*
-
-* Time.zone.parse respects offset information in string. Resolves #105. *Scott Fleckenstein, Geoff Buesing*
-
-* Added Ruby 1.8 implementation of Process.daemon
-
-* Duration #since and #ago with no argument (e.g., 5.days.ago) return TimeWithZone when config.time_zone is set. Introducing Time.current, which returns Time.zone.now if config.time_zone is set, otherwise just returns Time.now *Geoff Buesing*
-
-* Time#since behaves correctly when passed a Duration. Closes #11527 *kemiller*
-
-* Add #getutc alias for DateTime#utc *Geoff Buesing*
-
-* Refactor TimeWithZone: don't send #since, #ago, #+, #-, #advance through method_missing *Geoff Buesing*
-
-* TimeWithZone respects config.active_support.use_standard_json_time_format *Geoff Buesing*
-
-* Add config.active_support.escape_html_entities_in_json to allow disabling of html entity escaping. *Rick Olson*
-
-* Improve documentation. *Xavier Noria*
-
-* Modified ActiveSupport::Callbacks::Callback#call to accept multiple arguments.
-
-* Time #yesterday and #tomorrow behave correctly crossing DST boundary. Closes #7399 *sblackstone*
-
-* TimeWithZone: Adding tests for dst and leap day edge cases when advancing time *Geoff Buesing*
-
-* TimeWithZone#method_missing: send to utc to advance with dst correctness, otherwise send to time. Adding tests for time calculations methods *Geoff Buesing*
-
-* Add config.active_support.use_standard_json_time_format setting so that Times and Dates export to ISO 8601 dates. *Rick Olson*
-
-* TZInfo: Removing unneeded TimezoneProxy class *Geoff Buesing*
-
-* TZInfo: Removing unneeded TimezoneIndexDefinition, since we're not including Indexes::Timezones *Geoff Buesing*
-
-* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled *Geoff Buesing*
-
-* Bundling abbreviated version of TZInfo gem 0.3.8: only the classes and zone definitions required to support Rails time zone features are included. If a recent version of the full TZInfo gem is installed, this will take precedence over the bundled version *Geoff Buesing*
-
-* TimeWithZone#marshal_load does zone lookup via Time.get_zone, so that tzinfo/Olson identifiers are handled *Geoff Buesing*
-
-* Time.zone= accepts TZInfo::Timezone instances and Olson identifiers; wraps result in TimeZone instance *Geoff Buesing*
-
-* TimeWithZone time conversions don't need to be wrapped in TimeOrDateTime, because TZInfo does this internally *Geoff Buesing*
-
-* TimeWithZone#usec returns 0 instead of error when DateTime is wrapped *Geoff Buesing*
-
-* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
-
-* Ensure that TimeWithZone#to_yaml works when passed a YAML::Emitter. *Rick Olson*
-
-* Ensure correct TimeWithZone#to_date *Geoff Buesing*
-
-* Make TimeWithZone work with tzinfo 0.2.x: use TZInfo::Timezone#zone_identifier alias for #abbreviation, silence warnings on tests. Raise LoadError when TZInfo version is < 0.2 by sniffing for TZInfo::TimeOrDateTime constant. Move all tzinfo-dependent TimeZone tests into uses_tzinfo block *Geoff Buesing*
-
-* Time, DateTime and TimeWithZone #in_time_zone defaults to Time.zone. Removing now unneeded #in_current_time_zone *Geoff Buesing*
-
-* TZInfo caches Timezone instances in its own internal hash cache, so TimeZone::MAPPING doesn't need to cache them as well *Geoff Buesing*
-
-* Adding TimeZone#parse *Geoff Buesing*
-
-* Adding TimeZone#at and DateTime#to_f *Geoff Buesing*
-
-* TimeWithZone responds to Ruby 1.9 weekday-named query methods *Geoff Buesing*
-
-* TimeWithZone caches TZInfo::TimezonePeriod used for time conversion so that it can be reused, and enforces DST rules correctly when instance is created from a local time *Geoff Buesing*
-
-* Fixed that BufferedLogger should create its own directory if one doesn't already exist #11285 *lotswholetime*
-
-* Fix Numeric time tests broken by DST change by anchoring them to fixed times instead of Time.now. Anchor TimeZone#now DST test to time specified with Time.at instead of Time.local to work around platform differences with Time.local and DST representation *Geoff Buesing*
-
-* Removing unneeded #change_time_zone method from Time, DateTime and TimeWithZone *Geoff Buesing*
-
-* TimeZone #local and #now correctly enforce DST rules *Geoff Buesing*
-
-* TimeWithZone instances correctly enforce DST rules. Adding TimeZone#period_for_utc *Geoff Buesing*
-
-* test_time_with_datetime_fallback expects DateTime.local_offset instead of DateTime.now.offset *Geoff Buesing*
-
-* Adding TimeWithZone #marshal_dump and #marshal_load *Geoff Buesing*
-
-* Add OrderedHash#to_hash *Josh Peek*
-
-* Adding Time#end_of_day, _quarter, _week, and _year. #9312 *Juanjo Bazan, Tarmo Tänav, BigTitus*
-
-* Adding TimeWithZone#between? *Geoff Buesing*
-
-* Time.=== returns true for TimeWithZone instances *Geoff Buesing*
-
-* TimeWithZone #+ and #- behave consistently with numeric arguments regardless of whether wrapped time is a Time or DateTime; consistenty answers false to #acts_like?(:date) *Geoff Buesing*
-
-* Add String#squish and String#squish! to remove consecutive chunks of whitespace. #11123 *Jordi Bunster, Henrik N*
-
-* Serialize BigDecimals as Floats when using to_yaml. #8746 *Ernesto Jimenez*
-
-* Adding TimeWithZone #to_yaml, #to_datetime, #eql? and method aliases for duck-typing compatibility with Time *Geoff Buesing*
-
-* TimeWithZone #in_time_zone returns +self+ if zone argument is the same as #time_zone *Geoff Buesing*
-
-* Adding TimeWithZone #to_a, #to_f, #to_i, #httpdate, #rfc2822 *Geoff Buesing*
-
-* Pruning unneeded TimeWithZone#change_time_zone_to_current *Geoff Buesing*
-
-* Time#zone=, #in_time_zone and #change_time_zone accept a Duration *Geoff Buesing*
-
-* Time#in_time_zone handles Time.local instances correctly *Geoff Buesing*
-
-* Pruning unneeded Time#change_time_zone_to_current. Enhanced docs to #change_time_zone to explain the difference between this method and #in_time_zone *Geoff Buesing*
-
-* TimeZone#new method renamed #local; when used with Time.zone, constructor now reads: Time.zone.local() *Geoff Buesing*
-
-* Added Base64.encode64s to encode values in base64 without the newlines. This makes the values immediately usable as URL parameters or memcache keys without further processing *David Heinemeier Hansson*
-
-* Remove :nodoc: entries around the ActiveSupport test/unit assertions. #10946 *dancroak, jamesh*
-
-* Add Time.zone_default accessor for setting the default time zone. Rails::Configuration.time_zone sets this. #10982 *Geoff Buesing*
-
-* cache.fetch(key, :force => true) to force a cache miss. *Jeremy Kemper*
-
-* Support retrieving TimeZones with a Duration. TimeZone[-28800] == TimeZone[-480.minutes]. *Rick Olson*
-
-* TimeWithZone#- added, so that #- can handle a Time or TimeWithZone argument correctly *Geoff Buesing*
-
-* with_timezone test helper renamed with_env_tz, to distinguish between setting ENV['TZ'] and setting Time.zone in tests *Geoff Buesing*
-
-* Time#- coerces TimeWithZone argument to a Time instance so that difference in seconds can be calculated. Closes #10914 *Geoff Buesing, yyyc514*
-
-* Adding UTC zone to TimeZone; TimeWithZone no longer has to fake UTC zone with nil *Geoff Buesing*
-
-* Time.get_zone refactored to private method, given that the encapsulated logic is only useful internally *Geoff Buesing*
-
-* Time.zone uses thread-local variable for thread safety. Adding Time.use_zone, for overriding Time.zone locally inside a block. Removing unneeded Time.zone_reset! *Geoff Buesing*
-
-* TimeZone#to_s uses UTC rather than GMT; reapplying change that was undone in [8679]. #1689 *Cheah Chu Yeow*
-
-* Time.days_in_month defaults to current year if no year is supplied as argument #10799 [Radar], uses Date.gregorian_leap? to determine leap year, and uses constant lookup to determine days in month *Geoff Buesing*
-
-* Adding Time and DateTime #compare_with_coercion, which layers behavior on #<=> so that any combination of Time, DateTime and ActiveSupport::TimeWithZone instances can be chronologically compared *Geoff Buesing*
-
-* TimeZone#now returns an ActiveSupport::TimeWithZone *Geoff Buesing*
-
-* Time #in_current_time_zone and #change_time_zone_to_current return self when Time.zone is nil *Geoff Buesing*
-
-* Remove unneeded #to_datetime_default_s alias for DateTime#to_s, given that we inherit a #to_default_s from Date that does exactly the same thing *Geoff Buesing*
-
-* Refactor Time and DateTime #to_formatted_s: use ternary instead of nested if/else *Geoff Buesing*
-
-* Adding Time and DateTime #formatted_offset, for outputting +HH:MM utc offset strings with cross-platform consistency *Geoff Buesing*
-
-* Adding alternate_utc_string option to TimeZone#formatted_offset. Removing unneeded TimeZone#offset. *Geoff Buesing*
-
-* Introduce ActiveSupport::TimeWithZone, for wrapping Time instances with a TimeZone. Introduce instance methods to Time for creating TimeWithZone instances, and class methods for managing a global time zone. *Geoff Buesing*
-
-* Replace non-dst-aware TimeZone class with dst-aware class from tzinfo_timezone plugin. TimeZone#adjust and #unadjust are no longer available; tzinfo gem must now be present in order to perform time zone calculations, via #local_to_utc and #utc_to_local methods. *Geoff Buesing*
-
-* Extract ActiveSupport::Callbacks from Active Record, test case setup and teardown, and ActionController::Dispatcher. #10727 *Josh Peek*
-
-* Introducing DateTime #utc, #utc? and #utc_offset, for duck-typing compatibility with Time. Closes #10002 *Geoff Buesing*
-
-* Time#to_json uses Numeric#to_utc_offset_s to output a cross-platform-consistent representation without having to convert to DateTime. References #9750 *Geoff Buesing*
-
-* Refactor number-to-HH:MM-string conversion logic from TimeZone#formatted_offset to a reusable Numeric#to_utc_offset_s method. *Geoff Buesing*
-
-* Continue evolution toward ActiveSupport::TestCase. #10679 *Josh Peek*
-
-* TestCase: introduce declared setup and teardown callbacks. Pass a list of methods and an optional block to call before setup or after teardown. Setup callbacks are run in the order declared; teardown callbacks are run in reverse. *Jeremy Kemper*
-
-* Added ActiveSupport::Gzip.decompress/compress(source) as an easy wrapper for Zlib *Tobias Lütke*
-
-* Included MemCache-Client to make the improved ActiveSupport::Cache::MemCacheStore work out of the box *Bob Cottrell, Eric Hodel*
-
-## Added ActiveSupport::Cache:: framework as an extraction from ActionController::Caching::Fragments:: David Heinemeier Hansson ##
-
-* Fixed String#titleize to work for strings with 's too #10571 *trek*
-
-* Changed the implementation of Enumerable#group_by to use a double array approach instead of a hash such that the insert order is honored *David Heinemeier Hansson/Marcel Molina Jr.*
-
-* remove multiple enumerations from ActiveSupport::JSON#convert_json_to_yaml when dealing with date/time values. *Rick Olson*
-
-* Hash#symbolize_keys skips keys that can't be symbolized. #10500 *Brad Greenlee*
-
-* Ruby 1.9 compatibility. #1689, #10466, #10468, #10554, #10594, #10632 *Cheah Chu Yeow, Pratik Naik, Jeremy Kemper, Dirkjan Bussink, Xavier Noria*
-
-* TimeZone#to_s uses UTC rather than GMT. #1689 *Cheah Chu Yeow*
-
-* Refactor of Hash#symbolize_keys! to use Hash#replace. Closes #10420 *ReinH*
-
-* Fix HashWithIndifferentAccess#to_options! so it doesn't clear the options hash. Closes #10419 *ReinH*
-
-
-## 2.0.1 (December 7th, 2007) ##
-
-* Added Array#from and Array#to that behaves just from String#from and String#to *David Heinemeier Hansson*
-
-* Fix that empty collections should be treated as empty arrays regardless of whitespace for Hash#from_xml #10255 *adamj*
-
-* Time#time_with_datetime_fallback, Time#to_datetime, Date#to_datetime and String#to_datetime honor Ruby's default calendar reform setting. #10201 *Geoff Buesing*
-
-* Change Time and DateTime #end_of_month to return last second of month instead of beginning of last day of month. Closes #10200 *Geoff Buesing*
-
-* Speedup String#blank? *Jeremy Kemper, Michael Koziarski*
-
-* Add documentation for Hash#diff. Closes #9306 *Tarmo Tänav*
-
-* Add new superclass_delegating_accessors. Similar to class inheritable attributes but with subtly different semantics. *Michael Koziarski, Tarmo Tänav*
-
-* Change JSON to encode %w(< > &) as 4 digit hex codes to be in compliance with the JSON spec. Closes #9975 *Josh Peek, Cheah Chu Yeow, Tim Pope*
-
-* Fix JSON encoding/decoding bugs dealing with /'s. Closes #9990 *Rick Olson, theamazingrando*
-
-* Introduce a base class for all test cases used by rails applications. ActiveSupport::TestCase *Michael Koziarski*
-
- The intention is to use this to reduce the amount of monkeypatching / overriding that
- is done to test/unit's classes.
-
-* Document Enumerable and Hash #to_json. #9970 *Cheah Chu Yeow*
-
-* Hash#to_xml handles symbol values. #9954 *Assaf*
-
-* Hash#symbolize_keys behaves well with integer keys. #9890 *PotatoSalad*
-
-* Multibyte: String#slice supports regexp argument. #9646 *yob*
-
-* object.duplicable? returns true if object.dup is safe. False for nil, true, false, symbols, and numbers; true otherwise. #9333 *sur*
-
-* Time, Date and DateTime #advance accept :weeks option. #9866 *Geoff Buesing*
-
-* Fix Time#years_ago and #years_since from leap days. #9865 *Geoff Buesing*
-
-* Time and DateTime#advance accept :hours, :minutes, and :seconds options. #9825 *Geoff Buesing*
-
-* Fix Date#years_ago and #years_since from leap days. #9864 *Geoff Buesing*
-
-* Refactor Time and Date#months_since and #months_ago to use #advance. #9863 *Geoff Buesing*
-
-* Rebundle Builder 2.1.2 but prefer a newer RubyGem if available. *Jeremy Kemper*
-
-* Add Range#overlaps?(range), Range#include?(range), and Range#step without a block. *brandon*
-
-* Correct BufferedLogger#level? checks. #9806 *wildchild, Johan Sorensen*
-
-* String#to_xs uses Eric Wong's fast_xs extension, if available, for Builder speedup. http://bogomips.org/fast_xs/ *Jeremy Kemper*
-
-* Introduce BasicObject as Builder::BlankSlate for Ruby 1.9 forward compatibility. *Jeremy Kemper*
-
-* Unbundle Builder in favor of a gem dependency. *Jeremy Kemper*
-
-* Disambiguate Time, Date, and DateTime#to_json formatting. #9750 *Geoff Buesing, Cheah Chu Yeow*
-
-* Hash#to_json takes :only or :except options to specific or omit certain hash keys. Enumerable#to_json passes through its options to each element. #9751 *Cheah Chu Yeow*
-
-* BufferedLogger#auto_flushing = N flushes the log every N messages. Buffers with an array instead of string. Disabling auto_flushing still flushes when the buffer hits a maximum size, as a failsafe against memory-gobbling. *Jeremy Kemper*
-
-* Fixed Date#xmlschema for dates outside the range of what can be created with Time #9744 *Geoff Buesing*
-
-* Fixed that La Paz was included in -25200 and -14400 offsets when it should only be in -14400 #9735 *bermi*
-
-* Fixed JSON encoding to use quoted keys according to the JSON standard. #8762 *choonkat, Cheah Chu Yeow*
-
-* Alias Object#send to send! for Ruby 1.9 forward compatibility. *Jeremy Kemper*
-
-* Backport Object#instance_variable_defined? for Ruby < 1.8.6. *Jeremy Kemper*
-
-* BufferedLogger#add converts the message to a string. #9702, #9724 *eigentone, DrMark, Tom Ward*
-
-* Added ActiveSupport::BufferedLogger as a duck-typing alternative (albeit with no formatter) to the Ruby Logger, which provides a very nice speed bump (inspired by Ezra's buffered logger) *David Heinemeier Hansson*
-
-* Object#instance_exec produces fewer garbage methods. *Mauricio Fernandez*
-
-* Decode json strings as Dates/Times if they're using a YAML-compatible format. Closes #9614 *Rick Olson*
-
-* Fixed cache_page to use the request url instead of the routing options when picking a save path. #8614 *Josh Peek*
-
-* Object.subclasses_of includes anonymous subclasses. *Jeremy Kemper*
-
-* Fixed that pluralizing an empty string should return the same empty string, not "s". #7720 *Josh Peek*
-
-* Added call to inspect on non-string classes for the logger #8533 *Coda Hale*
-
-* Deprecation: remove deprecated :mday option from Time, Date, and DateTime#change. *Jeremy Kemper*
-
-* Fix JSON decoder with nested quotes and commas. #9579 *Zach Dennis*
-
-* Hash#to_xml doesn't double-unescape. #8806 *Ezran*
-
-* Added Array#rand #9170 [Norbert Crombach]. Examples:
-
- [].rand # => nil
- ['a'].rand # => 'a'
- [1,2,3].rand # => 1 or 2 or 3
-
-* Deprecation: removed Reloadable. *Jeremy Kemper*
-
-* Make the utf-handler return the correct value for non-matching regular expressions. Closes #9049 *Manfred Stienstra*
-
-* Add ljust, rjust and center to utf8-handler. Closes #9165 *Manfred Stienstra*
-
-* Fix Time#advance bug when trying to advance a year from leap day. Closes #8655 *Geoff Buesing*
-
-* Add support for []= on ActiveSupport::Multibyte::Chars. Closes #9142. *ewan, Manfred Stienstra*
-
-* Added Array#extract_options! to encapsulate the pattern of getting an options hash out of a variable number of parameters. #8759 *Norbert Crombach*
-
-* Let alias_attribute work with attributes with initial capital letters (legacy columns etc). Closes #8596 *mpalmer*
-
-* Added Hash#except which is the inverse of Hash#slice -- return the hash except the keys that are specified *David Heinemeier Hansson*
-
-* Added support for pluralization with a different starting letter than the singular version (cow/kine) #4929 *norri_b/Josh Susser*
-
-* Demote Hash#to_xml to use XmlSimple#xml_in_string so it can't read files or stdin. #8453 *candlerb, Jeremy Kemper*
-
-* Backport clean_logger changes to support ruby 1.8.2 *Mislav Marohnić*
-
-* Added proper handling of arrays #8537 *Josh Susser*
-
- Before:
- Hash.from_xml '<images></images>'
- # => {:images => nil}
-
- Hash.from_xml '<images><image>foo.jpg</image></images>'
- # => {:images => {:image => "foo.jpg"}}
-
- Hash.from_xml '<images><image>foo.jpg</image><image>bar.jpg</image></images>'
- # => {:images => {:image => ["foo.jpg", "bar.jpg"]}}
-
- After:
- Hash.from_xml '<images type="array"></images>'
- # => {:images => []}
-
- Hash.from_xml '<images type="array"><image>foo.jpg</image></images>'
- # => {:images => ["foo.jpg"]}
-
- Hash.from_xml '<images type="array"><image>foo.jpg</image><image>bar.jpg</image></images>'
- # => {:images => ["foo.jpg", "bar.jpg"]}
-
-* Improve Time and Date test coverage. #8646 *Josh Peek*
-
-* Add Date#since, ago, beginning_of_day, and end_of_day. Date + seconds works now. #8575 *Geoff Buesing*
-
-* String#to_time overflows to DateTime. Add String#to_datetime. #8572 *Geoff Buesing*
-
-* Date.yesterday and .tomorrow. #8571 *Geoff Buesing*
-
-* Readable Date and DateTime#inspect. #8570 *Geoff Buesing*
-
-* Move common DateTime calculations to Date. #8536 *Geoff Buesing*
-
-* Added Date#change (like Time#change) *David Heinemeier Hansson*
-
-* DateTime#to_time converts to Time unless out of range. #8512 *Geoff Buesing*
-
-* Date#to_datetime, #to_s(:rfc822). #8512 *Geoff Buesing*
-
-* Time durations use since instead of + for accuracy. #8513 *Geoff Buesing*
-
-* escape <'s and >'s in JSON strings. #8371 *Rick Olson*
-
-* Inflections: MatrixTest -> MatrixTests instead of MatricesTest. #8496 *jbwiv*
-
-* Multibyte strings respond_to the String methods they proxy so they can be duck-typed. #6549 *Tuxie*
-
-* Array#to_xml yields the builder just like Hash and ActiveRecord::Base. #8472 *seth*
-
-* Date, Time, and DateTime support formatting blocks in addition to strftime strings. Introduce :long_ordinal format, e.g. "February 21st, 2005". #8191 *Coda Hale*
-
-* Document Object#blank?. #6491 *Chris Mear*
-
-* Date, Time, and DateTime#to_json. #8399 *wycats*
-
-* Simplify API of assert_difference by passing in an expression that is evaluated before and after the passed in block. See documenation for examples of new API. *Marcel Molina Jr.*
-
-* Added assert_difference and assert_no_difference to test/unit assertions *Tobias Lütke*
-
-* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back *David Heinemeier Hansson*
-
-* Added parsing of file type in Hash.xml_in so you can easily do file uploads with base64 from an API *David Heinemeier Hansson*
-
- <person>
- <name>David</name>
- <avatar type="file" name="me.jpg" content_type="image/jpg">R0lGODlhkACZAPUAAM5lcfjrtMQCG=\n</avatar>
- </person>
-
- ...becomes:
-
- attributes = { :person => { :name => "David", :avatar => #<StringIO> } }
- attributes[:person][:avatar].content_type # => "image/jpg"
- attributes[:person][:avatar].original_filename # => "me.jpg"
- attributes[:person][:avatar].read # => binary data of the file
-
- Which is duck-type compatible with the files that you get when doing multipart uploads through HTML.
-
-* Improved multibyte performance by relying less on exception raising #8159 *Blaine*
-
-* Use XSD-compatible type names for Hash#to_xml and make the converters extendable #8047 *Tim Pope*
-
-* Added yielding of builder in Hash#to_xml *David Heinemeier Hansson*
-
-* Hash#with_indifferent_access now also converts hashes kept in arrays to indifferent access (makes it easier to treat HTML and XML parameters the same) *David Heinemeier Hansson*
-
-* Hash#to_xml supports YAML attributes. #7502 *jonathan*
-
-* Refactor ActiveSupport::JSON to be less obtuse. Add support for JSON decoding by way of Syck with ActiveSupport::JSON.decode(json_string). Prevent hash keys that are JavaScript reserved words from being unquoted during encoding. *Sam Stephenson*
-
-* alias_method_chain preserves the original method's visibility. #7854 *Jonathan Viney*
-
-* Update Dependencies to ignore constants inherited from ancestors. Closes #6951. *Nicholas Seckar*
-
-* Array#to_query preserves its ordering. #7756 *Greg Spurrier*
-
-* Out-of-range Time calculations transparently overflow to DateTime. Introduce Time#to_datetime. #7706, #7715 *Geoff Buesing*
-
-* DateTime calculations analogous to the Date and Time extensions. #7693 *Geoff Buesing*
-
-* Give DateTime correct .to_s implementations, lets it play nice with ActiveRecord quoting. #7649 *Geoff Buesing*
-
-* Add File.atomic_write, allows you to write large files in an atomic manner, preventing users from seeing half written files. *Michael Koziarski*
-
-* Allow users to provide custom formatters to Logger. *Anthony Eden*
-
-* Hash#to_query CGI-escapes its keys. *Jeremy Kemper*
-
-* Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 *Bruce Perens*
-
-* :db format for Date#to_s *Jeremy Kemper*
- Date.new(2007, 1, 27).to_s(:db) # => '2007-01-27'
-
-* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. *Rick Olson*
-
-* Added Hash#to_query to turn a hash of values into a form-encoded query string *Nicholas Seckar*
-
-* Increase test coverage for subclasses_of. Closes #7335. *Roman2K, Nicholas Seckar*
-
-* Remove unused code from Duration#inspect. Closes #7180. *Rich Collins*
-
-* Added test coverage for Inflector.inflections.clear. Closes #7179. *Rich Collins*
-
-* ActiveSupport::Multibyte::Handlers::UTF8Handler should raise when a range and an integer are passed in (just like the native implementation). Closes #7176 *Rich Collins*
-
-* A couple extra tests for #classify. Closes #7273. *Josh Susser*
-
-* Better docs for Object extensions *zackchandler, Jamis Buck*
-
-* Fix that Dates couldn't be subtracted from Dates after [5940]. *Sam Stephenson*
-
-* Add Object#acts_like? and Time#acts_like_time? and Date#acts_like_date? to facilitate duck-typing. *Jamis Buck*
-
-* Make 1.months and friends accurate by introducing a Duration class. #6835 *eventualbuddha*
-
-
-## 1.4.2 (March 12th, 2007) ##
-
-* Ruby 1.8.6 and 1.9 define private Time#to_date and #to_datetime; make them
- public for compatibility. *Jeremy Kemper*
-
-* Deprecation: warn on stderr if RAILS_DEFAULT_LOGGER isn't set yet. *Jeremy Kemper*
-
-
-## 1.4.1 (February 5th, 2007) ##
-
-* Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 *Bruce Perens*
-
-* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. *Rick Olson*
-
-* Full test coverage for Inflector. #7228 *Dan Kubb*
-
-
-## 1.4.0 (January 16th, 2007) ##
-
-* Document Inflector.ordinalize and merge docs from String inflections. #7023 *smeade*
-
-* Unbundle flexmock. *Jeremy Kemper*
-
-* Fix Dependencies.autoloaded? to ignore anonymous modules. Closes #6561. *Nicholas Seckar*
-
-* Update load once paths to prevent nested once constants from being detected and claimed by an external non-once load. *Nicholas Seckar*
-
-* Deprecation: silence warnings when reporting test errors. *Jeremy Kemper*
-
-* Hash#slice(*keys) returns a new hash with only the given keys. #slice! replaces the hash with only the given keys. Works with HashWithIndifferentAccess also. *Jeremy Kemper*
-
-* HashWithIndifferentAccess#to_hash converts to a Hash with String keys and the same default value. *Jeremy Kemper*
-
-* Fix remove_constant to correctly handle constant names of the form "::A::...". References #6720. *Nicholas Seckar*
-
-* Fixed Array#to_xml when it contains a series of hashes (each piece would get its own XML declaration) #6610 *thkarcher/cyu*
-
-* Added Time#to_s(:time) which will just return H:M, like 17:44 *David Heinemeier Hansson*
-
-* Add Module#attr_accessor_with_default to initialize value of attribute before setting it. Closes #6538. *Stuart Halloway, Marcel Molina Jr.*
-
-* Hash#to_xml handles keys with the same name as Kernel methods. #6613 *Jonathan del Strother*
-
-* Added Time#end_of_day to get 23:59:59 of that day *David Heinemeier Hansson*
-
-* Don't quote hash keys in Hash#to_json if they're valid JavaScript identifiers. Disable this with ActiveSupport::JSON.unquote_hash_key_identifiers = false if you need strict JSON compliance. *Sam Stephenson*
-
-* Lazily load the Unicode Database in the UTF-8 Handler *Rick Olson*
-
-* Update dependencies to delete partially loaded constants. *Nicholas Seckar*
-
-* Fix unicode JSON regexp for Onigurama compatibility. #6494 *whitley*
-
-* update XmlSimple to 1.0.10. Closes #6532. *Nick Sieger*
-
-* Update dependencies to allow constants to be defined alongside their siblings. A common case for this is AR model classes with STI; user.rb might define User, Administrator and Guest for example. *Nicholas Seckar*
-
-* next_week respects DST changes. #6483, #5617, #2353, #2509, #4551 *marclove, Rob Biedenharn, rails@roetzel.de, jsolson@damogran.org, drbrain@segment7.net*
-
-* Expose methods added to Enumerable in the documentation, such as group_by. Closes #6170. *sergeykojin@gmail.com, Marcel Molina Jr.*
-
-* Ensure Chars#tidy_bytes only tidies broken bytes. Closes #6397 *Manfred Stienstra*
-
-* Add 'unloadable', a method used to mark any constant as requiring an unload after each request. *Nicholas Seckar*
-
-* Make core_ext/string/access.rb multibyte safe. Closes #6388 *Manfred Stienstra*
-
-* Make String#chars slicing behaviour consistent with String. Closes #6387 *Manfred Stienstra*
-
-* Pull in latest multibyte patch. Closes #6346 *Manfred Stienstra*
-
-* Add ActiveSupport::Multibyte. Provides String#chars which lets you deal with strings as a sequence of chars, not of bytes. Closes #6242 *Julian Tarkhanov, Manfred Stienstra, Thijs van der Vossen & Jan Behrens*
-
-* Fix issue with #class_inheritable_accessor saving updates to the parent class when initialized with an Array or Hash *mojombo*
-
-* Hash#to_xml supports Bignum and BigDecimal. #6313 *edibiase*
-
-* Don't undefine #class in OptionMerger *Rick Olson*
-
-* Hash.create_from_xml has been renamed to Hash.from_xml, alias will exist until Rails 2.0 *David Heinemeier Hansson*
-
-* alias_method_chain works with accessor= methods also. #6153 *Caio Chassot*
-
-* Fix loadable_constants_for_path to handle load paths that do not end with a slash. *Nicholas Seckar*
-
-* Fix logic error in determining what was loaded by a given file. Closes #6039. *Nicholas Seckar*
-
-* Equate Kernel.const_missing with Object.const_missing. Fixes #5988. *Nicholas Seckar*
-
-* Add ApplicationController special case to Dependencies. *Nicholas Seckar*
-
-* Don't pad remaining places with in_groups_of if specified padding value is false. *Marcel Molina Jr.*
-
-* Fix cases where empty xml nodes weren't being translated to nil in Hash.create_from_xml *Rick Olso n*
-
- <written-on type="date"></written-on> # => { :type => 'date' } # WRONG
- <written-on type="date"></written-on> # => nil # RIGHT
-
-* Tighten rescue clauses. #5985 *james@grayproductions.net*
-
-* Inflections: don't singularize -ies plurals. *foamdino@gmail.com, Mark Van Holstyn*
-
-* Update Initializer to use load_once_paths to avoid plugin reloading. References #5852. *Nicholas Seckar*
-
-* Use Array#assoc in ActiveSupport::OrderedHash. *Mauricio Fernandez*
-
-* Greatly increased performance of String.to_json, which speeds up RJS considerably on large pages, fixes #3473 *Shugo Maeda*
-
-* Detect missing_constants calls from removed modules and fail accordingly. *Nicholas Seckar*
-
-* Stop using defined? in Dependencies.qualified_const_defined? since defined? may invoke const_missing. *Nicholas Seckar*
-
-* Dependencies can autoload directories of nested classes. *Jeremy Kemper*
- Example:
- invoice.rb class Invoice
- invoice/lineitem.rb class Invoice::Lineitem
-
-* Add Deprecation.silence so that Reloadable does not scold itself. *Nicholas Seckar*
-
-* Add debugging logging to Dependencies. Currently can be enabled with Dependencies.log_activity = true; adding to Initializer and documenting is forthcoming. *Nicholas Seckar*
-
-* Replace Reloadable with improvements to the Dependencies mechanism. *Nicholas Seckar*
-
-* DateTime#to_time gives hour/minute/second resolution. #5747 *jon.evans@pobox.com*
-
-* attr_internal to support namespacing and deprecation. Like attr_* except backed by internally-named instance variable. Set attr_internal_naming_format to change the format from the default '@_%s'. *Jeremy Kemper*
- # def foo() @foo__rofl end
- # def foo=(v) @foo__rofl = v end
- self.attr_internal_naming_format = '@%s__rofl'
- attr_internal :foo
-
-* Raise fully qualified names upon name errors. #5533 *Lars Pind, Nicholas Seckar*
-
-* Add extention to obtain the missing constant from NameError instances. *Nicholas Seckar*
-
-* Thoroughly document inflections. #5700 *petermichaux@gmail.com*
-
-* Added Module#alias_attribute [Jamis/David Heinemeier Hansson]. Example:
-
- class Content < ActiveRecord::Base
- # has a title attribute
- end
-
- class Email < ActiveRecord::Base
- alias_attribute :subject, :title
- end
-
- e = Email.find(1)
- e.title # => "Superstars"
- e.subject # => "Superstars"
- e.subject? # => true
- e.subject = "Megastars"
- e.title # => "Megastars"
-
-* Deprecation: easier to work with warning behavior as procs; default behaviors for each environment so users needn't update env.rb; and testing pleasure with assert_deprecated, assert_not_deprecated. *Jeremy Kemper*
- By default, test prints to $stderr, dev logs, production ignores.
- Provide your own per-environment in e.g. config/environments/development.rb:
- ActiveSupport::Deprecation.behavior = Proc.new { |message| raise message }
-
-* First cut of the Rails Deprecation system. *Michael Koziarski*
-
-* Strip boolean XML content before checking for 'true' *Rick Olson*
-
-* Customize default BigDecimal formatting. References #5672 *Dave Thomas*
-
-* Correctly convert <foo nil="true"> to nil when using Hash.create_from_xml. *Rick Olson*
-
-* Optional identity for Enumerable#sum defaults to zero. #5657 *gensym@mac.com*
-
-* HashWithIndifferentAccess shouldn't confuse false and nil. #5601 *Shugo Maeda*
-
-* Fixed HashWithIndifferentAccess#default #5586 *chris@seagul.co.uk*
-
-* More compatible Hash.create_from_xml. #5523 *nunemaker@gmail.com*
-
-* Added Enumerable#sum for calculating a sum from the elements [David Heinemeier Hansson, jonathan@daikini.com]. Examples:
-
- [1, 2, 3].sum
- payments.sum { |p| p.price * p.tax_rate }
- payments.sum(&:price)
-
- This is instead of payments.inject(0) { |sum, p| sum + p.price }
-
-* Correct and clarify Array#to_sentence docs. #5458 *brad@madriska.com*
-
-* alias_method_chain preserves method punctuation so foo, foo?, and foo! may be chained with the same feature. *Jeremy Kemper*
- Example:
- alias_method_chain :save!, :validation
- is equivalent to
- alias_method :save_without_validation!, :save!
- alias_method :save!, :save_with_validation!
-
-* Enhance Symbol#to_proc so it works with list objects, such as multi-dimensional arrays. Closes #5295 [nov@yo.rim.or.jp]. Example:
-
- {1 => "one", 2 => "two", 3 => "three"}.sort_by(&:first).map(&:last)
- # => ["one", "two", "three"]
-
-* Added Hash.create_from_xml(string) which will create a hash from a XML string and even typecast if possible [David Heinemeier Hansson]. Example:
-
- Hash.create_from_xml <<-EOT
- <note>
- <title>This is a note</title>
- <created-at type="date">2004-10-10</created-at>
- </note>
- EOT
-
- ...would return:
-
- { :note => { :title => "This is a note", :created_at => Date.new(2004, 10, 10) } }
-
-* Added Jim Weirich's excellent FlexMock class to vendor (Copyright 2003, 2004 by Jim Weirich (jim@weriichhouse.org)) -- it's not automatically required, though, so require 'flexmock' is still necessary *David Heinemeier Hansson*
-
-* Fixed that Module#alias_method_chain should work with both foo? foo! and foo at the same time #4954 *anna@wota.jp*
-
-* to_xml fixes, features, and speedup: introduce :dasherize option that converts updated_at to updated-at if true (the existing default); binary columns get encoding="base64" attribute; nil values get nil="true" attribute to distinguish empty values; add type information for float columns; allow arbitrarily deep :include; include SQL type information as the type attribute. #4989 *Blair Zajac <blair@orcaware.com>*
-
-* Add OrderedHash#values. *Sam Stephenson*
-
-* Added Array#to_s(:db) that'll produce a comma-separated list of ids [David Heinemeier Hansson]. Example:
-
- Purchase.find(:all, :conditions => "product_id IN (#{shops.products.to_s(:db)})"
-
-* Normalize classify's argument to a String so that it plays nice with Symbols. *Marcel Molina Jr.*
-
-* Strip out leading schema name in classify. References #5139. *Michael Schoen*
-
-* Remove Enumerable#first_match since break(value) handles the use case well enough. *Nicholas Seckar*
-
- Enumerable#first_match was like detect, but instead of returning the matching element, the yielded value returned. For example:
-
- user_xml = adapters(:from => User, :to => Xml).first_match do |adapter|
- adapter.adapt @user
- end
-
- But this is just as easily done with:
-
- user_xml = adapters(:from => User, :to => Xml).each do
- break adapter.adapt(@user)
- end
-
-* Make Array#in_groups_of just return the grouped collection if a block isn't given. *Marcel Molina Jr.*
-
-* Don't destroy a HashWithIndifferentAccess if symbolize_keys! or stringify_keys! is called on it. Closes #5076. *Marcel Molina Jr., guy.naor@famundo.com*
-
-* Document Module::delegate. #5002 *pergesu@gmail.com*
-
-* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
-
-* Strip out punctuation on predicates or bang methods being aliased with alias_method_chain since target?_without_feature is not a valid method name. Add tests for Module#alias_method_chain. *Marcel Molina Jr.*
-
-* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
-
-* Allow default options in with_options to be overridden. Closes #4480. *murphy@cYcnus.de*
-
-* Added Module#alias_method_chain *Jamis Buck*
-
-* Updated to Builder 2.0 *David Heinemeier Hansson*
-
-* Add Array#split for dividing arrays into one or more subarrays by value or block. *Sam Stephenson*
-
-## 1.3.1 (April 6th, 2006) ##
-
-* Clean paths inside of exception messages and traces. *Nicholas Seckar*
-
-* Add Pathname.clean_within for cleaning all the paths inside of a string. *Nicholas Seckar*
-
-* provide an empty Dependencies::LoadingModule.load which prints deprecation warnings. Lets 1.0 applications function with .13-style environment.rb.
-
-
-## 1.3.0 (March 27th, 2006) ##
-
-* When possible, avoid incorrectly obtaining constants from parent modules. Fixes #4221. *Nicholas Seckar*
-
-* Add more tests for dependencies; refactor existing cases. *Nicholas Seckar*
-
-* Move Module#parent and Module#as_load_path into core_ext. Add Module#parent. *Nicholas Seckar*
-
-* Add CachingTools::HashCaching to simplify the creation of nested, autofilling hashes. *Nicholas Seckar*
-
-* Remove a hack intended to avoid unloading the same class twice, but which would not work anyways. *Nicholas Seckar*
-
-* Update Object.subclasses_of to locate nested classes. This affects Object.remove_subclasses_of in that nested classes will now be unloaded. *Nicholas Seckar*
-
-* Update Object.remove_subclasses_of to use Class.remove_class, reducing duplication. *Nicholas Seckar*
-
-* Added Fixnum#seconds for consistency, so you can say 5.minutes + 30.seconds instead of 5.minutes + 30 #4389 *François Beausoleil*
-
-* Added option to String#camelize to generate lower-cased camel case by passing in :lower, like "super_man".camelize(:lower) # => "superMan" *David Heinemeier Hansson*
-
-* Added Hash#diff to show the difference between two hashes *Chris McGrath*
-
-* Added Time#advance to do precise time time calculations for cases where a month being approximated to 30 days won't do #1860 *Rick Olson*
-
-* Enhance Inflector.underscore to convert '-' into '_' (as the inverse of Inflector.dasherize) *Jamis Buck*
-
-* Switched to_xml to use the xml schema format for datetimes. This allows the encoding of time zones and should improve operability. *Michael Koziarski*
-
-* Added a note to the documentation for the Date related Numeric extensions to indicate that they're
- approximations and shouldn't be used for critical calculations. *Michael Koziarski*
-
-* Added Hash#to_xml and Array#to_xml that makes it much easier to produce XML from basic structures [David Heinemeier Hansson]. Examples:
-
- { :name => "David", :street_name => "Paulina", :age => 26, :moved_on => Date.new(2005, 11, 15) }.to_xml
-
- ...returns:
-
- <person>
- <street-name>Paulina</street-name>
- <name>David</name>
- <age type="integer">26</age>
- <moved-on type="date">2005-11-15</moved-on>
- </person>
-
-* Moved Jim Weirich's wonderful Builder from Action Pack to Active Support (it's simply too useful to be stuck in AP) *David Heinemeier Hansson*
-
-* Fixed that Array#to_sentence will return "" on an empty array instead of ", and" #3842, #4031 *rubyonrails@beautifulpixel.com*
-
-* Add Enumerable#group_by for grouping collections based on the result of some
- block. Useful, for example, for grouping records by date.
-
- ex.
-
- latest_transcripts.group_by(&:day).each do |day, transcripts|
- p "#{day} -> #{transcripts.map(&:class) * ', '}"
- end
- "2006-03-01 -> Transcript"
- "2006-02-28 -> Transcript"
- "2006-02-27 -> Transcript, Transcript"
- "2006-02-26 -> Transcript, Transcript"
-
- Add Array#in_groups_of, for iterating over an array in groups of a certain
- size.
-
- ex.
-
- %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
- ["1", "2", "3"]
- ["4", "5", "6"]
- ["7", nil, nil]
-
- *Marcel Molina Jr., Sam Stephenson*
-
-* Added Kernel#daemonize to turn the current process into a daemon that can be killed with a TERM signal *David Heinemeier Hansson*
-
-* Add 'around' methods to Logger, to make it easy to log before and after messages for a given block as requested in #3809. [Michael Koziarski] Example:
-
- logger.around_info("Start rendering component (#{options.inspect}): ",
- "\n\nEnd of component rendering") { yield }
-
-* Added Time#beginning_of_quarter #3607 *cohen.jeff@gmail.com*
-
-* Fix Object.subclasses_of to only return currently defined objects *Jonathan Viney <jonathan@bluewire.net.nz>*
-
-* Fix constantize to properly handle names beginning with '::'. *Nicholas Seckar*
-
-* Make String#last return the string instead of nil when it is shorter than the limit [Scott Barron].
-
-* Added delegation support to Module that allows multiple delegations at once (unlike Forwardable in the stdlib) [David Heinemeier Hansson]. Example:
-
- class Account < ActiveRecord::Base
- has_one :subscription
- delegate :free?, :paying?, :to => :subscription
- delegate :overdue?, :to => "subscription.last_payment"
- end
-
- account.free? # => account.subscription.free?
- account.overdue? # => account.subscription.last_payment.overdue?
-
-* Fix Reloadable to handle the case where a class that has been 'removed' has not yet been garbage collected. *Nicholas Seckar*
-
-* Don't allow Reloadable to be included into Modules.
-
-* Remove LoadingModule. *Nicholas Seckar*
-
-* Add documentation for Reloadable::Subclasses. *Nicholas Seckar*
-
-* Add Reloadable::Subclasses which handles the common case where a base class should not be reloaded, but its subclasses should be. *Nicholas Seckar*
-
-* Further improvements to reloading code *Nicholas Seckar, Trevor Squires*
-
- - All classes/modules which include Reloadable can define reloadable? for fine grained control of reloading
- - Class.remove_class uses Module#parent to access the parent module
- - Class.remove_class expanded to handle multiple classes in a single call
- - LoadingModule.clear! has been removed as it is no longer required
- - Module#remove_classes_including has been removed in favor of Reloadable.reloadable_classes
-
-* Added reusable reloading support through the inclusion of the Relodable module that all subclasses of ActiveRecord::Base, ActiveRecord::Observer, ActiveController::Base, and ActionMailer::Base automatically gets. This means that these classes will be reloaded by the dispatcher when Dependencies.mechanism = :load. You can make your own models reloadable easily:
-
- class Setting
- include Reloadable
- end
-
- Reloading a class is done by removing its constant which will cause it to be loaded again on the next reference. *David Heinemeier Hansson*
-
-* Added auto-loading support for classes in modules, so Conductor::Migration will look for conductor/migration.rb and Conductor::Database::Settings will look for conductor/database/settings.rb *Nicholas Seckar*
-
-* Add Object#instance_exec, like instance_eval but passes its arguments to the block. (Active Support will not override the Ruby 1.9 implementation of this method.) *Sam Stephenson*
-
-* Add Proc#bind(object) for changing a proc or block's self by returning a Method bound to the given object. Based on why the lucky stiff's "cloaker" method. *Sam Stephenson*
-
-* Fix merge and dup for hashes with indifferent access #3404 *Ken Miller*
-
-* Fix the requires in option_merger_test to unbreak AS tests. *Sam Stephenson*
-
-* Make HashWithIndifferentAccess#update behave like Hash#update by returning the hash. #3419, #3425 *asnem@student.ethz.ch, JanPrill@blauton.de, Marcel Molina Jr.*
-
-* Add ActiveSupport::JSON and Object#to_json for converting Ruby objects to JSON strings. *Sam Stephenson*
-
-* Add Object#with_options for DRYing up multiple calls to methods having shared options. [Sam Stephenson] Example:
-
- ActionController::Routing::Routes.draw do |map|
- # Account routes
- map.with_options(:controller => 'account') do |account|
- account.home '', :action => 'dashboard'
- account.signup 'signup', :action => 'new'
- account.logout 'logout', :action => 'logout'
- end
- end
-
-* Introduce Dependencies.warnings_on_first_load setting. If true, enables warnings on first load of a require_dependency. Otherwise, loads without warnings. Disabled (set to false) by default. *Jeremy Kemper*
-
-* Active Support is warnings-safe. #1792 *Eric Hodel*
-
-* Introduce enable_warnings counterpart to silence_warnings. Turn warnings on when loading a file for the first time if Dependencies.mechanism == :load. Common mistakes such as redefined methods will print warnings to stderr. *Jeremy Kemper*
-
-* Add Symbol#to_proc, which allows for, e.g. [:foo, :bar].map(&:to_s). *Marcel Molina Jr.*
-
-* Added the following methods [Marcel Molina Jr., Sam Stephenson]:
- * Object#copy_instance_variables_from(object) to copy instance variables from one object to another
- * Object#extended_by to get an instance's included/extended modules
- * Object#extend_with_included_modules_from(object) to extend an instance with the modules from another instance
-
-## 1.2.5 (December 13th, 2005) ##
-
-* Become part of Rails 1.0
-
-* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
-
-## 1.2.3 (November 7th, 2005) ##
-
-* Change Inflector#constantize to use eval instead of const_get. *Nicholas Seckar*
-
-* Fix const_missing handler to ignore the trailing '.rb' on files when comparing paths. *Nicholas Seckar*
-
-* Define kernel.rb methods in "class Object" instead of "module Kernel" to work around a Windows peculiarity *Sam Stephenson*
-
-* Fix broken tests caused by incomplete loading of active support. *Nicholas Seckar*
-
-* Fix status pluralization bug so status_codes doesn't get pluralized as statuses_code. #2758 *keithm@infused.org*
-
-* Added Kernel#silence_stderr to silence stderr for the duration of the given block *Sam Stephenson*
-
-* Changed Kernel#` to print a message to stderr (like Unix) instead of raising Errno::ENOENT on Win32 *Sam Stephenson*
-
-* Changed 0.blank? to false rather than true since it violates everyone's expectation of blankness. #2518, #2705 *rails@jeffcole.net*
-
-* When loading classes using const_missing, raise a NameError if and only if the file we tried to load was not present. *Nicholas Seckar*
-
-* Added petabytes and exebytes to numeric extensions #2397 *timct@mac.com*
-
-* Added Time#end_of_month to accompany Time#beginning_of_month #2514 *Jens-Christian Fischer*
-
-
-## 1.2.2 (October 26th, 2005) ##
-
-* Set Logger.silencer = false to disable Logger#silence. Useful for debugging fixtures.
-
-* Add title case method to String to do, e.g., 'action_web_service'.titlecase # => 'Action Web Service'. *Marcel Molina Jr.*
-
-
-## 1.2.1 (October 19th, 2005) ##
-
-* Classify generated routing code as framework code to avoid appearing in application traces. *Nicholas Seckar*
-
-* Show all framework frames in the framework trace. *Nicholas Seckar*
-
-
-## 1.2.0 (October 16th, 2005) ##
-
-* Update Exception extension to show the first few framework frames in an application trace. *Nicholas Seckar*
-
-* Added Exception extension to provide support for clean backtraces. *Nicholas Seckar*
-
-* Updated whiny nil to be more concise and useful. *Nicholas Seckar*
-
-* Added Enumerable#first_match *Nicholas Seckar*
-
-* Fixed that Time#change should also reset usec when also resetting minutes #2459 *ikeda@dream.big.or.jp*
-
-* Fix Logger compatibility for distributions that don't keep Ruby and its standard library in sync.
-
-* Replace '%e' from long and short time formats as Windows does not support it. #2344. *Tom Ward <tom@popdog.net>*
-
-* Added to_s(:db) to Range, so you can get "BETWEEN '2005-12-10' AND '2005-12-12'" from Date.new(2005, 12, 10)..Date.new(2005, 12, 12) (and likewise with Times)
-
-* Moved require_library_or_gem into Kernel. #1992 *Michael Schuerig <michael@schuerig.de>*
-
-* Add :rfc822 as an option for Time#to_s (to get rfc822-formatted times)
-
-* Chain the const_missing hook to any previously existing hook so rails can play nicely with rake
-
-* Clean logger is compatible with both 1.8.2 and 1.8.3 Logger. #2263 *Michael Schuerig <michael@schuerig.de>*
-
-* Added native, faster implementations of .blank? for the core types #2286 *skae*
-
-* Fixed clean logger to work with Ruby 1.8.3 Logger class #2245
-
-* Fixed memory leak with Active Record classes when Dependencies.mechanism = :load #1704 *Chris McGrath*
-
-* Fixed Inflector.underscore for use with acronyms, so HTML becomes html instead of htm_l #2173 *k@v2studio.com*
-
-* Fixed dependencies related infinite recursion bug when a controller file does not contain a controller class. Closes #1760. *rcolli2@tampabay.rr.com*
-
-* Fixed inflections for status, quiz, move #2056 *deirdre@deirdre.net*
-
-* Added Hash#reverse_merge, Hash#reverse_merge!, and Hash#reverse_update to ease the use of default options
-
-* Added Array#to_sentence that'll turn ['one', 'two', 'three'] into "one, two, and three" #2157 *Manfred Stienstra*
-
-* Added Kernel#silence_warnings to turn off warnings temporarily for the passed block
-
-* Added String#starts_with? and String#ends_with? #2118 *Thijs van der Vossen*
-
-* Added easy extendability to the inflector through Inflector.inflections (using the Inflector::Inflections singleton class). Examples:
-
- Inflector.inflections do |inflect|
- inflect.plural /^(ox)$/i, '\1\2en'
- inflect.singular /^(ox)en/i, '\1'
-
- inflect.irregular 'octopus', 'octopi'
-
- inflect.uncountable "equipment"
- end
-
-* Added String#at, String#from, String#to, String#first, String#last in ActiveSupport::CoreExtensions::String::Access to ease access to individual characters and substrings in a string serving basically as human names for range access.
-
-* Make Time#last_month work when invoked on the 31st of a month.
-
-* Add Time.days_in_month, and make Time#next_month work when invoked on the 31st of a month
-
-* Fixed that Time#midnight would have a non-zero usec on some platforms #1836
-
-* Fixed inflections of "index/indices" #1766 *damn_pepe@gmail.com*
-
-* Added stripping of _id to String#humanize, so "employee_id" becomes "Employee" #1574 *Justin French*
-
-* Factor Fixnum and Bignum extensions into Integer extensions *Nicholas Seckar*
-
-* Hooked #ordinalize into Fixnum and Bignum classes. *Nicholas Seckar, danp*
-
-* Added Fixnum#ordinalize to turn 1.ordinalize to "1st", 3.ordinalize to "3rd", and 10.ordinalize to "10th" and so on #1724 *paul@cnt.org*
-
-
-## 1.1.1 (11 July, 2005) ##
-
-* Added more efficient implementation of the development mode reset of classes #1638 *Chris McGrath*
-
-
-## 1.1.0 (6 July, 2005) ##
-
-* Fixed conflict with Glue gem #1606 *Rick Olson*
-
-* Added new rules to the Inflector to deal with more unusual plurals mouse/louse => mice/lice, information => information, ox => oxen, virus => viri, archive => archives #1571, #1583, #1490, #1599, #1608 *foamdino@gmail.com/others*
-
-* Fixed memory leak with Object#remove_subclasses_of, which inflicted a Rails application running in development mode with a ~20KB leak per request #1289 *Chris McGrath*
-
-* Made 1.year == 365.25.days to account for leap years. This allows you to do User.find(:all, :conditions => ['birthday > ?', 50.years.ago]) without losing a lot of days. #1488 *tuxie@dekadance.se*
-
-* Added an exception if calling id on nil to WhinyNil #584 *kevin-temp@writesoon.com*
-
-* Added Fix/Bignum#multiple_of? which returns true on 14.multiple_of?(7) and false on 16.multiple_of?(7) #1464 *Thomas Fuchs*
-
-* Added even? and odd? to work with Bignums in addition to Fixnums #1464 *Thomas Fuchs*
-
-* Fixed Time#at_beginning_of_week returned the next Monday instead of the previous one when called on a Sunday #1403 *jean.helou@gmail.com*
-
-* Increased the speed of indifferent hash access by using Hash#default. #1436 *Nicholas Seckar*
-
-* Added that " " is now also blank? (using strip if available)
-
-* Fixed Dependencies so all modules are able to load missing constants #1173 *Nicholas Seckar*
-
-* Fixed the Inflector to underscore strings containing numbers, so Area51Controller becomes area51_controller #1176 *Nicholas Seckar*
-
-* Fixed that HashWithIndifferentAccess stringified all keys including symbols, ints, objects, and arrays #1162 *Nicholas Seckar*
-
-* Fixed Time#last_year to go back in time, not forward #1278 *fabien@odilat.com*
-
-* Fixed the pluralization of analysis to analyses #1295 *seattle@rootimage.msu.edu*
-
-* Fixed that Time.local(2005,12).months_since(1) would raise "ArgumentError: argument out of range" #1311 *jhahn@niveon.com*
-
-* Added silencing to the default Logger class
-
-
-## 1.0.4 (19th April, 2005) ##
-
-* Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 *Nicholas Seckar*
-
-* Fixed inflection of perspectives and similar words #1045 *Thijs van der Vossen*
-
-* Added Fixnum#even? and Fixnum#odd?
-
-* Fixed problem with classes being required twice. Object#const_missing now uses require_dependency to load files. It used to use require_or_load which would cause models to be loaded twice, which was not good for validations and other class methods #971 *Nicholas Seckar*
-
-
-## 1.0.3 (27th March, 2005) ##
-
-* Fixed Inflector.pluralize to handle capitalized words #932 *Jeremy Kemper*
-
-* Added Object#suppress which allows you to make a saner choice around with exceptions to swallow #980. Example:
-
- suppress(ZeroDivisionError) { 1/0 }
-
- ...instead of:
-
- 1/0 rescue nil # BAD, EVIL, DIRTY.
-
-
-## 1.0.2 (22th March, 2005) ##
-
-* Added Kernel#returning -- a Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.
-
- def foo
- returning values = [] do
- values << 'bar'
- values << 'baz'
- end
- end
-
- foo # => ['bar', 'baz']
-
-
-## 1.0.1 (7th March, 2005) ##
-
-* Fixed Hash#indifferent_access to also deal with include? and fetch and nested hashes #726 *Nicholas Seckar*
-
-* Added Object#blank? -- see http://redhanded.hobix.com/inspect/objectBlank.html #783 *_why the lucky stiff*
-
-* Added inflection rules for "sh" words, like "wish" and "fish" #755 *phillip@pjbsoftware.com*
-
-* Fixed an exception when using Ajax based requests from Safari because Safari appends a \000 to the post body. Symbols can't have \000 in them so indifferent access would throw an exception in the constructor. Indifferent hashes now use strings internally instead. #746 *Tobias Lütke*
-
-* Added String#to_time and String#to_date for wrapping ParseDate
-
-
-## 1.0.0 (24th February, 2005) ##
-
-* Added TimeZone as the first of a number of value objects that among others Active Record can use rich value objects using composed_of #688 *Jamis Buck*
-
-* Added Date::Conversions for getting dates in different convenient string representations and other objects
-
-* Added Time::Conversions for getting times in different convenient string representations and other objects
-
-* Added Time::Calculations to ask for things like Time.now.tomorrow, Time.now.yesterday, Time.now.months_ago(4) #580 [DP|Flurin]. Examples:
-
- "Later today" => now.in(3.hours),
- "Tomorrow morning" => now.tomorrow.change(:hour => 9),
- "Tomorrow afternoon" => now.tomorrow.change(:hour => 14),
- "In a couple of days" => now.tomorrow.tomorrow.change(:hour => 9),
- "Next monday" => now.next_week.change(:hour => 9),
- "In a month" => now.next_month.change(:hour => 9),
- "In 6 months" => now.months_since(6).change(:hour => 9),
- "In a year" => now.in(1.year).change(:hour => 9)
-
-* Upgraded to breakpoint 92 which fixes:
-
- * overload IRB.parse_opts(), fixes #443
- => breakpoints in tests work even when running them via rake
- * untaint handlers, might fix an issue discussed on the Rails ML
- * added verbose mode to breakpoint_client
- * less noise caused by breakpoint_client by default
- * ignored TerminateLineInput exception in signal handler
- => quiet exit on Ctrl-C
-
-* Fixed Inflector for words like "news" and "series" that are the same in plural and singular #603 [echion], #615 *marcenuc*
-
-* Added Hash#stringify_keys and Hash#stringify_keys!
-
-* Added IndifferentAccess as a way to wrap a hash by a symbol-based store that also can be accessed by string keys
-
-* Added Inflector.constantize to turn "Admin::User" into a reference for the constant Admin::User
-
-* Added that Inflector.camelize and Inflector.underscore can deal with modules like turning "Admin::User" into "admin/user" and back
-
-* Added Inflector.humanize to turn attribute names like employee_salary into "Employee salary". Used by automated error reporting in AR.
-
-* Added availability of class inheritable attributes to the masses #477 *Jeremy Kemper*
-
- class Foo
- class_inheritable_reader :read_me
- class_inheritable_writer :write_me
- class_inheritable_accessor :read_and_write_me
- class_inheritable_array :read_and_concat_me
- class_inheritable_hash :read_and_update_me
- end
-
- # Bar gets a clone of (not a reference to) Foo's attributes.
- class Bar < Foo
- end
-
- Bar.read_and_write_me == Foo.read_and_write_me
- Bar.read_and_write_me = 'bar'
- Bar.read_and_write_me != Foo.read_and_write_me
-
-* Added Inflections as an extension on String, so Inflector.pluralize(Inflector.classify(name)) becomes name.classify.pluralize #476 *Jeremy Kemper*
-
-* Added Byte operations to Numeric, so 5.5.megabytes + 200.kilobytes #461 *Marcel Molina Jr.*
-
-* Fixed that Dependencies.reload can't load the same file twice #420 *Kent Sibilev*
-
-* Added Fixnum#ago/until, Fixnum#since/from_now #450 *Jeremy Kemper*
-
-* Added that Inflector now accepts Symbols and Classes by calling .to_s on the word supplied
-
-* Added time unit extensions to Fixnum that'll return the period in seconds, like 2.days + 4.hours.
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activesupport/CHANGELOG.md) for previous changes.
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 56d6676961..41d77ab6c1 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -37,7 +37,6 @@ module ActiveSupport
autoload :LogSubscriber
autoload :Notifications
- # TODO: Narrow this list down
eager_autoload do
autoload :BacktraceCleaner
autoload :BasicObject
@@ -55,12 +54,12 @@ module ActiveSupport
autoload :OptionMerger
autoload :OrderedHash
autoload :OrderedOptions
- autoload :Rescuable
autoload :StringInquirer
autoload :TaggedLogging
autoload :XmlMini
end
+ autoload :Rescuable
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
autoload :TestCase
end
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 5be63af342..2c1ad60d44 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/file/atomic'
require 'active_support/core_ext/string/conversions'
-require 'active_support/core_ext/object/inclusion'
require 'uri/common'
module ActiveSupport
@@ -23,7 +22,7 @@ module ActiveSupport
end
def clear(options = nil)
- root_dirs = Dir.entries(cache_path).reject{|f| f.in?(EXCLUDED_DIRS + [".gitkeep"])}
+ root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
end
@@ -151,7 +150,7 @@ module ActiveSupport
# Delete empty directories in the cache.
def delete_empty_directories(dir)
return if dir == cache_path
- if Dir.entries(dir).reject{|f| f.in?(EXCLUDED_DIRS)}.empty?
+ if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
File.delete(dir) rescue nil
delete_empty_directories(File.dirname(dir))
end
@@ -165,7 +164,7 @@ module ActiveSupport
def search_dir(dir, &callback)
return if !File.exist?(dir)
Dir.foreach(dir) do |d|
- next if d.in?(EXCLUDED_DIRS)
+ next if EXCLUDED_DIRS.include?(d)
name = File.join(dir, d)
if File.directory?(name)
search_dir(name, &callback)
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index 2e1ccb72d8..5aa78cc9f3 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -1,7 +1,7 @@
begin
- require 'memcache'
+ require 'dalli'
rescue LoadError => e
- $stderr.puts "You don't have memcache-client installed in your application. Please add it to your Gemfile and run bundle install"
+ $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
@@ -22,21 +22,13 @@ module ActiveSupport
# MemCacheStore implements the Strategy::LocalCache strategy which implements
# an in-memory cache inside of a block.
class MemCacheStore < Store
- module Response # :nodoc:
- STORED = "STORED\r\n"
- NOT_STORED = "NOT_STORED\r\n"
- EXISTS = "EXISTS\r\n"
- NOT_FOUND = "NOT_FOUND\r\n"
- DELETED = "DELETED\r\n"
- end
-
ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n
def self.build_mem_cache(*addresses)
addresses = addresses.flatten
options = addresses.extract_options!
addresses = ["localhost:11211"] if addresses.empty?
- MemCache.new(addresses, options)
+ Dalli::Client.new(addresses, options)
end
# Creates a new MemCacheStore object, with the given memcached server
@@ -90,11 +82,11 @@ module ActiveSupport
# to zero.
def increment(name, amount = 1, options = nil) # :nodoc:
options = merged_options(options)
- response = instrument(:increment, name, :amount => amount) do
+ instrument(:increment, name, :amount => amount) do
@data.incr(escape_key(namespaced_key(name, options)), amount)
end
- response == Response::NOT_FOUND ? nil : response.to_i
- rescue MemCache::MemCacheError
+ rescue Dalli::DalliError
+ logger.error("DalliError (#{e}): #{e.message}") if logger
nil
end
@@ -104,11 +96,11 @@ module ActiveSupport
# to zero.
def decrement(name, amount = 1, options = nil) # :nodoc:
options = merged_options(options)
- response = instrument(:decrement, name, :amount => amount) do
+ instrument(:decrement, name, :amount => amount) do
@data.decr(escape_key(namespaced_key(name, options)), amount)
end
- response == Response::NOT_FOUND ? nil : response.to_i
- rescue MemCache::MemCacheError
+ rescue Dalli::DalliError
+ logger.error("DalliError (#{e}): #{e.message}") if logger
nil
end
@@ -116,6 +108,9 @@ module ActiveSupport
# be used with care when shared cache is being used.
def clear(options = nil)
@data.flush_all
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ nil
end
# Get the statistics from the memcached servers.
@@ -126,9 +121,9 @@ module ActiveSupport
protected
# Read an entry from the cache.
def read_entry(key, options) # :nodoc:
- deserialize_entry(@data.get(escape_key(key), true))
- rescue MemCache::MemCacheError => e
- logger.error("MemCacheError (#{e}): #{e.message}") if logger
+ deserialize_entry(@data.get(escape_key(key), options))
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
nil
end
@@ -137,23 +132,17 @@ module ActiveSupport
method = options && options[:unless_exist] ? :add : :set
value = options[:raw] ? entry.value.to_s : entry
expires_in = options[:expires_in].to_i
- if expires_in > 0 && !options[:raw]
- # Set the memcache expire a few minutes in the future to support race condition ttls on read
- expires_in += 5.minutes
- end
- response = @data.send(method, escape_key(key), value, expires_in, options[:raw])
- response == Response::STORED
- rescue MemCache::MemCacheError => e
- logger.error("MemCacheError (#{e}): #{e.message}") if logger
+ @data.send(method, escape_key(key), value, expires_in, options)
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
false
end
# Delete an entry from the cache.
def delete_entry(key, options) # :nodoc:
- response = @data.delete(escape_key(key))
- response == Response::DELETED
- rescue MemCache::MemCacheError => e
- logger.error("MemCacheError (#{e}): #{e.message}") if logger
+ @data.delete(escape_key(key))
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
false
end
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 6cc875c69a..3f7d0e401a 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -3,7 +3,6 @@ require 'active_support/descendants_tracker'
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/object/inclusion'
module ActiveSupport
# \Callbacks are code hooks that are run at key points in an object's lifecycle.
@@ -78,7 +77,7 @@ module ActiveSupport
private
# A hook invoked everytime a before callback is halted.
- # This can be overriden in AS::Callback implementors in order
+ # This can be overridden in AS::Callback implementors in order
# to provide better debugging/logging.
def halted_callback_hook(filter)
end
@@ -353,7 +352,7 @@ module ActiveSupport
# CallbackChain.
#
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
- type = filters.first.in?([:before, :after, :around]) ? filters.shift : :before
+ type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before
options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block
diff --git a/activesupport/lib/active_support/concurrency/latch.rb b/activesupport/lib/active_support/concurrency/latch.rb
new file mode 100644
index 0000000000..1507de433e
--- /dev/null
+++ b/activesupport/lib/active_support/concurrency/latch.rb
@@ -0,0 +1,27 @@
+require 'thread'
+require 'monitor'
+
+module ActiveSupport
+ module Concurrency
+ class Latch
+ def initialize(count = 1)
+ @count = count
+ @lock = Monitor.new
+ @cv = @lock.new_cond
+ end
+
+ def release
+ @lock.synchronize do
+ @count -= 1 if @count > 0
+ @cv.broadcast if @count.zero?
+ end
+ end
+
+ def await
+ @lock.synchronize do
+ @cv.wait_while { @count > 0 }
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date.rb b/activesupport/lib/active_support/core_ext/date.rb
new file mode 100644
index 0000000000..465fedda80
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date.rb
@@ -0,0 +1,5 @@
+require 'active_support/core_ext/date/acts_like'
+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/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index 7fe4161fb4..86badf4d29 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -3,17 +3,10 @@ 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
- DAYS_INTO_WEEK = {
- :monday => 0,
- :tuesday => 1,
- :wednesday => 2,
- :thursday => 3,
- :friday => 4,
- :saturday => 5,
- :sunday => 6
- }
+ include DateAndTime::Calculations
class << self
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
@@ -32,21 +25,6 @@ class Date
end
end
- # Returns true if the Date object's date lies in the past. Otherwise returns false.
- def past?
- self < ::Date.current
- end
-
- # Returns true if the Date object's date is today.
- def today?
- to_date == ::Date.current # we need the to_date because of DateTime
- end
-
- # Returns true if the Date object's date lies in the future.
- def future?
- self > ::Date.current
- end
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
# and then subtracts the specified number of seconds.
def ago(seconds)
@@ -106,6 +84,7 @@ class Date
end
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
+ # The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
#
# Date.new(2007, 5, 12).change(:day => 1) # => Date.new(2007, 5, 1)
# Date.new(2007, 5, 12).change(:year => 2005, :month => 1) # => Date.new(2005, 1, 12)
@@ -116,161 +95,4 @@ class Date
options.fetch(:day, day)
)
end
-
- # Returns a new Date/DateTime representing the time a number of specified weeks ago.
- def weeks_ago(weeks)
- advance(:weeks => -weeks)
- end
-
- # Returns a new Date/DateTime representing the time a number of specified months ago.
- def months_ago(months)
- advance(:months => -months)
- end
-
- # Returns a new Date/DateTime representing the time a number of specified months in the future.
- def months_since(months)
- advance(:months => months)
- end
-
- # Returns a new Date/DateTime representing the time a number of specified years ago.
- def years_ago(years)
- advance(:years => -years)
- end
-
- # Returns a new Date/DateTime representing the time a number of specified years in the future.
- def years_since(years)
- advance(:years => years)
- end
-
- # Returns number of days to start of this week. Week is assumed to start on
- # +start_day+, default is +:monday+.
- def days_to_week_start(start_day = :monday)
- start_day_number = DAYS_INTO_WEEK[start_day]
- current_day_number = wday != 0 ? wday - 1 : 6
- (current_day_number - start_day_number) % 7
- end
-
- # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
- # assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
- # have their time set to 0:00.
- def beginning_of_week(start_day = :monday)
- days_to_start = days_to_week_start(start_day)
- result = self - days_to_start
- acts_like?(:time) ? result.midnight : result
- end
- alias :at_beginning_of_week :beginning_of_week
-
- # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
- # assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
- def monday
- beginning_of_week
- end
-
- # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
- # assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
- # have their time set to 23:59:59.
- def end_of_week(start_day = :monday)
- days_to_end = 6 - days_to_week_start(start_day)
- result = self + days_to_end.days
- acts_like?(:time) ? result.end_of_day : result
- end
- alias :at_end_of_week :end_of_week
-
- # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
- # assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
- def sunday
- end_of_week
- end
-
- # Returns a new +Date+/+DateTime+ representing the given +day+ in the previous
- # week. Default is +:monday+. +DateTime+ objects have their time set to 0:00.
- def prev_week(day = :monday)
- result = (self - 7).beginning_of_week + DAYS_INTO_WEEK[day]
- acts_like?(:time) ? result.change(:hour => 0) : result
- end
- alias :last_week :prev_week
-
- # Alias of prev_month
- alias :last_month :prev_month
-
- # Alias of prev_year
- alias :last_year :prev_year
-
- # Returns a new Date/DateTime representing the start of the given day in next week (default is :monday).
- def next_week(day = :monday)
- result = (self + 7).beginning_of_week + DAYS_INTO_WEEK[day]
- acts_like?(:time) ? result.change(:hour => 0) : result
- end
-
- # Short-hand for months_ago(3)
- def prev_quarter
- months_ago(3)
- end
- alias_method :last_quarter, :prev_quarter
-
- # Short-hand for months_since(3)
- def next_quarter
- months_since(3)
- end
-
- # Returns a new Date/DateTime representing the start of the month (1st of the month; DateTime objects will have time set to 0:00)
- def beginning_of_month
- acts_like?(:time) ? change(:day => 1, :hour => 0) : change(:day => 1)
- end
- alias :at_beginning_of_month :beginning_of_month
-
- # Returns a new Date/DateTime representing the end of the month (last day of the month; DateTime objects will have time set to 0:00)
- def end_of_month
- last_day = ::Time.days_in_month(month, year)
- if acts_like?(:time)
- change(:day => last_day, :hour => 23, :min => 59, :sec => 59)
- else
- change(:day => last_day)
- end
- end
- alias :at_end_of_month :end_of_month
-
- # Returns a new Date/DateTime representing the start of the quarter (1st of january, april, july, october; DateTime objects will have time set to 0:00)
- def beginning_of_quarter
- first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
- beginning_of_month.change(:month => first_quarter_month)
- end
- alias :at_beginning_of_quarter :beginning_of_quarter
-
- # Returns a new Date/DateTime representing the end of the quarter (last day of march, june, september, december; DateTime objects will have time set to 23:59:59)
- 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
- end
- alias :at_end_of_quarter :end_of_quarter
-
- # Returns a new Date/DateTime representing the start of the year (1st of january; DateTime objects will have time set to 0:00)
- def beginning_of_year
- if acts_like?(:time)
- change(:month => 1, :day => 1, :hour => 0)
- else
- change(:month => 1, :day => 1)
- end
- end
- alias :at_beginning_of_year :beginning_of_year
-
- # Returns a new Time representing the end of the year (31st of december; DateTime objects will have time set to 23:59:59)
- def end_of_year
- if acts_like?(:time)
- change(:month => 12, :day => 31, :hour => 23, :min => 59, :sec => 59)
- else
- change(:month => 12, :day => 31)
- end
- end
- alias :at_end_of_year :end_of_year
-
- # Convenience method which returns a new Date/DateTime representing the time 1 day ago
- def yesterday
- self - 1
- end
-
- # Convenience method which returns a new Date/DateTime representing the time 1 day since the instance time
- def tomorrow
- self + 1
- end
end
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
new file mode 100644
index 0000000000..e703fca7a7
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
@@ -0,0 +1,213 @@
+module DateAndTime
+ module Calculations
+ DAYS_INTO_WEEK = {
+ :monday => 0,
+ :tuesday => 1,
+ :wednesday => 2,
+ :thursday => 3,
+ :friday => 4,
+ :saturday => 5,
+ :sunday => 6
+ }
+
+ # Returns a new date/time representing yesterday.
+ def yesterday
+ advance(:days => -1)
+ end
+
+ # Returns a new date/time representing tomorrow.
+ def tomorrow
+ advance(:days => 1)
+ end
+
+ # Returns true if the date/time is today.
+ def today?
+ to_date == ::Date.current
+ end
+
+ # Returns true if the date/time is in the past.
+ def past?
+ self < self.class.current
+ end
+
+ # Returns true if the date/time is in the future.
+ def future?
+ self > self.class.current
+ end
+
+ # Returns a new date/time the specified number of days ago.
+ def days_ago(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)
+ end
+
+ # Returns a new date/time the specified number of weeks ago.
+ def weeks_ago(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)
+ end
+
+ # Returns a new date/time the specified number of months ago.
+ def months_ago(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)
+ end
+
+ # Returns a new date/time the specified number of years ago.
+ def years_ago(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)
+ end
+
+ # Returns a new date/time at the start of the month.
+ # DateTime objects will have a time set to 0:00.
+ def beginning_of_month
+ first_hour{ change(:day => 1) }
+ end
+ alias :at_beginning_of_month :beginning_of_month
+
+ # Returns a new date/time at the start of the quarter.
+ # Example: 1st January, 1st July, 1st October.
+ # DateTime objects will have a time set to 0:00.
+ def beginning_of_quarter
+ first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
+ beginning_of_month.change(:month => first_quarter_month)
+ end
+ alias :at_beginning_of_quarter :beginning_of_quarter
+
+ # Returns a new date/time at the end of the quarter.
+ # Example: 31st March, 30th June, 30th September.
+ # DateTIme objects will have a time set to 23:59:59.
+ 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
+ end
+ alias :at_end_of_quarter :end_of_quarter
+
+ # Return a new date/time at the beginning of the year.
+ # Example: 1st January.
+ # DateTime objects will have a time set to 0:00.
+ def beginning_of_year
+ change(:month => 1).beginning_of_month
+ end
+ alias :at_beginning_of_year :beginning_of_year
+
+ # Returns a new date/time representing the given day in the next week.
+ # Default is :monday.
+ # DateTime objects have their time set to 0:00.
+ def next_week(day = :monday)
+ first_hour{ weeks_since(1).beginning_of_week.days_since(DAYS_INTO_WEEK[day]) }
+ end
+
+ # Short-hand for months_since(1).
+ def next_month
+ months_since(1)
+ end
+
+ # Short-hand for months_since(3)
+ def next_quarter
+ months_since(3)
+ end
+
+ # Short-hand for years_since(1).
+ def next_year
+ years_since(1)
+ end
+
+ # Returns a new date/time representing the given day in the previous week.
+ # Default is :monday.
+ # DateTime objects have their time set to 0:00.
+ def prev_week(day = :monday)
+ first_hour{ weeks_ago(1).beginning_of_week.days_since(DAYS_INTO_WEEK[day]) }
+ end
+ alias_method :last_week, :prev_week
+
+ # Short-hand for months_ago(1).
+ def prev_month
+ months_ago(1)
+ end
+ alias_method :last_month, :prev_month
+
+ # Short-hand for months_ago(3).
+ def prev_quarter
+ months_ago(3)
+ end
+ alias_method :last_quarter, :prev_quarter
+
+ # Short-hand for years_ago(1).
+ def prev_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.
+ # Default is :monday.
+ def days_to_week_start(start_day = :monday)
+ start_day_number = DAYS_INTO_WEEK[start_day]
+ current_day_number = wday != 0 ? wday - 1 : 6
+ (current_day_number - start_day_number) % 7
+ end
+
+ # Returns a new date/time representing the start of this week on the given day.
+ # Default is :monday.
+ # DateTime objects have their time set to 0:00.
+ def beginning_of_week(start_day = :monday)
+ result = days_ago(days_to_week_start(start_day))
+ acts_like?(:time) ? result.midnight : result
+ end
+ alias :at_beginning_of_week :beginning_of_week
+ alias :monday :beginning_of_week
+
+ # Returns a new date/time representing the end of this week on the given day.
+ # Default is :monday (i.e end of Sunday).
+ # DateTime objects have their time set to 23:59:59.
+ def end_of_week(start_day = :monday)
+ last_hour{ days_since(6 - days_to_week_start(start_day)) }
+ end
+ alias :at_end_of_week :end_of_week
+ alias :sunday :end_of_week
+
+ # Returns a new date/time representing the end of the month.
+ # DateTime objects will have a time set to 23:59:59.
+ def end_of_month
+ last_day = ::Time.days_in_month(month, year)
+ last_hour{ days_since(last_day - day) }
+ end
+ alias :at_end_of_month :end_of_month
+
+ # 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
+ end
+ alias :at_end_of_year :end_of_year
+
+ private
+
+ def first_hour
+ result = yield
+ acts_like?(:time) ? result.change(:hour => 0) : result
+ end
+
+ def last_hour
+ result = yield
+ acts_like?(:time) ? result.end_of_day : result
+ 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
new file mode 100644
index 0000000000..e8a27b9f38
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time.rb
@@ -0,0 +1,4 @@
+require 'active_support/core_ext/date_time/acts_like'
+require 'active_support/core_ext/date_time/calculations'
+require 'active_support/core_ext/date_time/conversions'
+require 'active_support/core_ext/date_time/zones'
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 fd78044b5d..5fb19f2e6e 100644
--- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -31,8 +31,13 @@ class DateTime
end
# Returns a new DateTime where one or more of the elements have been changed according to the +options+ parameter. The time options
- # (hour, minute, sec) reset cascadingly, so if only the hour is passed, then minute and sec is set to 0. If the hour and
- # minute is passed, then sec is set to 0.
+ # (<tt>:hour</tt>, <tt>:minute</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is passed, then minute and sec is set to 0. If the hour and
+ # minute is passed, then sec 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>:offset</tt>, <tt>:start</tt>.
+ #
+ # DateTime.new(2012, 8, 29, 22, 35, 0).change(:day => 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
+ # 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)
::DateTime.civil(
options.fetch(:year, year),
diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb
index 9e504851e7..81beb4e85d 100644
--- a/activesupport/lib/active_support/core_ext/file/atomic.rb
+++ b/activesupport/lib/active_support/core_ext/file/atomic.rb
@@ -1,3 +1,5 @@
+require 'fileutils'
+
class File
# Write to a file atomically. Useful for situations where you don't
# want other processes or threads to see half-written files.
@@ -25,17 +27,9 @@ class File
# Get original file permissions
old_stat = stat(file_name)
rescue Errno::ENOENT
- # No old permissions, write a temp file to determine the defaults
- temp_file_name = [
- '.permissions_check',
- Thread.current.object_id,
- Process.pid,
- rand(1000000)
- ].join('.')
- check_name = join(dirname(file_name), temp_file_name)
- open(check_name, 'w') { }
- old_stat = stat(check_name)
- unlink(check_name)
+ # If not possible, probe which are the default permissions in the
+ # destination directory.
+ old_stat = probe_stat_in(dirname(file_name))
end
# Overwrite original file with temp file
@@ -45,4 +39,20 @@ class File
chown(old_stat.uid, old_stat.gid, file_name)
chmod(old_stat.mode, file_name)
end
+
+ # Private utility method.
+ def self.probe_stat_in(dir) #:nodoc:
+ basename = [
+ '.permissions_check',
+ Thread.current.object_id,
+ Process.pid,
+ rand(1000000)
+ ].join('.')
+
+ file_name = join(dir, basename)
+ FileUtils.touch(file_name)
+ stat(file_name)
+ ensure
+ FileUtils.rm_f(file_name) if file_name
+ 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 e5f81078ee..0d5f3501e5 100644
--- a/activesupport/lib/active_support/core_ext/object/to_param.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_param.rb
@@ -6,18 +6,21 @@ class Object
end
class NilClass
+ # Returns +self+.
def to_param
self
end
end
class TrueClass
+ # Returns +self+.
def to_param
self
end
end
class FalseClass
+ # Returns +self+.
def to_param
self
end
@@ -35,12 +38,12 @@ class Hash
# Returns a string representation of the receiver suitable for use as a URL
# query string:
#
- # {:name => 'David', :nationality => 'Danish'}.to_param
+ # {name: 'David', nationality: 'Danish'}.to_param
# # => "name=David&nationality=Danish"
#
# An optional namespace can be passed to enclose the param names:
#
- # {:name => 'David', :nationality => 'Danish'}.to_param('user')
+ # {name: 'David', nationality: 'Danish'}.to_param('user')
# # => "user[name]=David&user[nationality]=Danish"
#
# The string pairs "key=value" that conform the query string
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index 16a799ec03..1079ddde98 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -5,6 +5,9 @@ class Object
# *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
# and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
#
+ # This is also true if the receiving object does not implemented the tried method. It will
+ # return +nil+ in that case as well.
+ #
# If try is called without a method to call, it will yield any given block with the object.
#
# Please also note that +try+ is defined on +Object+, therefore it won't work with
@@ -31,6 +34,16 @@ class Object
if a.empty? && block_given?
yield self
else
+ public_send(*a, &b) if respond_to?(a.first)
+ end
+ end
+
+ # Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
+ # does not implemented the tried method.
+ def try!(*a, &b)
+ if a.empty? && block_given?
+ yield self
+ else
public_send(*a, &b)
end
end
@@ -50,4 +63,8 @@ class NilClass
def try(*args)
nil
end
+
+ def try!(*args)
+ nil
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb
index fb36262528..ad864765a3 100644
--- a/activesupport/lib/active_support/core_ext/string.rb
+++ b/activesupport/lib/active_support/core_ext/string.rb
@@ -10,3 +10,4 @@ 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'
diff --git a/activesupport/lib/active_support/core_ext/string/indent.rb b/activesupport/lib/active_support/core_ext/string/indent.rb
new file mode 100644
index 0000000000..afc3032272
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/indent.rb
@@ -0,0 +1,43 @@
+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]/] || ' '
+ re = indent_empty_lines ? /^/ : /^(?!$)/
+ gsub!(re, indent_string * amount)
+ end
+
+ # Indents the lines in the receiver:
+ #
+ # <<EOS.indent(2)
+ # def some_method
+ # some_code
+ # end
+ # EOS
+ # # =>
+ # def some_method
+ # some_code
+ # end
+ #
+ # The second argument, +indent_string+, specifies which indent string to
+ # use. The default is +nil+, which tells the method to make a guess by
+ # peeking at the first indented line, and fallback to a space if there is
+ # none.
+ #
+ # " foo".indent(2) # => " foo"
+ # "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
+ # "foo".indent(2, "\t") # => "\t\tfoo"
+ #
+ # While +indent_string+ is tipically one space or tab, it may be any string.
+ #
+ # The third argument, +indent_empty_lines+, is a flag that says whether
+ # empty lines should be indented. Default is false.
+ #
+ # "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)}
+ 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 efa2d43f20..6edfcd7493 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -13,6 +13,11 @@ class String
# the singular form will be returned if <tt>count == 1</tt>.
# For any other value of +count+ the plural will be returned.
#
+ # If the optional parameter +locale+ is specified,
+ # the word will be pluralized as a word of that language.
+ # By default, this parameter is set to <tt>:en</tt>.
+ # You must define your own inflection rules for languages other than English.
+ #
# 'post'.pluralize # => "posts"
# 'octopus'.pluralize # => "octopi"
# 'sheep'.pluralize # => "sheep"
@@ -21,15 +26,23 @@ class String
# 'CamelOctopus'.pluralize # => "CamelOctopi"
# 'apple'.pluralize(1) # => "apple"
# 'apple'.pluralize(2) # => "apples"
- def pluralize(count = nil)
+ # 'ley'.pluralize(:es) # => "leyes"
+ # 'ley'.pluralize(1, :es) # => "ley"
+ def pluralize(count = nil, locale = :en)
+ locale = count if count.is_a?(Symbol)
if count == 1
self
else
- ActiveSupport::Inflector.pluralize(self)
+ ActiveSupport::Inflector.pluralize(self, locale)
end
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
+ #
+ # If the optional parameter +locale+ is specified,
+ # the word will be singularized as a word of that language.
+ # By default, this paramter is set to <tt>:en</tt>.
+ # You must define your own inflection rules for languages other than English.
#
# 'posts'.singularize # => "post"
# 'octopi'.singularize # => "octopus"
@@ -37,8 +50,9 @@ class String
# 'word'.singularize # => "word"
# 'the blue mailmen'.singularize # => "the blue mailman"
# 'CamelOctopi'.singularize # => "CamelOctopus"
- def singularize
- ActiveSupport::Inflector.singularize(self)
+ # 'leyes'.singularize(:es) # => "ley"
+ def singularize(locale = :en)
+ ActiveSupport::Inflector.singularize(self, locale)
end
# +constantize+ tries to find a declared constant with the name specified
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 5226ff0cbe..dad4b29d46 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -3,9 +3,9 @@ require 'active_support/core_ext/kernel/singleton_class'
class ERB
module Util
- HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }
+ HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;', "'" => '&#x27;' }
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
- HTML_ESCAPE_ONCE_REGEXP = /[\"><]|&(?!([a-zA-Z]+|(#\d+));)/
+ HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+));)/
JSON_ESCAPE_REGEXP = /[&"><]/
# A utility method for escaping HTML tag characters.
@@ -21,7 +21,7 @@ class ERB
if s.html_safe?
s
else
- s.encode(s.encoding, :xml => :attr)[1...-1].html_safe
+ s.gsub(/[&"'><]/, HTML_ESCAPE).html_safe
end
end
@@ -60,18 +60,11 @@ class ERB
# json_escape('{"name":"john","created_at":"2010-04-28T01:39:31Z","id":1}')
# # => {name:john,created_at:2010-04-28T01:39:31Z,id:1}
#
- # This method is also aliased as +j+, and available as a helper
- # in Rails templates:
- #
- # <%=j @person.to_json %>
- #
def json_escape(s)
result = s.to_s.gsub(JSON_ESCAPE_REGEXP) { |special| JSON_ESCAPE[special] }
s.html_safe? ? result.html_safe : result
end
- alias j json_escape
- module_function :j
module_function :json_escape
end
end
diff --git a/activesupport/lib/active_support/core_ext/time.rb b/activesupport/lib/active_support/core_ext/time.rb
new file mode 100644
index 0000000000..32cffe237d
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time.rb
@@ -0,0 +1,5 @@
+require 'active_support/core_ext/time/acts_like'
+require 'active_support/core_ext/time/calculations'
+require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/time/marshal'
+require 'active_support/core_ext/time/zones'
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 0a71fc117c..148f2c27f1 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -1,18 +1,13 @@
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'
class Time
+ include DateAndTime::Calculations
+
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- DAYS_INTO_WEEK = {
- :monday => 0,
- :tuesday => 1,
- :wednesday => 2,
- :thursday => 3,
- :friday => 4,
- :saturday => 5,
- :sunday => 6
- }
class << self
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
@@ -62,29 +57,19 @@ class Time
end
end
- # Tells whether the Time object's time lies in the past
- def past?
- self < ::Time.current
- end
-
- # Tells whether the Time object's time is today
- def today?
- to_date == ::Date.current
- end
-
- # Tells whether the Time object's time lies in the future
- def future?
- self > ::Time.current
- end
-
# Seconds since midnight: Time.now.seconds_since_midnight
def seconds_since_midnight
to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
end
# Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options
- # (hour, min, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and
- # minute is passed, then sec and usec is set to 0.
+ # (<tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0.
+ # If the hour and minute is passed, then sec and usec 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>.
+ #
+ # 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)
@@ -145,116 +130,6 @@ class Time
end
alias :in :since
- # Returns a new Time representing the time a number of specified weeks ago.
- def weeks_ago(weeks)
- advance(:weeks => -weeks)
- end
-
- # Returns a new Time representing the time a number of specified months ago
- def months_ago(months)
- advance(:months => -months)
- end
-
- # Returns a new Time representing the time a number of specified months in the future
- def months_since(months)
- advance(:months => months)
- end
-
- # Returns a new Time representing the time a number of specified years ago
- def years_ago(years)
- advance(:years => -years)
- end
-
- # Returns a new Time representing the time a number of specified years in the future
- def years_since(years)
- advance(:years => years)
- end
-
- # Short-hand for years_ago(1)
- def prev_year
- years_ago(1)
- end
- alias_method :last_year, :prev_year
-
- # Short-hand for years_since(1)
- def next_year
- years_since(1)
- end
-
- # Short-hand for months_ago(1)
- def prev_month
- months_ago(1)
- end
- alias_method :last_month, :prev_month
-
- # Short-hand for months_since(1)
- def next_month
- months_since(1)
- end
-
- # Short-hand for months_ago(3)
- def prev_quarter
- months_ago(3)
- end
- alias_method :last_quarter, :prev_quarter
-
- # Short-hand for months_since(3)
- def next_quarter
- months_since(3)
- end
-
- # Returns number of days to start of this week, week starts on start_day (default is :monday).
- def days_to_week_start(start_day = :monday)
- start_day_number = DAYS_INTO_WEEK[start_day]
- current_day_number = wday != 0 ? wday - 1 : 6
- days_span = current_day_number - start_day_number
-
- days_span >= 0 ? days_span : 7 + days_span
- end
-
- # Returns a new Time representing the "start" of this week, week starts on start_day (default is :monday, i.e. Monday, 0:00).
- def beginning_of_week(start_day = :monday)
- days_to_start = days_to_week_start(start_day)
- (self - days_to_start.days).midnight
- end
- alias :at_beginning_of_week :beginning_of_week
-
- # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
- # assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
- def monday
- beginning_of_week
- end
-
- # Returns a new Time representing the end of this week, week starts on start_day (default is :monday, i.e. end of Sunday).
- def end_of_week(start_day = :monday)
- days_to_end = 6 - days_to_week_start(start_day)
- (self + days_to_end.days).end_of_day
- end
- alias :at_end_of_week :end_of_week
-
- # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
- # assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
- def sunday
- end_of_week
- end
-
- # Returns a new Time representing the start of the given day in the previous week (default is :monday).
- def prev_week(day = :monday)
- ago(1.week).
- beginning_of_week.
- since(DAYS_INTO_WEEK[day].day).
- change(:hour => 0)
- end
- alias_method :last_week, :prev_week
-
- # Returns a new Time representing the start of the given day in next week (default is :monday).
- def next_week(day = :monday)
- since(1.week).
- beginning_of_week.
- since(DAYS_INTO_WEEK[day].day).
- change(:hour => 0)
- end
-
# Returns a new Time representing the start of the day (0:00)
def beginning_of_day
#(self - seconds_since_midnight).change(:usec => 0)
@@ -289,70 +164,6 @@ class Time
)
end
- # Returns a new Time representing the start of the month (1st of the month, 0:00)
- def beginning_of_month
- #self - ((self.mday-1).days + self.seconds_since_midnight)
- change(:day => 1, :hour => 0)
- end
- alias :at_beginning_of_month :beginning_of_month
-
- # Returns a new Time representing the end of the month (end of the last day of the month)
- def end_of_month
- #self - ((self.mday-1).days + self.seconds_since_midnight)
- last_day = ::Time.days_in_month(month, year)
- change(
- :day => last_day,
- :hour => 23,
- :min => 59,
- :sec => 59,
- :usec => Rational(999999999, 1000)
- )
- end
- alias :at_end_of_month :end_of_month
-
- # Returns a new Time representing the start of the quarter (1st of january, april, july, october, 0:00)
- def beginning_of_quarter
- first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
- beginning_of_month.change(:month => first_quarter_month)
- end
- alias :at_beginning_of_quarter :beginning_of_quarter
-
- # Returns a new Time representing the end of the quarter (end of the last day of march, june, september, december)
- 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
- end
- alias :at_end_of_quarter :end_of_quarter
-
- # Returns a new Time representing the start of the year (1st of january, 0:00)
- def beginning_of_year
- change(:month => 1, :day => 1, :hour => 0)
- end
- alias :at_beginning_of_year :beginning_of_year
-
- # Returns a new Time representing the end of the year (end of the 31st of december)
- def end_of_year
- change(
- :month => 12,
- :day => 31,
- :hour => 23,
- :min => 59,
- :sec => 59,
- :usec => Rational(999999999, 1000)
- )
- end
- alias :at_end_of_year :end_of_year
-
- # Convenience method which returns a new Time representing the time 1 day ago
- def yesterday
- advance(:days => -1)
- end
-
- # Convenience method which returns a new Time representing the time 1 day since the instance time
- def tomorrow
- advance(:days => 1)
- end
-
# Returns a Range representing the whole day of the current time.
def all_day
beginning_of_day..end_of_day
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
index e48866abe3..37bc3fae24 100644
--- a/activesupport/lib/active_support/core_ext/time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/time/calculations'
require 'active_support/time_with_zone'
class Time
@@ -27,11 +26,11 @@ class Time
# around_filter :set_time_zone
#
# def set_time_zone
- # old_time_zone = Time.zone
- # Time.zone = current_user.time_zone if logged_in?
- # yield
- # ensure
- # Time.zone = old_time_zone
+ # if logged_in?
+ # Time.use_zone(current_user.time_zone) { yield }
+ # else
+ # yield
+ # end
# end
# end
def zone=(time_zone)
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index c9071a73d8..d6bc95a522 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -168,16 +168,30 @@ module ActiveSupport #:nodoc:
end
end
- def const_missing(const_name, nesting = nil)
+ def const_missing(const_name)
klass_name = name.presence || "Object"
- unless nesting
- # We'll assume that the nesting of Foo::Bar is ["Foo::Bar", "Foo"]
- # even though it might not be, such as in the case of
- # class Foo::Bar; Baz; end
- nesting = []
- klass_name.to_s.scan(/::|$/) { nesting.unshift $` }
- end
+ # Since Ruby does not pass the nesting at the point the unknown
+ # constant triggered the callback we cannot fully emulate constant
+ # name lookup and need to make a trade-off: we are going to assume
+ # that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
+ # though it might not be. Counterexamples are
+ #
+ # class Foo::Bar
+ # Module.nesting # => [Foo::Bar]
+ # end
+ #
+ # or
+ #
+ # module M::N
+ # module S::T
+ # Module.nesting # => [S::T, M::N]
+ # end
+ # end
+ #
+ # for example.
+ nesting = []
+ klass_name.to_s.scan(/::|$/) { nesting.unshift $` }
# If there are multiple levels of nesting to search under, the top
# level is the one we want to report as the lookup fail.
@@ -287,13 +301,11 @@ module ActiveSupport #:nodoc:
Object.class_eval { include Loadable }
Module.class_eval { include ModuleConstMissing }
Exception.class_eval { include Blamable }
- true
end
def unhook!
ModuleConstMissing.exclude_from(Module)
Loadable.exclude_from(Object)
- true
end
def load?
@@ -319,7 +331,7 @@ module ActiveSupport #:nodoc:
def require_or_load(file_name, const_path = nil)
log_call file_name, const_path
- file_name = $1 if file_name =~ /^(.*)\.rb$/
+ file_name = $` if file_name =~ /\.rb\z/
expanded = File.expand_path(file_name)
return if loaded.include?(expanded)
@@ -363,7 +375,7 @@ module ActiveSupport #:nodoc:
# Given +path+, a filesystem path to a ruby file, return an array of constant
# paths which would cause Dependencies to attempt to load this file.
def loadable_constants_for_path(path, bases = autoload_paths)
- path = $1 if path =~ /\A(.*)\.rb\Z/
+ path = $` if path =~ /\.rb\z/
expanded_path = File.expand_path(path)
paths = []
@@ -431,7 +443,7 @@ module ActiveSupport #:nodoc:
def load_file(path, const_paths = loadable_constants_for_path(path))
log_call path, const_paths
const_paths = [const_paths].compact unless const_paths.is_a? Array
- parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
+ parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || :Object }
result = nil
newly_defined_paths = new_constants_in(*parent_paths) do
@@ -467,10 +479,17 @@ module ActiveSupport #:nodoc:
file_path = search_for_file(path_suffix)
- if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
- require_or_load file_path
- raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless from_mod.const_defined?(const_name, false)
- return from_mod.const_get(const_name)
+ if file_path
+ expanded = File.expand_path(file_path)
+ expanded.sub!(/\.rb\z/, '')
+
+ if loaded.include?(expanded)
+ raise "Circular dependency detected while autoloading constant #{qualified_name}"
+ else
+ require_or_load(expanded)
+ raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
+ return from_mod.const_get(const_name)
+ end
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
return mod
elsif (parent = from_mod.parent) && parent != from_mod &&
diff --git a/activesupport/lib/active_support/dependencies/autoload.rb b/activesupport/lib/active_support/dependencies/autoload.rb
index 4045db3232..df490ae298 100644
--- a/activesupport/lib/active_support/dependencies/autoload.rb
+++ b/activesupport/lib/active_support/dependencies/autoload.rb
@@ -1,52 +1,78 @@
require "active_support/inflector/methods"
module ActiveSupport
+ # Autoload and eager load conveniences for your library.
+ #
+ # This module allows you to define autoloads based on
+ # Rails conventions (i.e. no need to define the path
+ # it is automatically guessed based on the filename)
+ # and also define a set of constants that needs to be
+ # eager loaded:
+ #
+ # module MyLib
+ # extend ActiveSupport::Autoload
+ #
+ # autoload :Model
+ #
+ # eager_autoload do
+ # autoload :Cache
+ # end
+ # end
+ #
+ # Then your library can be eager loaded by simply calling:
+ #
+ # MyLib.eager_load!
+ #
module Autoload
- @@autoloads = {}
- @@under_path = nil
- @@at_path = nil
- @@eager_autoload = false
+ def self.extended(base)
+ base.class_eval do
+ @_autoloads = {}
+ @_under_path = nil
+ @_at_path = nil
+ @_eager_autoload = false
+ end
+ end
- def autoload(const_name, path = @@at_path)
+ def autoload(const_name, path = @_at_path)
unless path
- full = [name, @@under_path, const_name.to_s, path].compact.join("::")
+ full = [name, @_under_path, const_name.to_s, path].compact.join("::")
path = Inflector.underscore(full)
end
- if @@eager_autoload
- @@autoloads[const_name] = path
+ if @_eager_autoload
+ @_autoloads[const_name] = path
end
super const_name, path
end
def autoload_under(path)
- @@under_path, old_path = path, @@under_path
+ @_under_path, old_path = path, @_under_path
yield
ensure
- @@under_path = old_path
+ @_under_path = old_path
end
def autoload_at(path)
- @@at_path, old_path = path, @@at_path
+ @_at_path, old_path = path, @_at_path
yield
ensure
- @@at_path = old_path
+ @_at_path = old_path
end
def eager_autoload
- old_eager, @@eager_autoload = @@eager_autoload, true
+ old_eager, @_eager_autoload = @_eager_autoload, true
yield
ensure
- @@eager_autoload = old_eager
+ @_eager_autoload = old_eager
end
- def self.eager_autoload!
- @@autoloads.values.each { |file| require file }
+ def eager_load!
+ @_autoloads.values.each { |file| require file }
end
def autoloads
- @@autoloads
+ @_autoloads
end
end
end
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 2cdc991120..a0139b7d8e 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -70,7 +70,7 @@ module ActiveSupport
alias :until :ago
def inspect #:nodoc:
- consolidated = parts.inject(::Hash.new(0)) { |h,part| h[part.first] += part.last; h }
+ consolidated = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
parts = [:years, :months, :days, :minutes, :seconds].map do |length|
n = consolidated[length]
"#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index 3e6c8893e9..71713644a7 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -1,12 +1,46 @@
require 'active_support/core_ext/hash/keys'
module ActiveSupport
- # This class has dubious semantics and we only have it so that
- # people can write <tt>params[:key]</tt> instead of <tt>params['key']</tt>
- # and they get the same value for both keys.
+ # Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered to be the same.
+ #
+ # rgb = ActiveSupport::HashWithIndifferentAccess.new
+ #
+ # rgb[:black] = '#000000'
+ # rgb[:black] # => '#000000'
+ # rgb['black'] # => '#000000'
+ #
+ # rgb['white'] = '#FFFFFF'
+ # rgb[:white] # => '#FFFFFF'
+ # rgb['white'] # => '#FFFFFF'
+ #
+ # Internally symbols are mapped to strings when used as keys in the entire
+ # writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
+ # mapping belongs to the public interface. For example, given
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new(:a => 1)
+ #
+ # you are guaranteed that the key is returned as a string:
+ #
+ # hash.keys # => ["a"]
+ #
+ # Technically other types of keys are accepted:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new(:a => 1)
+ # hash[0] = 0
+ # hash # => {"a"=>1, 0=>0}
+ #
+ # but this class is intended for use cases where strings or symbols are the
+ # expected keys and it is convenient to understand both as the same. For
+ # example the +params+ hash in Ruby on Rails.
+ #
+ # Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
+ #
+ # rgb = {:black => '#000000', :white => '#FFFFFF'}.with_indifferent_access
+ #
+ # which may be handy.
class HashWithIndifferentAccess < Hash
-
- # Always returns true, so that <tt>Array#extract_options!</tt> finds members of this class.
+ # Returns true so that <tt>Array#extract_options!</tt> finds members of
+ # this class.
def extractable_options?
true
end
@@ -51,30 +85,52 @@ module ActiveSupport
# Assigns a new value to the hash:
#
- # hash = HashWithIndifferentAccess.new
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
# hash[:key] = "value"
#
+ # This value can be later fetched using either +:key+ or +"key"+.
def []=(key, value)
regular_writer(convert_key(key), convert_value(value))
end
alias_method :store, :[]=
- # Updates the instantized hash with values from the second:
+ # Updates the receiver in-place, merging in the hash passed as argument:
#
- # hash_1 = HashWithIndifferentAccess.new
+ # hash_1 = ActiveSupport::HashWithIndifferentAccess.new
# hash_1[:key] = "value"
#
- # hash_2 = HashWithIndifferentAccess.new
+ # hash_2 = ActiveSupport::HashWithIndifferentAccess.new
# hash_2[:key] = "New Value!"
#
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
#
+ # The argument can be either an
+ # <tt>ActiveSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
+ # In either case the merge respects the semantics of indifferent access.
+ #
+ # If the argument is a regular hash with keys +:key+ and +"key"+ only one
+ # of the values end up in the receiver, but which one is unspecified.
+ #
+ # When given a block, the value for duplicated keys will be determined
+ # by the result of invoking the block with the duplicated key, the value
+ # in the receiver, and the value in +other_hash+. The rules for duplicated
+ # keys follow the semantics of indifferent access:
+ #
+ # hash_1[:key] = 10
+ # hash_2['key'] = 12
+ # hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
+ #
def update(other_hash)
if other_hash.is_a? HashWithIndifferentAccess
super(other_hash)
else
- other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
+ other_hash.each_pair do |key, value|
+ if block_given? && key?(key)
+ value = yield(convert_key(key), self[key], value)
+ end
+ regular_writer(convert_key(key), convert_value(value))
+ end
self
end
end
@@ -83,10 +139,10 @@ module ActiveSupport
# Checks the hash for a key matching the argument passed in:
#
- # hash = HashWithIndifferentAccess.new
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
# hash["key"] = "value"
- # hash.key? :key # => true
- # hash.key? "key" # => true
+ # hash.key?(:key) # => true
+ # hash.key?("key") # => true
#
def key?(key)
super(convert_key(key))
@@ -96,14 +152,24 @@ module ActiveSupport
alias_method :has_key?, :key?
alias_method :member?, :key?
- # Fetches the value for the specified key, same as doing hash[key]
+ # Same as <tt>Hash#fetch</tt> where the key passed as argument can be
+ # either a string or a symbol:
+ #
+ # counters = ActiveSupport::HashWithIndifferentAccess.new
+ # counters[:foo] = 1
+ #
+ # counters.fetch("foo") # => 1
+ # counters.fetch(:bar, 0) # => 0
+ # counters.fetch(:bar) {|key| 0} # => 0
+ # counters.fetch(:zoo) # => KeyError: key not found: "zoo"
+ #
def fetch(key, *extras)
super(convert_key(key), *extras)
end
# Returns an array of the values at the specified indices:
#
- # hash = HashWithIndifferentAccess.new
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
# hash[:a] = "x"
# hash[:b] = "y"
# hash.values_at("a", "b") # => ["x", "y"]
@@ -119,23 +185,30 @@ module ActiveSupport
end
end
- # Merges the instantized and the specified hashes together, giving precedence to the values from the second hash.
- # Does not overwrite the existing hash.
- def merge(hash)
- self.dup.update(hash)
+ # This method has the same semantics of +update+, except it does not
+ # 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)
end
- # Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
- # This overloaded definition prevents returning a regular hash, if reverse_merge is called on a <tt>HashWithDifferentAccess</tt>.
+ # Like +merge+ but the other way around: Merges the receiver into the
+ # argument and returns a new hash with indifferent access as result:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
+ # hash['a'] = nil
+ # hash.reverse_merge(:a => 0, :b => 1) # => {"a"=>nil, "b"=>1}
+ #
def reverse_merge(other_hash)
- super self.class.new_from_hash_copying_default(other_hash)
+ super(self.class.new_from_hash_copying_default(other_hash))
end
+ # Same semantics as +reverse_merge+ but modifies the receiver in-place.
def reverse_merge!(other_hash)
replace(reverse_merge( other_hash ))
end
- # Removes a specified key from the hash.
+ # Removes the specified key from the hash.
def delete(key)
super(convert_key(key))
end
@@ -150,7 +223,7 @@ module ActiveSupport
def deep_symbolize_keys; to_hash.deep_symbolize_keys end
def to_options!; self end
- # Convert to a Hash with String keys.
+ # Convert to a regular hash with string keys.
def to_hash
Hash.new(default).merge!(self)
end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index ca2d8cb270..ef882ebd09 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -1,7 +1,7 @@
require 'active_support/inflector/inflections'
module ActiveSupport
- Inflector.inflections do |inflect|
+ Inflector.inflections(:en) do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/s$/i, 's')
inflect.plural(/^(ax|test)is$/i, '\1es')
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index c9e50a9462..091692e5a4 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -1,13 +1,15 @@
require 'active_support/core_ext/array/prepend_and_append'
+require 'active_support/i18n'
module ActiveSupport
module Inflector
extend self
# A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional
- # inflection rules.
+ # inflection rules. If passed an optional locale, rules for other languages can be specified. The default locale is
+ # <tt>:en</tt>. Only rules for English are provided.
#
- # ActiveSupport::Inflector.inflections do |inflect|
+ # ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1\2en'
# inflect.singular /^(ox)en/i, '\1'
#
@@ -20,8 +22,9 @@ module ActiveSupport
# pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may
# already have been loaded.
class Inflections
- def self.instance
- @__instance__ ||= new
+ def self.instance(locale = :en)
+ @__instance__ ||= Hash.new { |h, k| h[k] = new }
+ @__instance__[locale]
end
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
@@ -160,16 +163,18 @@ module ActiveSupport
end
# Yields a singleton instance of Inflector::Inflections so you can specify additional
- # inflector rules.
+ # inflector rules. If passed an optional locale, rules for other languages can be specified.
+ # If not specified, defaults to <tt>:en</tt>. Only rules for English are provided.
+ #
#
- # ActiveSupport::Inflector.inflections do |inflect|
+ # ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.uncountable "rails"
# end
- def inflections
+ def inflections(locale = :en)
if block_given?
- yield Inflections.instance
+ yield Inflections.instance(locale)
else
- Inflections.instance
+ Inflections.instance(locale)
end
end
end
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index c14a43de0d..44214d16fa 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -10,31 +10,41 @@ module ActiveSupport
#
# The Rails core team has stated patches for the inflections library will not be accepted
# in order to avoid breaking legacy applications which may be relying on errant inflections.
- # If you discover an incorrect inflection and require it for your application, you'll need
- # to correct it yourself (explained below).
+ # If you discover an incorrect inflection and require it for your application or wish to
+ # define rules for languages other than English, please correct or add them yourself (explained below).
module Inflector
extend self
# Returns the plural form of the word in the string.
#
+ # If passed an optional +locale+ parameter, the word will be
+ # pluralized using rules defined for that language. By default,
+ # this parameter is set to <tt>:en</tt>.
+ #
# "post".pluralize # => "posts"
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
# "CamelOctopus".pluralize # => "CamelOctopi"
- def pluralize(word)
- apply_inflections(word, inflections.plurals)
+ # "ley".pluralize(:es) # => "leyes"
+ def pluralize(word, locale = :en)
+ apply_inflections(word, inflections(locale).plurals)
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
#
+ # If passed an optional +locale+ parameter, the word will be
+ # pluralized using rules defined for that language. By default,
+ # this parameter is set to <tt>:en</tt>.
+ #
# "posts".singularize # => "post"
# "octopi".singularize # => "octopus"
# "sheep".singularize # => "sheep"
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
- def singularize(word)
- apply_inflections(word, inflections.singulars)
+ # "leyes".singularize(:es) # => "ley"
+ def singularize(word, locale = :en)
+ apply_inflections(word, inflections(locale).singulars)
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index c319e94bc6..1a95bd63e6 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/object/to_json'
require 'active_support/core_ext/module/delegation'
+require 'active_support/json/variable'
require 'bigdecimal'
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
@@ -161,38 +162,67 @@ class Struct #:nodoc:
end
class TrueClass
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) to_s end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ to_s
+ end
end
class FalseClass
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) to_s end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ to_s
+ end
end
class NilClass
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) 'null' end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ 'null'
+ end
end
class String
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) encoder.escape(self) end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ encoder.escape(self)
+ end
end
class Symbol
- def as_json(options = nil) to_s end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
end
class Numeric
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) to_s end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ to_s
+ end
end
class Float
# Encoding Infinity or NaN to JSON should return "null". The default returns
# "Infinity" or "NaN" which breaks parsing the JSON. E.g. JSON.parse('[NaN]').
- def as_json(options = nil) finite? ? self : nil end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ finite? ? self : nil
+ end
end
class BigDecimal
@@ -216,7 +246,9 @@ class BigDecimal
end
class Regexp
- def as_json(options = nil) to_s end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
end
module Enumerable
@@ -226,7 +258,9 @@ module Enumerable
end
class Range
- def as_json(options = nil) to_s end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
end
class Array
@@ -262,7 +296,7 @@ class Hash
Hash[subset.map { |k, v| [k.to_s, encoder.as_json(v, options)] }]
end
- def encode_json(encoder)
+ def encode_json(encoder) #:nodoc:
# values are encoded with use_options = false, because we don't want hash representations from ActiveModel to be
# processed once again with as_json with options, as this could cause unexpected results (i.e. missing fields);
diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb
new file mode 100644
index 0000000000..8af661a795
--- /dev/null
+++ b/activesupport/lib/active_support/json/variable.rb
@@ -0,0 +1,17 @@
+require 'active_support/deprecation'
+
+module ActiveSupport
+ module JSON
+ # Deprecated: A string that returns itself as its JSON-encoded form.
+ class Variable < String
+ def initialize(*args)
+ ActiveSupport::Deprecation.warn 'ActiveSupport::JSON::Variable is deprecated and will be removed in Rails 4.1. ' \
+ 'For your own custom JSON literals, define #as_json and #encode_json yourself.'
+ super
+ end
+
+ def as_json(options = nil) self end #:nodoc:
+ def encode_json(encoder) self end #:nodoc:
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/locale/en.yml b/activesupport/lib/active_support/locale/en.yml
index 18c7d47026..f4900dc935 100644
--- a/activesupport/lib/active_support/locale/en.yml
+++ b/activesupport/lib/active_support/locale/en.yml
@@ -49,7 +49,7 @@ en:
significant: false
# If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
strip_insignificant_zeros: false
-
+
# Used in NumberHelper.number_to_currency()
currency:
format:
@@ -62,7 +62,7 @@ en:
precision: 2
significant: false
strip_insignificant_zeros: false
-
+
# Used in NumberHelper.number_to_percentage()
percentage:
format:
@@ -73,7 +73,7 @@ en:
# significant: false
# strip_insignificant_zeros: false
format: "%n%"
-
+
# Used in NumberHelper.number_to_rounded()
precision:
format:
@@ -83,7 +83,7 @@ en:
# precision:
# significant: false
# strip_insignificant_zeros: false
-
+
# Used in NumberHelper.number_to_human_size() and NumberHelper.number_to_human()
human:
format:
@@ -131,5 +131,3 @@ en:
billion: Billion
trillion: Trillion
quadrillion: Quadrillion
-
- \ No newline at end of file
diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb
index 6ffc091233..2e5bcf4639 100644
--- a/activesupport/lib/active_support/notifications/fanout.rb
+++ b/activesupport/lib/active_support/notifications/fanout.rb
@@ -59,10 +59,10 @@ module ActiveSupport
module Subscribers # :nodoc:
def self.new(pattern, listener)
- if listener.respond_to?(:call)
- subscriber = Timed.new pattern, listener
- else
+ if listener.respond_to?(:start) and listener.respond_to?(:finish)
subscriber = Evented.new pattern, listener
+ else
+ subscriber = Timed.new pattern, listener
end
unless pattern
diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb
index 99f6489adb..3849f94a31 100644
--- a/activesupport/lib/active_support/number_helper.rb
+++ b/activesupport/lib/active_support/number_helper.rb
@@ -7,12 +7,108 @@ module ActiveSupport
module NumberHelper
extend self
+ DEFAULTS = {
+ # Used in number_to_delimited
+ # These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
+ format: {
+ # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
+ separator: ".",
+ # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three)
+ delimiter: ",",
+ # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
+ precision: 3,
+ # If set to true, precision will mean the number of significant digits instead
+ # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2)
+ significant: false,
+ # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
+ strip_insignificant_zeros: false
+ },
+
+ # Used in number_to_currency
+ currency: {
+ format: {
+ format: "%u%n",
+ negative_format: "-%u%n",
+ unit: "$",
+ # These five are to override number.format and are optional
+ separator: ".",
+ delimiter: ",",
+ precision: 2,
+ significant: false,
+ strip_insignificant_zeros: false
+ }
+ },
+
+ # Used in number_to_percentage
+ percentage: {
+ format: {
+ delimiter: "",
+ format: "%n%"
+ }
+ },
+
+ # Used in number_to_rounded
+ precision: {
+ format: {
+ delimiter: ""
+ }
+ },
+
+ # Used in number_to_human_size and number_to_human
+ human: {
+ format: {
+ # These five are to override number.format and are optional
+ delimiter: "",
+ precision: 3,
+ significant: true,
+ strip_insignificant_zeros: true
+ },
+ # Used in number_to_human_size
+ storage_units: {
+ # Storage units output formatting.
+ # %u is the storage unit, %n is the number (default: 2 MB)
+ format: "%n %u",
+ units: {
+ byte: "Bytes",
+ kb: "KB",
+ mb: "MB",
+ gb: "GB",
+ tb: "TB"
+ }
+ },
+ # Used in number_to_human
+ decimal_units: {
+ format: "%n %u",
+ # Decimal units output formatting
+ # By default we will only quantify some of the exponents
+ # but the commented ones might be defined or overridden
+ # by the user.
+ units: {
+ # femto: Quadrillionth
+ # pico: Trillionth
+ # nano: Billionth
+ # micro: Millionth
+ # mili: Thousandth
+ # centi: Hundredth
+ # deci: Tenth
+ unit: "",
+ # ten:
+ # one: Ten
+ # other: Tens
+ # hundred: Hundred
+ thousand: "Thousand",
+ million: "Million",
+ billion: "Billion",
+ trillion: "Trillion",
+ quadrillion: "Quadrillion"
+ }
+ }
+ }
+ }
+
DECIMAL_UNITS = { 0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
-1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto }
- DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :negative_format => "-%u%n", :unit => "$", :separator => ".", :delimiter => ",",
- :precision => 2, :significant => false, :strip_insignificant_zeros => false }
-
STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb]
# Formats a +number+ into a US phone number (e.g., (555)
@@ -106,10 +202,10 @@ module ActiveSupport
return unless number
options = options.symbolize_keys
- currency = translations_for('currency', options[:locale])
+ currency = i18n_format_options(options[:locale], :currency)
currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
- defaults = DEFAULT_CURRENCY_VALUES.merge(defaults_translations(options[:locale])).merge!(currency)
+ defaults = default_format_options(:currency).merge!(currency)
defaults[:negative_format] = "-" + options[:format] if options[:format]
options = defaults.merge!(options)
@@ -160,7 +256,7 @@ module ActiveSupport
return unless number
options = options.symbolize_keys
- defaults = format_translations('percentage', options[:locale])
+ defaults = format_options(options[:locale], :percentage)
options = defaults.merge!(options)
format = options[:format] || "%n%"
@@ -197,7 +293,7 @@ module ActiveSupport
return number unless valid_float?(number)
- options = defaults_translations(options[:locale]).merge(options)
+ options = format_options(options[:locale]).merge!(options)
parts = number.to_s.to_str.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
@@ -248,7 +344,7 @@ module ActiveSupport
number = Float(number)
options = options.symbolize_keys
- defaults = format_translations('precision', options[:locale])
+ defaults = format_options(options[:locale], :precision)
options = defaults.merge!(options)
precision = options.delete :precision
@@ -328,18 +424,18 @@ module ActiveSupport
return number unless valid_float?(number)
number = Float(number)
- defaults = format_translations('human', options[:locale])
+ defaults = format_options(options[:locale], :human)
options = defaults.merge!(options)
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
- storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
+ storage_units_format = translate_number_value_with_default('human.storage_units.format', :locale => options[:locale], :raise => true)
base = options[:prefix] == :si ? 1000 : 1024
if number.to_i < base
- unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
+ unit = translate_number_value_with_default('human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
else
max_exp = STORAGE_UNITS.size - 1
@@ -348,7 +444,7 @@ module ActiveSupport
number /= base ** exponent
unit_key = STORAGE_UNITS[exponent]
- unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
+ unit = translate_number_value_with_default("human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
formatted_number = self.number_to_rounded(number, options)
storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)
@@ -458,7 +554,7 @@ module ActiveSupport
return number unless valid_float?(number)
number = Float(number)
- defaults = format_translations('human', options[:locale])
+ defaults = format_options(options[:locale], :human)
options = defaults.merge!(options)
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
@@ -473,7 +569,7 @@ module ActiveSupport
when String, Symbol
I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
when nil
- I18n.translate(:"number.human.decimal_units.units", :locale => options[:locale], :raise => true)
+ translate_number_value_with_default("human.decimal_units.units", :locale => options[:locale], :raise => true)
else
raise ArgumentError, ":units must be a Hash or String translation scope."
end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
@@ -488,34 +584,47 @@ module ActiveSupport
when String, Symbol
I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
else
- I18n.translate(:"number.human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
+ translate_number_value_with_default("human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
end
- decimal_format = options[:format] || I18n.translate(:'number.human.decimal_units.format', :locale => options[:locale], :default => "%n %u")
+ decimal_format = options[:format] || translate_number_value_with_default('human.decimal_units.format', :locale => options[:locale])
formatted_number = self.number_to_rounded(number, options)
decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip
end
- def self.private_module_and_instance_method(method_name)
+ def self.private_module_and_instance_method(method_name) #:nodoc:
private method_name
private_class_method method_name
end
private_class_method :private_module_and_instance_method
- def format_translations(namespace, locale) #:nodoc:
- defaults_translations(locale).merge(translations_for(namespace, locale))
+ def format_options(locale, namespace = nil) #:nodoc:
+ default_format_options(namespace).merge!(i18n_format_options(locale, namespace))
+ end
+ private_module_and_instance_method :format_options
+
+ def default_format_options(namespace = nil) #:nodoc:
+ options = DEFAULTS[:format].dup
+ options.merge!(DEFAULTS[namespace][:format]) if namespace
+ options
end
- private_module_and_instance_method :format_translations
+ private_module_and_instance_method :default_format_options
- def defaults_translations(locale) #:nodoc:
- I18n.translate(:'number.format', :locale => locale, :default => {})
+ def i18n_format_options(locale, namespace = nil) #:nodoc:
+ options = I18n.translate(:'number.format', locale: locale, default: {}).dup
+ if namespace
+ options.merge!(I18n.translate(:"number.#{namespace}.format", locale: locale, default: {}))
+ end
+ options
end
- private_module_and_instance_method :defaults_translations
+ private_module_and_instance_method :i18n_format_options
+
+ def translate_number_value_with_default(key, i18n_options = {}) #:nodoc:
+ default = key.split('.').reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] }
- def translations_for(namespace, locale) #:nodoc:
- I18n.translate(:"number.#{namespace}.format", :locale => locale, :default => {})
+ I18n.translate(key, { default: default, scope: :number }.merge!(i18n_options))
end
- private_module_and_instance_method :translations_for
+ private_module_and_instance_method :translate_number_value_with_default
def valid_float?(number) #:nodoc:
Float(number)
diff --git a/activesupport/lib/active_support/rails.rb b/activesupport/lib/active_support/rails.rb
new file mode 100644
index 0000000000..b05c3ff126
--- /dev/null
+++ b/activesupport/lib/active_support/rails.rb
@@ -0,0 +1,27 @@
+# This is private interface.
+#
+# Rails components cherry pick from Active Support as needed, but there are a
+# few features that are used for sure some way or another and it is not worth
+# to put individual requires absolutely everywhere. Think blank? for example.
+#
+# This file is loaded by every Rails component except Active Support itself,
+# but it does not belong to the Rails public interface. It is internal to
+# Rails and can change anytime.
+
+# Defines Object#blank? and Object#present?.
+require 'active_support/core_ext/object/blank'
+
+# Rails own autoload, eager_load, etc.
+require 'active_support/dependencies/autoload'
+
+# Support for ClassMethods and the included macro.
+require 'active_support/concern'
+
+# Defines Class#class_attribute.
+require 'active_support/core_ext/class/attribute'
+
+# Defines Module#delegate.
+require 'active_support/core_ext/module/delegation'
+
+# Defines ActiveSupport::Deprecation.
+require 'active_support/deprecation'
diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb
index 30ac881090..aa8d408da9 100644
--- a/activesupport/lib/active_support/railtie.rb
+++ b/activesupport/lib/active_support/railtie.rb
@@ -5,6 +5,8 @@ module ActiveSupport
class Railtie < Rails::Railtie
config.active_support = ActiveSupport::OrderedOptions.new
+ config.eager_load_namespaces << ActiveSupport
+
initializer "active_support.deprecation_behavior" do |app|
if deprecation = app.config.active_support.deprecation
ActiveSupport::Deprecation.behavior = deprecation
diff --git a/activesupport/lib/active_support/string_inquirer.rb b/activesupport/lib/active_support/string_inquirer.rb
index f3f3909a90..5f20bfa7bc 100644
--- a/activesupport/lib/active_support/string_inquirer.rb
+++ b/activesupport/lib/active_support/string_inquirer.rb
@@ -10,12 +10,18 @@ module ActiveSupport
# Rails.env.production?
#
class StringInquirer < String
- def method_missing(method_name, *arguments)
- if method_name[-1, 1] == "?"
- self == method_name[0..-2]
- else
- super
+ private
+
+ def respond_to_missing?(method_name, include_private = false)
+ method_name[-1] == '?'
+ end
+
+ def method_missing(method_name, *arguments)
+ if method_name[-1] == '?'
+ self == method_name[0..-2]
+ else
+ super
+ end
end
- end
end
end
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index a6f3b43792..d2b8e602f9 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -3,25 +3,19 @@ require 'minitest/spec'
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/mocha_module'
require 'active_support/core_ext/kernel/reporting'
+require 'active_support/deprecation'
module ActiveSupport
class TestCase < ::MiniTest::Spec
include ActiveSupport::Testing::MochaModule
- if MiniTest::Unit::VERSION < '2.6.1'
- class << self
- alias :name :to_s
- end
- end
-
# Use AS::TestCase for the base class when describing a model
register_spec_type(self) do |desc|
- desc < ActiveRecord::Model
+ Class === desc && desc < ActiveRecord::Model
end
Assertion = MiniTest::Assertion
@@ -41,7 +35,24 @@ module ActiveSupport
include ActiveSupport::Testing::SetupAndTeardown
include ActiveSupport::Testing::Assertions
include ActiveSupport::Testing::Deprecation
- extend ActiveSupport::Testing::Declarative
+
+ def self.describe(text)
+ if block_given?
+ super
+ else
+ ActiveSupport::Deprecation.warn("`describe` without a block is deprecated, please switch to: `def self.name; #{text.inspect}; end`\n")
+
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def self.name
+ "#{text}"
+ end
+ RUBY_EVAL
+ end
+ end
+
+ class << self
+ alias :test :it
+ end
# test/unit backwards compatibility methods
alias :assert_raise :assert_raises
diff --git a/activesupport/lib/active_support/testing/declarative.rb b/activesupport/lib/active_support/testing/declarative.rb
deleted file mode 100644
index 508e37254a..0000000000
--- a/activesupport/lib/active_support/testing/declarative.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-module ActiveSupport
- module Testing
- module Declarative
-
- def self.extended(klass) #:nodoc:
- klass.class_eval do
-
- unless method_defined?(:describe)
- def self.describe(text)
- class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def self.name
- "#{text}"
- end
- RUBY_EVAL
- end
- end
-
- end
- end
-
- unless defined?(Spec)
- # test "verify something" do
- # ...
- # end
- def test(name, &block)
- test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
- defined = instance_method(test_name) rescue false
- raise "#{test_name} is already defined in #{self}" if defined
- if block_given?
- define_method(test_name, &block)
- else
- define_method(test_name) do
- flunk "No implementation provided for #{name}"
- end
- end
- end
- end
- end
- end
-end
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 451520ac5c..93c2d614f5 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -1,6 +1,5 @@
require 'active_support/values/time_zone'
require 'active_support/core_ext/object/acts_like'
-require 'active_support/core_ext/object/inclusion'
module ActiveSupport
# A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are
@@ -339,7 +338,7 @@ module ActiveSupport
end
def duration_of_variable_length?(obj)
- ActiveSupport::Duration === obj && obj.parts.any? {|p| p[0].in?([:years, :months, :days]) }
+ ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
end
def wrap_with_time_zone(time)
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index 25ed962c23..8a67b148c3 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -21,15 +21,5 @@ require 'empty_bool'
ENV['NO_RELOAD'] = '1'
require 'active_support'
-def uses_memcached(test_name)
- require 'memcache'
- begin
- MemCache.new('localhost:11211').stats
- yield
- rescue MemCache::MemCacheError
- $stderr.puts "Skipping #{test_name} tests. Start memcached and try again."
- end
-end
-
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
diff --git a/activesupport/test/autoload.rb b/activesupport/test/autoload_test.rb
index 5d8026a9ca..7d02d835a8 100644
--- a/activesupport/test/autoload.rb
+++ b/activesupport/test/autoload_test.rb
@@ -28,15 +28,6 @@ class TestAutoloadModule < ActiveSupport::TestCase
assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end
- test ":eager constants can be triggered via ActiveSupport::Autoload.eager_autoload!" do
- module ::Fixtures::Autoload
- autoload :SomeClass, "fixtures/autoload/some_class"
- end
- ActiveSupport::Autoload.eager_autoload!
- assert $LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
- assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
- end
-
test "the location of autoloaded constants defaults to :name.underscore" do
module ::Fixtures::Autoload
autoload :SomeClass
@@ -51,8 +42,7 @@ class TestAutoloadModule < ActiveSupport::TestCase
autoload :SomeClass
end
- ActiveSupport::Autoload.eager_autoload!
- assert $LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ ::Fixtures::Autoload.eager_load!
assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end
diff --git a/activesupport/test/autoloading_fixtures/circular1.rb b/activesupport/test/autoloading_fixtures/circular1.rb
new file mode 100644
index 0000000000..a45761f066
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/circular1.rb
@@ -0,0 +1,6 @@
+silence_warnings do
+ Circular2
+end
+
+class Circular1
+end
diff --git a/activesupport/test/autoloading_fixtures/circular2.rb b/activesupport/test/autoloading_fixtures/circular2.rb
new file mode 100644
index 0000000000..c847fa5001
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/circular2.rb
@@ -0,0 +1,4 @@
+Circular1
+
+class Circular2
+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 ef66ddaac7..402609c583 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,3 @@
class ClassFolder::ClassFolderSubclass < ClassFolder
- ConstantInClassFolder
+ ConstantInClassFolder = 'indeed'
end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index a75db47be8..71cd9d81b3 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -83,20 +83,20 @@ class CacheStoreSettingTest < ActiveSupport::TestCase
end
def test_mem_cache_fragment_cache_store
- MemCache.expects(:new).with(%w[localhost], {})
+ Dalli::Client.expects(:new).with(%w[localhost], {})
store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost"
assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
end
def test_mem_cache_fragment_cache_store_with_given_mem_cache
- mem_cache = MemCache.new
- MemCache.expects(:new).never
+ mem_cache = Dalli::Client.new
+ Dalli::Client.expects(:new).never
store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache
assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
end
def test_mem_cache_fragment_cache_store_with_given_mem_cache_like_object
- MemCache.expects(:new).never
+ Dalli::Client.expects(:new).never
memcache = Object.new
def memcache.get() true end
store = ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
@@ -104,13 +104,13 @@ class CacheStoreSettingTest < ActiveSupport::TestCase
end
def test_mem_cache_fragment_cache_store_with_multiple_servers
- MemCache.expects(:new).with(%w[localhost 192.168.1.1], {})
+ Dalli::Client.expects(:new).with(%w[localhost 192.168.1.1], {})
store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1'
assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
end
def test_mem_cache_fragment_cache_store_with_options
- MemCache.expects(:new).with(%w[localhost 192.168.1.1], { :timeout => 10 })
+ Dalli::Client.expects(:new).with(%w[localhost 192.168.1.1], { :timeout => 10 })
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]
@@ -447,6 +447,7 @@ module CacheIncrementDecrementBehavior
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
@@ -456,6 +457,7 @@ module CacheIncrementDecrementBehavior
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
@@ -702,53 +704,65 @@ class MemoryStoreTest < ActiveSupport::TestCase
end
end
-uses_memcached 'memcached backed store' do
- class MemCacheStoreTest < ActiveSupport::TestCase
- def setup
- @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
+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
+
+ 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
- include CacheStoreBehavior
- include LocalCacheBehavior
- include CacheIncrementDecrementBehavior
- include EncodedKeyCacheBehavior
+ 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_raw_values
- cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
- cache.clear
+ 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_raw_values_with_marshal
- cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
- cache.clear
+ 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
-
- 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
end
end
diff --git a/activesupport/test/core_ext/date_and_time_behavior.rb b/activesupport/test/core_ext/date_and_time_behavior.rb
new file mode 100644
index 0000000000..014935b0c0
--- /dev/null
+++ b/activesupport/test/core_ext/date_and_time_behavior.rb
@@ -0,0 +1,186 @@
+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
+ 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
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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
+ 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)
+ 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
+ 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
+ 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
+ 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
+ end
+
+ def test_next_week
+ 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_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
+ 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
+ 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
+ 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)
+ 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
+ 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
+ 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
+ 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)
+ 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
+ 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
+ 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
+ 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
+ end
+end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index 088b74a29a..7ae1f67785 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -1,7 +1,22 @@
require 'abstract_unit'
require 'active_support/time'
+require 'core_ext/date_and_time_behavior'
class DateExtCalculationsTest < ActiveSupport::TestCase
+ def date_time_init(year,month,day,*args)
+ Date.new(year,month,day)
+ end
+
+ include DateAndTimeBehavior
+
+ def test_yesterday_in_calendar_reform
+ 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
+ end
+
def test_to_s
date = Date.new(2005, 2, 21)
assert_equal "2005-02-21", date.to_s
@@ -46,22 +61,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(2005,6,22), Date.new(2005,2,22).change(:month => 6)
end
- def test_beginning_of_week
- assert_equal Date.new(2005,1,31), Date.new(2005,2,4).beginning_of_week
- assert_equal Date.new(2005,11,28), Date.new(2005,11,28).beginning_of_week #monday
- assert_equal Date.new(2005,11,28), Date.new(2005,11,29).beginning_of_week #tuesday
- assert_equal Date.new(2005,11,28), Date.new(2005,11,30).beginning_of_week #wednesday
- assert_equal Date.new(2005,11,28), Date.new(2005,12,01).beginning_of_week #thursday
- assert_equal Date.new(2005,11,28), Date.new(2005,12,02).beginning_of_week #friday
- assert_equal Date.new(2005,11,28), Date.new(2005,12,03).beginning_of_week #saturday
- assert_equal Date.new(2005,11,28), Date.new(2005,12,04).beginning_of_week #sunday
- end
-
- def test_monday
- assert_equal Date.new(2005,11,28), Date.new(2005,11,28).monday
- assert_equal Date.new(2005,11,28), Date.new(2005,12,01).monday
- 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
@@ -71,41 +70,10 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(1582,10,1), Date.new(1582,10,15).beginning_of_week #friday
end
- def test_beginning_of_month
- assert_equal Date.new(2005,2,1), Date.new(2005,2,22).beginning_of_month
- end
-
- def test_beginning_of_quarter
- assert_equal Date.new(2005,1,1), Date.new(2005,2,15).beginning_of_quarter
- assert_equal Date.new(2005,1,1), Date.new(2005,1,1).beginning_of_quarter
- assert_equal Date.new(2005,10,1), Date.new(2005,12,31).beginning_of_quarter
- assert_equal Date.new(2005,4,1), Date.new(2005,6,30).beginning_of_quarter
- end
-
- def test_end_of_week
- assert_equal Date.new(2008,2,24), Date.new(2008,2,22).end_of_week
- assert_equal Date.new(2008,3,2), Date.new(2008,2,25).end_of_week #monday
- assert_equal Date.new(2008,3,2), Date.new(2008,2,26).end_of_week #tuesday
- assert_equal Date.new(2008,3,2), Date.new(2008,2,27).end_of_week #wednesday
- assert_equal Date.new(2008,3,2), Date.new(2008,2,28).end_of_week #thursday
- assert_equal Date.new(2008,3,2), Date.new(2008,2,29).end_of_week #friday
- assert_equal Date.new(2008,3,2), Date.new(2008,3,01).end_of_week #saturday
- assert_equal Date.new(2008,3,2), Date.new(2008,3,02).end_of_week #sunday
- 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
end
- def test_end_of_quarter
- assert_equal Date.new(2008,3,31), Date.new(2008,2,15).end_of_quarter
- assert_equal Date.new(2008,3,31), Date.new(2008,3,31).end_of_quarter
- assert_equal Date.new(2008,12,31), Date.new(2008,10,8).end_of_quarter
- assert_equal Date.new(2008,6,30), Date.new(2008,4,14).end_of_quarter
- assert_equal Date.new(2008,6,30), Date.new(2008,5,31).end_of_quarter
- assert_equal Date.new(2008,9,30), Date.new(2008,8,21).end_of_quarter
- 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
end
@@ -116,57 +84,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(2005,4,30), Date.new(2005,4,20).end_of_month
end
- def test_beginning_of_year
- assert_equal Date.new(2005,1,1).to_s, Date.new(2005,2,22).beginning_of_year.to_s
- end
-
- def test_weeks_ago
- assert_equal Date.new(2005,5,10), Date.new(2005,5,17).weeks_ago(1)
- assert_equal Date.new(2005,5,10), Date.new(2005,5,24).weeks_ago(2)
- assert_equal Date.new(2005,5,10), Date.new(2005,5,31).weeks_ago(3)
- assert_equal Date.new(2005,5,10), Date.new(2005,6,7).weeks_ago(4)
- assert_equal Date.new(2006,12,31), Date.new(2007,2,4).weeks_ago(5)
- end
-
- def test_months_ago
- assert_equal Date.new(2005,5,5), Date.new(2005,6,5).months_ago(1)
- assert_equal Date.new(2004,11,5), Date.new(2005,6,5).months_ago(7)
- assert_equal Date.new(2004,12,5), Date.new(2005,6,5).months_ago(6)
- assert_equal Date.new(2004,6,5), Date.new(2005,6,5).months_ago(12)
- assert_equal Date.new(2003,6,5), Date.new(2005,6,5).months_ago(24)
- end
-
- def test_months_since
- assert_equal Date.new(2005,7,5), Date.new(2005,6,5).months_since(1)
- assert_equal Date.new(2006,1,5), Date.new(2005,12,5).months_since(1)
- assert_equal Date.new(2005,12,5), Date.new(2005,6,5).months_since(6)
- assert_equal Date.new(2006,6,5), Date.new(2005,12,5).months_since(6)
- assert_equal Date.new(2006,1,5), Date.new(2005,6,5).months_since(7)
- assert_equal Date.new(2006,6,5), Date.new(2005,6,5).months_since(12)
- assert_equal Date.new(2007,6,5), Date.new(2005,6,5).months_since(24)
- assert_equal Date.new(2005,4,30), Date.new(2005,3,31).months_since(1)
- assert_equal Date.new(2005,2,28), Date.new(2005,1,29).months_since(1)
- assert_equal Date.new(2005,2,28), Date.new(2005,1,30).months_since(1)
- assert_equal Date.new(2005,2,28), Date.new(2005,1,31).months_since(1)
- end
-
- def test_years_ago
- assert_equal Date.new(2004,6,5), Date.new(2005,6,5).years_ago(1)
- assert_equal Date.new(1998,6,5), Date.new(2005,6,5).years_ago(7)
- assert_equal Date.new(2003,2,28), Date.new(2004,2,29).years_ago(1) # 1 year ago from leap day
- end
-
- def test_years_since
- assert_equal Date.new(2006,6,5), Date.new(2005,6,5).years_since(1)
- assert_equal Date.new(2012,6,5), Date.new(2005,6,5).years_since(7)
- assert_equal Date.new(2182,6,5), Date.new(2005,6,5).years_since(177)
- assert_equal Date.new(2005,2,28), Date.new(2004,2,29).years_since(1) # 1 year since leap day
- end
-
- def test_prev_year
- assert_equal Date.new(2004,6,5), Date.new(2005,6,5).prev_year
- end
-
def test_prev_year_in_leap_years
assert_equal Date.new(1999,2,28), Date.new(2000,2,29).prev_year
end
@@ -187,10 +104,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(1582,10,4), Date.new(1583,10,14).last_year
end
- def test_next_year
- assert_equal Date.new(2006,6,5), Date.new(2005,6,5).next_year
- end
-
def test_next_year_in_leap_years
assert_equal Date.new(2001,2,28), Date.new(2000,2,29).next_year
end
@@ -199,24 +112,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(1582,10,4), Date.new(1581,10,10).next_year
end
- def test_yesterday
- assert_equal Date.new(2005,2,21), Date.new(2005,2,22).yesterday
- assert_equal Date.new(2005,2,28), Date.new(2005,3,2).yesterday.yesterday
- end
-
- def test_yesterday_in_calendar_reform
- assert_equal Date.new(1582,10,4), Date.new(1582,10,15).yesterday
- end
-
- def test_tomorrow
- assert_equal Date.new(2005,2,23), Date.new(2005,2,22).tomorrow
- assert_equal Date.new(2005,3,2), Date.new(2005,2,28).tomorrow.tomorrow
- end
-
- def test_tomorrow_in_calendar_reform
- assert_equal Date.new(1582,10,15), Date.new(1582,10,4).tomorrow
- 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)
@@ -249,14 +144,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_prev_week
- assert_equal Date.new(2005,5,9), Date.new(2005,5,17).prev_week
- assert_equal Date.new(2006,12,25), Date.new(2007,1,7).prev_week
- assert_equal Date.new(2010,2,12), Date.new(2010,2,19).prev_week(:friday)
- assert_equal Date.new(2010,2,13), Date.new(2010,2,19).prev_week(:saturday)
- assert_equal Date.new(2010,2,27), Date.new(2010,3,4).prev_week(:saturday)
- 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
@@ -265,38 +152,15 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(2010,2,27), Date.new(2010,3,4).last_week(:saturday)
end
- def test_next_week
- assert_equal Date.new(2005,2,28), Date.new(2005,2,22).next_week
- assert_equal Date.new(2005,3,4), Date.new(2005,2,22).next_week(:friday)
- assert_equal Date.new(2006,10,30), Date.new(2006,10,23).next_week
- assert_equal Date.new(2006,11,1), Date.new(2006,10,23).next_week(:wednesday)
- 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_next_month_on_31st
- assert_equal Date.new(2005, 9, 30), Date.new(2005, 8, 31).next_month
- end
-
- def test_prev_month_on_31st
- assert_equal Date.new(2004, 2, 29), Date.new(2004, 3, 31).prev_month
- end
-
def test_last_month_on_31st
assert_equal Date.new(2004, 2, 29), Date.new(2004, 3, 31).last_month
end
- def test_next_quarter_on_31st
- assert_equal Date.new(2005, 11, 30), Date.new(2005, 8, 31).next_quarter
- end
-
- def test_prev_quarter_on_31st
- assert_equal Date.new(2004, 2, 29), Date.new(2004, 5, 31).prev_quarter
- end
-
def test_last_quarter_on_31st
assert_equal Date.new(2004, 2, 29), Date.new(2004, 5, 31).last_quarter
end
@@ -420,13 +284,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_today
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, Date.new(1999, 12, 31).today?
- assert_equal true, Date.new(2000,1,1).today?
- assert_equal false, Date.new(2000,1,2).today?
- end
-
def test_past
Date.stubs(:current).returns(Date.new(2000, 1, 1))
assert_equal true, Date.new(1999, 12, 31).past?
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 21b7efdc73..b1d1e8ecb4 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -1,7 +1,14 @@
require 'abstract_unit'
require 'active_support/time'
+require 'core_ext/date_and_time_behavior'
class DateTimeExtCalculationsTest < ActiveSupport::TestCase
+ def date_time_init(year,month,day,hour,minute,second,*args)
+ DateTime.civil(year,month,day,hour,minute,second)
+ end
+
+ include DateAndTimeBehavior
+
def test_to_s
datetime = DateTime.new(2005, 2, 21, 14, 30, 0, 0)
assert_equal "2005-02-21 14:30:00", datetime.to_s(:db)
@@ -54,35 +61,6 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal 86399,DateTime.civil(2005,1,1,23,59,59).seconds_since_midnight
end
- def test_days_to_week_start
- assert_equal 0, Time.local(2011,11,01,0,0,0).days_to_week_start(:tuesday)
- assert_equal 1, Time.local(2011,11,02,0,0,0).days_to_week_start(:tuesday)
- assert_equal 2, Time.local(2011,11,03,0,0,0).days_to_week_start(:tuesday)
- assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
- assert_equal 4, Time.local(2011,11,05,0,0,0).days_to_week_start(:tuesday)
- assert_equal 5, Time.local(2011,11,06,0,0,0).days_to_week_start(:tuesday)
- assert_equal 6, Time.local(2011,11,07,0,0,0).days_to_week_start(:tuesday)
-
- assert_equal 3, Time.local(2011,11,03,0,0,0).days_to_week_start(:monday)
- assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
- assert_equal 3, Time.local(2011,11,05,0,0,0).days_to_week_start(:wednesday)
- assert_equal 3, Time.local(2011,11,06,0,0,0).days_to_week_start(:thursday)
- assert_equal 3, Time.local(2011,11,07,0,0,0).days_to_week_start(:friday)
- assert_equal 3, Time.local(2011,11,8,0,0,0).days_to_week_start(:saturday)
- assert_equal 3, Time.local(2011,11,9,0,0,0).days_to_week_start(:sunday)
- end
-
- def test_beginning_of_week
- assert_equal DateTime.civil(2005,1,31), DateTime.civil(2005,2,4,10,10,10).beginning_of_week
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,11,28,0,0,0).beginning_of_week #monday
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,11,29,0,0,0).beginning_of_week #tuesday
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,11,30,0,0,0).beginning_of_week #wednesday
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,12,01,0,0,0).beginning_of_week #thursday
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,12,02,0,0,0).beginning_of_week #friday
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,12,03,0,0,0).beginning_of_week #saturday
- assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,12,04,0,0,0).beginning_of_week #sunday
- 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
end
@@ -99,82 +77,16 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal DateTime.civil(2005,2,4,19,59,59), DateTime.civil(2005,2,4,19,30,10).end_of_hour
end
- def test_beginning_of_month
- assert_equal DateTime.civil(2005,2,1,0,0,0), DateTime.civil(2005,2,22,10,10,10).beginning_of_month
- end
-
- def test_beginning_of_quarter
- assert_equal DateTime.civil(2005,1,1,0,0,0), DateTime.civil(2005,2,15,10,10,10).beginning_of_quarter
- assert_equal DateTime.civil(2005,1,1,0,0,0), DateTime.civil(2005,1,1,0,0,0).beginning_of_quarter
- assert_equal DateTime.civil(2005,10,1,0,0,0), DateTime.civil(2005,12,31,10,10,10).beginning_of_quarter
- assert_equal DateTime.civil(2005,4,1,0,0,0), DateTime.civil(2005,6,30,23,59,59).beginning_of_quarter
- 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_beginning_of_year
- assert_equal DateTime.civil(2005,1,1,0,0,0), DateTime.civil(2005,2,22,10,10,10).beginning_of_year
- end
-
- def test_weeks_ago
- assert_equal DateTime.civil(2005,5,29,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(1)
- assert_equal DateTime.civil(2005,5,1,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(5)
- assert_equal DateTime.civil(2005,4,24,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(6)
- assert_equal DateTime.civil(2005,2,27,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(14)
- assert_equal DateTime.civil(2004,12,25,10), DateTime.civil(2005,1,1,10,0,0).weeks_ago(1)
- end
-
- def test_months_ago
- assert_equal DateTime.civil(2005,5,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(1)
- assert_equal DateTime.civil(2004,11,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(7)
- assert_equal DateTime.civil(2004,12,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(6)
- assert_equal DateTime.civil(2004,6,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(12)
- assert_equal DateTime.civil(2003,6,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(24)
- end
-
- def test_months_since
- assert_equal DateTime.civil(2005,7,5,10), DateTime.civil(2005,6,5,10,0,0).months_since(1)
- assert_equal DateTime.civil(2006,1,5,10), DateTime.civil(2005,12,5,10,0,0).months_since(1)
- assert_equal DateTime.civil(2005,12,5,10), DateTime.civil(2005,6,5,10,0,0).months_since(6)
- assert_equal DateTime.civil(2006,6,5,10), DateTime.civil(2005,12,5,10,0,0).months_since(6)
- assert_equal DateTime.civil(2006,1,5,10), DateTime.civil(2005,6,5,10,0,0).months_since(7)
- assert_equal DateTime.civil(2006,6,5,10), DateTime.civil(2005,6,5,10,0,0).months_since(12)
- assert_equal DateTime.civil(2007,6,5,10), DateTime.civil(2005,6,5,10,0,0).months_since(24)
- assert_equal DateTime.civil(2005,4,30,10), DateTime.civil(2005,3,31,10,0,0).months_since(1)
- assert_equal DateTime.civil(2005,2,28,10), DateTime.civil(2005,1,29,10,0,0).months_since(1)
- assert_equal DateTime.civil(2005,2,28,10), DateTime.civil(2005,1,30,10,0,0).months_since(1)
- assert_equal DateTime.civil(2005,2,28,10), DateTime.civil(2005,1,31,10,0,0).months_since(1)
- end
-
- def test_years_ago
- assert_equal DateTime.civil(2004,6,5,10), DateTime.civil(2005,6,5,10,0,0).years_ago(1)
- assert_equal DateTime.civil(1998,6,5,10), DateTime.civil(2005,6,5,10,0,0).years_ago(7)
- assert_equal DateTime.civil(2003,2,28,10), DateTime.civil(2004,2,29,10,0,0).years_ago(1) # 1 year ago from leap day
- end
-
- def test_years_since
- assert_equal DateTime.civil(2006,6,5,10), DateTime.civil(2005,6,5,10,0,0).years_since(1)
- assert_equal DateTime.civil(2012,6,5,10), DateTime.civil(2005,6,5,10,0,0).years_since(7)
- assert_equal DateTime.civil(2182,6,5,10), DateTime.civil(2005,6,5,10,0,0).years_since(177)
- assert_equal DateTime.civil(2005,2,28,10), DateTime.civil(2004,2,29,10,0,0).years_since(1) # 1 year since leap day
- end
-
- def test_prev_year
- assert_equal DateTime.civil(2004,6,5,10), DateTime.civil(2005,6,5,10,0,0).prev_year
- end
-
def test_last_year
assert_equal DateTime.civil(2004,6,5,10), DateTime.civil(2005,6,5,10,0,0).last_year
end
- def test_next_year
- assert_equal DateTime.civil(2006,6,5,10), DateTime.civil(2005,6,5,10,0,0).next_year
- 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)
@@ -191,16 +103,6 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal DateTime.civil(2005,2,22,10,10,12), DateTime.civil(2005,2,22,10,10,10).since(1.667)
end
- def test_yesterday
- assert_equal DateTime.civil(2005,2,21,10,10,10), DateTime.civil(2005,2,22,10,10,10).yesterday
- assert_equal DateTime.civil(2005,2,28,10,10,10), DateTime.civil(2005,3,2,10,10,10).yesterday.yesterday
- end
-
- def test_tomorrow
- assert_equal DateTime.civil(2005,2,23,10,10,10), DateTime.civil(2005,2,22,10,10,10).tomorrow
- assert_equal DateTime.civil(2005,3,2,10,10,10), DateTime.civil(2005,2,28,10,10,10).tomorrow.tomorrow
- 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)
@@ -236,14 +138,6 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
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_prev_week
- assert_equal DateTime.civil(2005,2,21), DateTime.civil(2005,3,1,15,15,10).prev_week
- assert_equal DateTime.civil(2005,2,22), DateTime.civil(2005,3,1,15,15,10).prev_week(:tuesday)
- assert_equal DateTime.civil(2005,2,25), DateTime.civil(2005,3,1,15,15,10).prev_week(:friday)
- assert_equal DateTime.civil(2006,10,30), DateTime.civil(2006,11,6,0,0,0).prev_week
- assert_equal DateTime.civil(2006,11,15), DateTime.civil(2006,11,23,0,0,0).prev_week(:wednesday)
- 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)
@@ -252,33 +146,10 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal DateTime.civil(2006,11,15), DateTime.civil(2006,11,23,0,0,0).last_week(:wednesday)
end
- def test_next_week
- assert_equal DateTime.civil(2005,2,28), DateTime.civil(2005,2,22,15,15,10).next_week
- assert_equal DateTime.civil(2005,3,4), DateTime.civil(2005,2,22,15,15,10).next_week(:friday)
- assert_equal DateTime.civil(2006,10,30), DateTime.civil(2006,10,23,0,0,0).next_week
- assert_equal DateTime.civil(2006,11,1), DateTime.civil(2006,10,23,0,0,0).next_week(:wednesday)
- end
-
- def test_next_month_on_31st
- assert_equal DateTime.civil(2005, 9, 30), DateTime.civil(2005, 8, 31).next_month
- end
-
- def test_prev_month_on_31st
- assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 3, 31).prev_month
- end
-
def test_last_month_on_31st
assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 3, 31).last_month
end
- def test_next_quarter_on_31st
- assert_equal DateTime.civil(2005, 11, 30), DateTime.civil(2005, 8, 31).next_quarter
- end
-
- def test_prev_quarter_on_31st
- assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 5, 31).prev_quarter
- end
-
def test_last_quarter_on_31st
assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 5, 31).last_quarter
end
diff --git a/activesupport/test/core_ext/file_test.rb b/activesupport/test/core_ext/file_test.rb
index 128e956a8c..2c04e9687c 100644
--- a/activesupport/test/core_ext/file_test.rb
+++ b/activesupport/test/core_ext/file_test.rb
@@ -51,7 +51,7 @@ class AtomicWriteTest < ActiveSupport::TestCase
assert !File.exist?(file_name)
end
assert File.exist?(file_name)
- assert_equal 0100666 & ~File.umask, file_mode
+ assert_equal File.probe_stat_in(Dir.pwd).mode, file_mode
assert_equal contents, File.read(file_name)
ensure
File.unlink(file_name) rescue nil
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 4dc9f57038..37fdf1c0af 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -428,6 +428,29 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal 2, hash['b']
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('some' => 'value', 'other' => 'value')
hash.reverse_merge!(:some => 'noclobber', :another => 'clobber')
diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb
index 8af0b9a023..343a848a42 100644
--- a/activesupport/test/core_ext/module/qualified_const_test.rb
+++ b/activesupport/test/core_ext/module/qualified_const_test.rb
@@ -67,17 +67,24 @@ class QualifiedConstTest < ActiveSupport::TestCase
end
test "qualified_const_set" do
- 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
+ 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
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
index 98ab82609e..ec7dd6d4fb 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -99,13 +99,25 @@ class ObjectTryTest < ActiveSupport::TestCase
def test_nonexisting_method
method = :undefined_method
assert !@string.respond_to?(method)
- assert_raise(NoMethodError) { @string.try(method) }
+ assert_nil @string.try(method)
end
def test_nonexisting_method_with_arguments
method = :undefined_method
assert !@string.respond_to?(method)
- assert_raise(NoMethodError) { @string.try(method, 'llo', 'y') }
+ assert_nil @string.try(method, 'llo', 'y')
+ end
+
+ def test_nonexisting_method_bang
+ method = :undefined_method
+ assert !@string.respond_to?(method)
+ assert_raise(NoMethodError) { @string.try!(method) }
+ end
+
+ def test_nonexisting_method_with_arguments_bang
+ method = :undefined_method
+ assert !@string.respond_to?(method)
+ assert_raise(NoMethodError) { @string.try!(method, 'llo', 'y') }
end
def test_valid_method
@@ -139,6 +151,18 @@ class ObjectTryTest < ActiveSupport::TestCase
assert_equal false, ran
end
+ def test_try_with_private_method_bang
+ klass = Class.new do
+ private
+
+ def private_method
+ 'private method'
+ end
+ end
+
+ assert_raise(NoMethodError) { klass.new.try!(:private_method) }
+ end
+
def test_try_with_private_method
klass = Class.new do
private
@@ -148,6 +172,6 @@ class ObjectTryTest < ActiveSupport::TestCase
end
end
- assert_raise(NoMethodError) { klass.new.try(:private_method) }
+ assert_nil klass.new.try(:private_method)
end
end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index e5b774425e..dc5ae0eafc 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -9,6 +9,7 @@ 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'
module Ace
module Base
@@ -498,8 +499,8 @@ class OutputSafetyTest < ActiveSupport::TestCase
end
test "ERB::Util.html_escape should escape unsafe characters" do
- string = '<>&"'
- expected = '&lt;&gt;&amp;&quot;'
+ string = '<>&"\''
+ expected = '&lt;&gt;&amp;&quot;&#x27;'
assert_equal expected, ERB::Util.html_escape(string)
end
@@ -521,3 +522,58 @@ class StringExcludeTest < ActiveSupport::TestCase
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|
+ assert_nil str.indent!(8)
+ assert_equal str, str.indent(8)
+ assert_equal str, str.indent(1, "\t")
+ end
+ end
+
+ test "by default, indents with spaces if the existing indentation uses them" do
+ assert_equal " foo\n bar", "foo\n bar".indent(4)
+ end
+
+ test "by default, indents with tabs if the existing indentation uses them" do
+ assert_equal "\tfoo\n\t\t\bar", "foo\n\t\bar".indent(1)
+ end
+
+ test "by default, indents with spaces as a fallback if there is no indentation" do
+ assert_equal " foo\n bar\n baz", "foo\nbar\nbaz".indent(3)
+ end
+
+ # 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, '.')
+.... def some_method(x, y)
+.... some_code
+.... end
+EXPECTED
+ def some_method(x, y)
+ some_code
+ end
+ACTUAL
+
+ 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
+EXPECTED
+&nbsp;&nbsp;def some_method(x, y)
+&nbsp;&nbsp;&nbsp;&nbsp;some_code
+&nbsp;&nbsp;end
+ACTUAL
+ end
+
+ test "does not indent blank lines by default" do
+ assert_equal " foo\n\n bar", "foo\n\nbar".indent(1)
+ end
+
+ 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 412aef9301..6d6757a1b6 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -1,7 +1,14 @@
require 'abstract_unit'
require 'active_support/time'
+require 'core_ext/date_and_time_behavior'
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)
+ end
+
+ include DateAndTimeBehavior
+
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
@@ -50,37 +57,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_beginning_of_week
- assert_equal Time.local(2005,1,31), Time.local(2005,2,4,10,10,10).beginning_of_week
- assert_equal Time.local(2005,11,28), Time.local(2005,11,28,0,0,0).beginning_of_week #monday
- assert_equal Time.local(2005,11,28), Time.local(2005,11,29,0,0,0).beginning_of_week #tuesday
- assert_equal Time.local(2005,11,28), Time.local(2005,11,30,0,0,0).beginning_of_week #wednesday
- assert_equal Time.local(2005,11,28), Time.local(2005,12,01,0,0,0).beginning_of_week #thursday
- assert_equal Time.local(2005,11,28), Time.local(2005,12,02,0,0,0).beginning_of_week #friday
- assert_equal Time.local(2005,11,28), Time.local(2005,12,03,0,0,0).beginning_of_week #saturday
- assert_equal Time.local(2005,11,28), Time.local(2005,12,04,0,0,0).beginning_of_week #sunday
-
- end
-
- def test_days_to_week_start
- assert_equal 0, Time.local(2011,11,01,0,0,0).days_to_week_start(:tuesday)
- assert_equal 1, Time.local(2011,11,02,0,0,0).days_to_week_start(:tuesday)
- assert_equal 2, Time.local(2011,11,03,0,0,0).days_to_week_start(:tuesday)
- assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
- assert_equal 4, Time.local(2011,11,05,0,0,0).days_to_week_start(:tuesday)
- assert_equal 5, Time.local(2011,11,06,0,0,0).days_to_week_start(:tuesday)
- assert_equal 6, Time.local(2011,11,07,0,0,0).days_to_week_start(:tuesday)
-
- assert_equal 3, Time.local(2011,11,03,0,0,0).days_to_week_start(:monday)
- assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
- assert_equal 3, Time.local(2011,11,05,0,0,0).days_to_week_start(:wednesday)
- assert_equal 3, Time.local(2011,11,06,0,0,0).days_to_week_start(:thursday)
- assert_equal 3, Time.local(2011,11,07,0,0,0).days_to_week_start(:friday)
- assert_equal 3, Time.local(2011,11,8,0,0,0).days_to_week_start(:saturday)
- assert_equal 3, Time.local(2011,11,9,0,0,0).days_to_week_start(:sunday)
- 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
@@ -97,17 +73,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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_month
- assert_equal Time.local(2005,2,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_month
- end
-
- def test_beginning_of_quarter
- assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,2,15,10,10,10).beginning_of_quarter
- assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,1,1,0,0,0).beginning_of_quarter
- assert_equal Time.local(2005,10,1,0,0,0), Time.local(2005,12,31,10,10,10).beginning_of_quarter
- assert_equal Time.local(2005,4,1,0,0,0), Time.local(2005,6,30,23,59,59).beginning_of_quarter
- 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
@@ -120,100 +85,14 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_end_of_week
- assert_equal Time.local(2008,1,6,23,59,59,Rational(999999999, 1000)), Time.local(2007,12,31,10,10,10).end_of_week
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,27,0,0,0).end_of_week #monday
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,28,0,0,0).end_of_week #tuesday
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,29,0,0,0).end_of_week #wednesday
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,30,0,0,0).end_of_week #thursday
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,31,0,0,0).end_of_week #friday
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,9,01,0,0,0).end_of_week #saturday
- assert_equal Time.local(2007,9,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,9,02,0,0,0).end_of_week #sunday
- 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
end
- def test_end_of_month
- assert_equal Time.local(2005,3,31,23,59,59,Rational(999999999, 1000)), Time.local(2005,3,20,10,10,10).end_of_month
- assert_equal Time.local(2005,2,28,23,59,59,Rational(999999999, 1000)), Time.local(2005,2,20,10,10,10).end_of_month
- assert_equal Time.local(2005,4,30,23,59,59,Rational(999999999, 1000)), Time.local(2005,4,20,10,10,10).end_of_month
- end
-
- def test_end_of_quarter
- assert_equal Time.local(2007,3,31,23,59,59,Rational(999999999, 1000)), Time.local(2007,2,15,10,10,10).end_of_quarter
- assert_equal Time.local(2007,3,31,23,59,59,Rational(999999999, 1000)), Time.local(2007,3,31,0,0,0).end_of_quarter
- assert_equal Time.local(2007,12,31,23,59,59,Rational(999999999, 1000)), Time.local(2007,12,21,10,10,10).end_of_quarter
- assert_equal Time.local(2007,6,30,23,59,59,Rational(999999999, 1000)), Time.local(2007,4,1,0,0,0).end_of_quarter
- assert_equal Time.local(2008,6,30,23,59,59,Rational(999999999, 1000)), Time.local(2008,5,31,0,0,0).end_of_quarter
- end
-
- def test_end_of_year
- assert_equal Time.local(2007,12,31,23,59,59,Rational(999999999, 1000)), Time.local(2007,2,22,10,10,10).end_of_year
- assert_equal Time.local(2007,12,31,23,59,59,Rational(999999999, 1000)), Time.local(2007,12,31,10,10,10).end_of_year
- end
-
- def test_beginning_of_year
- assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_year
- end
-
- def test_weeks_ago
- assert_equal Time.local(2005,5,29,10), Time.local(2005,6,5,10,0,0).weeks_ago(1)
- assert_equal Time.local(2005,5,1,10), Time.local(2005,6,5,10,0,0).weeks_ago(5)
- assert_equal Time.local(2005,4,24,10), Time.local(2005,6,5,10,0,0).weeks_ago(6)
- assert_equal Time.local(2005,2,27,10), Time.local(2005,6,5,10,0,0).weeks_ago(14)
- assert_equal Time.local(2004,12,25,10), Time.local(2005,1,1,10,0,0).weeks_ago(1)
- end
-
- def test_months_ago
- assert_equal Time.local(2005,5,5,10), Time.local(2005,6,5,10,0,0).months_ago(1)
- assert_equal Time.local(2004,11,5,10), Time.local(2005,6,5,10,0,0).months_ago(7)
- assert_equal Time.local(2004,12,5,10), Time.local(2005,6,5,10,0,0).months_ago(6)
- assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).months_ago(12)
- assert_equal Time.local(2003,6,5,10), Time.local(2005,6,5,10,0,0).months_ago(24)
- end
-
- def test_months_since
- assert_equal Time.local(2005,7,5,10), Time.local(2005,6,5,10,0,0).months_since(1)
- assert_equal Time.local(2006,1,5,10), Time.local(2005,12,5,10,0,0).months_since(1)
- assert_equal Time.local(2005,12,5,10), Time.local(2005,6,5,10,0,0).months_since(6)
- assert_equal Time.local(2006,6,5,10), Time.local(2005,12,5,10,0,0).months_since(6)
- assert_equal Time.local(2006,1,5,10), Time.local(2005,6,5,10,0,0).months_since(7)
- assert_equal Time.local(2006,6,5,10), Time.local(2005,6,5,10,0,0).months_since(12)
- assert_equal Time.local(2007,6,5,10), Time.local(2005,6,5,10,0,0).months_since(24)
- assert_equal Time.local(2005,4,30,10), Time.local(2005,3,31,10,0,0).months_since(1)
- assert_equal Time.local(2005,2,28,10), Time.local(2005,1,29,10,0,0).months_since(1)
- assert_equal Time.local(2005,2,28,10), Time.local(2005,1,30,10,0,0).months_since(1)
- assert_equal Time.local(2005,2,28,10), Time.local(2005,1,31,10,0,0).months_since(1)
- end
-
- def test_years_ago
- assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).years_ago(1)
- assert_equal Time.local(1998,6,5,10), Time.local(2005,6,5,10,0,0).years_ago(7)
- assert_equal Time.local(2003,2,28,10), Time.local(2004,2,29,10,0,0).years_ago(1) # 1 year ago from leap day
- end
-
- def test_years_since
- assert_equal Time.local(2006,6,5,10), Time.local(2005,6,5,10,0,0).years_since(1)
- assert_equal Time.local(2012,6,5,10), Time.local(2005,6,5,10,0,0).years_since(7)
- assert_equal Time.local(2005,2,28,10), Time.local(2004,2,29,10,0,0).years_since(1) # 1 year since leap day
- # Failure because of size limitations of numeric?
- # assert_equal Time.local(2182,6,5,10), Time.local(2005,6,5,10,0,0).years_since(177)
- end
-
- def test_prev_year
- assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).prev_year
- end
-
def test_last_year
assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).last_year
end
- def test_next_year
- assert_equal Time.local(2006,6,5,10), Time.local(2005,6,5,10,0,0).next_year
- 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)
@@ -426,16 +305,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_yesterday
- assert_equal Time.local(2005,2,21,10,10,10), Time.local(2005,2,22,10,10,10).yesterday
- assert_equal Time.local(2005,2,28,10,10,10), Time.local(2005,3,2,10,10,10).yesterday.yesterday
- end
-
- def test_tomorrow
- assert_equal Time.local(2005,2,23,10,10,10), Time.local(2005,2,22,10,10,10).tomorrow
- assert_equal Time.local(2005,3,2,10,10,10), Time.local(2005,2,28,10,10,10).tomorrow.tomorrow
- 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)
@@ -539,16 +408,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal t, t.advance(:months => 0)
end
- def test_prev_week
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2005,2,21), Time.local(2005,3,1,15,15,10).prev_week
- assert_equal Time.local(2005,2,22), Time.local(2005,3,1,15,15,10).prev_week(:tuesday)
- assert_equal Time.local(2005,2,25), Time.local(2005,3,1,15,15,10).prev_week(:friday)
- assert_equal Time.local(2006,10,30), Time.local(2006,11,6,0,0,0).prev_week
- assert_equal Time.local(2006,11,15), Time.local(2006,11,23,0,0,0).prev_week(:wednesday)
- end
- 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
@@ -559,16 +418,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_next_week
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2005,2,28), Time.local(2005,2,22,15,15,10).next_week
- assert_equal Time.local(2005,3,1), Time.local(2005,2,22,15,15,10).next_week(:tuesday)
- assert_equal Time.local(2005,3,4), Time.local(2005,2,22,15,15,10).next_week(:friday)
- assert_equal Time.local(2006,10,30), Time.local(2006,10,23,0,0,0).next_week
- assert_equal Time.local(2006,11,1), Time.local(2006,10,23,0,0,0).next_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'
@@ -709,14 +558,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_next_month_on_31st
- assert_equal Time.local(2005, 9, 30), Time.local(2005, 8, 31).next_month
- end
-
- def test_prev_month_on_31st
- assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).prev_month
- end
-
def test_last_month_on_31st
assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
end
@@ -938,15 +779,6 @@ class TimeExtMarshalingTest < ActiveSupport::TestCase
assert_equal t, unmarshaled
end
-
- def test_next_quarter_on_31st
- assert_equal Time.local(2005, 11, 30), Time.local(2005, 8, 31).next_quarter
- end
-
- def test_prev_quarter_on_31st
- assert_equal Time.local(2004, 2, 29), Time.local(2004, 5, 31).prev_quarter
- end
-
def test_last_quarter_on_31st
assert_equal Time.local(2004, 2, 29), Time.local(2004, 5, 31).last_quarter
end
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 69829bcda5..e5bc806397 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -145,6 +145,12 @@ class DependenciesTest < ActiveSupport::TestCase
end
end
+ def test_circular_autoloading_detection
+ with_autoloading_fixtures do
+ assert_raise(RuntimeError, "Circular dependency detected while autoloading constant Circular1") { Circular1 }
+ end
+ end
+
def test_module_loading
with_autoloading_fixtures do
assert_kind_of Module, A
@@ -679,6 +685,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal true, M.unloadable
assert_equal false, M.unloadable
end
+ ensure
+ Object.class_eval { remove_const :M }
end
def test_unloadable_constants_should_receive_callback
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index 1f32e4ff92..aa41e57928 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -169,11 +169,11 @@ class InflectorTest < ActiveSupport::TestCase
def test_underscore_acronym_sequence
ActiveSupport::Inflector.inflections do |inflect|
inflect.acronym("API")
- inflect.acronym("HTML5")
+ inflect.acronym("JSON")
inflect.acronym("HTML")
end
- assert_equal("html5_html_api", ActiveSupport::Inflector.underscore("HTML5HTMLAPI"))
+ assert_equal("json_html_api", ActiveSupport::Inflector.underscore("JSONHTMLAPI"))
end
def test_underscore
@@ -354,6 +354,35 @@ class InflectorTest < ActiveSupport::TestCase
RUBY
end
+ def test_inflector_locality
+ ActiveSupport::Inflector.inflections(:es) do |inflect|
+ inflect.plural(/$/, 's')
+ inflect.plural(/z$/i, 'ces')
+
+ inflect.singular(/s$/, '')
+ inflect.singular(/es$/, '')
+
+ inflect.irregular('el', 'los')
+ end
+
+ 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('los', 'el'.pluralize(:es))
+ assert_equal('els', 'el'.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.plurals.empty?
+ assert !ActiveSupport::Inflector.inflections.singulars.empty?
+ end
+
def test_clear_all
with_dup do
ActiveSupport::Inflector.inflections do |inflect|
@@ -467,7 +496,7 @@ class InflectorTest < ActiveSupport::TestCase
# there are module functions that access ActiveSupport::Inflector.inflections,
# so we need to replace the singleton itself.
def with_dup
- original = ActiveSupport::Inflector.inflections
+ original = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)
ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, original.dup)
ensure
ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, original)
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index a947635f4a..7ed71f9abc 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -85,6 +85,13 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
end
+ def test_json_variable
+ assert_deprecated do
+ assert_equal ActiveSupport::JSON::Variable.new('foo'), 'foo'
+ assert_equal ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")'
+ end
+ end
+
def test_hash_encoding
assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b)
assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
index a8d69d0ec3..ef289692bc 100644
--- a/activesupport/test/multibyte_chars_test.rb
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -110,7 +110,7 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
%w{capitalize downcase lstrip reverse rstrip swapcase upcase}.each do |method|
- class_eval(<<-EOTESTS)
+ class_eval(<<-EOTESTS, __FILE__, __LINE__ + 1)
def test_#{method}_bang_should_return_self_when_modifying_wrapped_string
chars = ' él piDió Un bUen café '
assert_equal chars.object_id, chars.send("#{method}!").object_id
diff --git a/activesupport/test/notifications/evented_notification_test.rb b/activesupport/test/notifications/evented_notification_test.rb
index f77a0eb3fa..f690ad43fc 100644
--- a/activesupport/test/notifications/evented_notification_test.rb
+++ b/activesupport/test/notifications/evented_notification_test.rb
@@ -19,6 +19,12 @@ module ActiveSupport
end
end
+ class ListenerWithTimedSupport < Listener
+ def call(name, start, finish, id, payload)
+ @events << [:call, name, start, finish, id, payload]
+ end
+ end
+
def test_evented_listener
notifier = Fanout.new
listener = Listener.new
@@ -62,6 +68,20 @@ module ActiveSupport
[:finish, 'hello', 1, {}],
], listener.events
end
+
+ def test_evented_listener_priority
+ notifier = Fanout.new
+ listener = ListenerWithTimedSupport.new
+ notifier.subscribe 'hi', listener
+
+ notifier.start 'hi', 1, {}
+ notifier.finish 'hi', 1, {}
+
+ assert_equal [
+ [:start, 'hi', 1, {}],
+ [:finish, 'hi', 1, {}]
+ ], listener.events
+ end
end
end
end
diff --git a/activesupport/test/number_helper_i18n_test.rb b/activesupport/test/number_helper_i18n_test.rb
index e07198027b..65aecece71 100644
--- a/activesupport/test/number_helper_i18n_test.rb
+++ b/activesupport/test/number_helper_i18n_test.rb
@@ -56,6 +56,13 @@ module ActiveSupport
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 => ";" } } }
+
+ 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' } }
@@ -72,11 +79,24 @@ module ActiveSupport
assert_equal("1.00", number_to_rounded(1.0, :locale => 'ts'))
end
+ def test_number_with_i18n_precision_and_empty_i18n_store
+ I18n.backend.store_translations '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'))
end
+ def test_number_with_i18n_delimiter_and_empty_i18n_store
+ I18n.backend.store_translations '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'))
@@ -86,12 +106,27 @@ module ActiveSupport
assert_equal("12434%", number_to_percentage(12434, :locale => 'ts'))
end
+ def test_number_to_i18n_percentage_and_empty_i18n_store
+ I18n.backend.store_translations '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'))
end
+ def test_number_to_i18n_human_size_with_empty_i18n_store
+ I18n.backend.store_translations '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')
@@ -106,6 +141,13 @@ module ActiveSupport
assert_equal "2 Tens", number_to_human(20, :locale => 'ts')
end
+ def test_number_to_human_with_empty_i18n_store
+ I18n.backend.store_translations '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)
diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb
index 9b7d7f020c..5f54587f93 100644
--- a/activesupport/test/number_helper_test.rb
+++ b/activesupport/test/number_helper_test.rb
@@ -4,7 +4,7 @@ require 'active_support/number_helper'
module ActiveSupport
module NumberHelper
class NumberHelperTest < ActiveSupport::TestCase
-
+
class TestClassWithInstanceNumberHelpers
include ActiveSupport::NumberHelper
end
@@ -16,7 +16,7 @@ module ActiveSupport
def setup
@instance_with_helpers = TestClassWithInstanceNumberHelpers.new
end
-
+
def kilobytes(number)
number * 1024
end
@@ -362,14 +362,13 @@ module ActiveSupport
assert_equal "x", number_helper.number_to_human('x')
end
end
-
+
def test_extending_or_including_number_helper_correctly_hides_private_methods
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
assert !number_helper.respond_to?(:valid_float?)
assert number_helper.respond_to?(:valid_float?, true)
end
end
-
end
end
end
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index e8defd396b..ac85ba1f21 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -226,12 +226,8 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_alternate_initialization_raises_exception_on_odd_length_args
- begin
+ assert_raises ArgumentError do
ActiveSupport::OrderedHash[1,2,3,4,5]
- flunk "Hash::[] should have raised an exception on initialization " +
- "with an odd number of parameters"
- rescue ArgumentError => e
- assert_equal "odd number of arguments for Hash", e.message
end
end
diff --git a/activesupport/test/string_inquirer_test.rb b/activesupport/test/string_inquirer_test.rb
index bb15916e9e..94d5fe197d 100644
--- a/activesupport/test/string_inquirer_test.rb
+++ b/activesupport/test/string_inquirer_test.rb
@@ -1,15 +1,23 @@
require 'abstract_unit'
class StringInquirerTest < ActiveSupport::TestCase
+ def setup
+ @string_inquirer = ActiveSupport::StringInquirer.new('production')
+ end
+
def test_match
- assert ActiveSupport::StringInquirer.new("production").production?
+ assert @string_inquirer.production?
end
def test_miss
- assert !ActiveSupport::StringInquirer.new("production").development?
+ refute @string_inquirer.development?
end
def test_missing_question_mark
- assert_raise(NoMethodError) { ActiveSupport::StringInquirer.new("production").production }
+ assert_raise(NoMethodError) { @string_inquirer.production }
+ end
+
+ def test_respond_to
+ assert_respond_to @string_inquirer, :development?
end
end
diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb
index 0751c2469e..43cf1a8e4f 100644
--- a/activesupport/test/tagged_logging_test.rb
+++ b/activesupport/test/tagged_logging_test.rb
@@ -29,6 +29,11 @@ class TaggedLoggingTest < ActiveSupport::TestCase
assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
end
+ test "does not strip message content" do
+ @logger.info " Hello"
+ assert_equal " Hello\n", @output.string
+ end
+
test "provides access to the logger instance" do
@logger.tagged("BCX") { |logger| logger.info "Funky time" }
assert_equal "[BCX] Funky time\n", @output.string
diff --git a/activesupport/test/transliterate_test.rb b/activesupport/test/transliterate_test.rb
index b7076e9e58..b5d8142458 100644
--- a/activesupport/test/transliterate_test.rb
+++ b/activesupport/test/transliterate_test.rb
@@ -1,7 +1,6 @@
# encoding: utf-8
require 'abstract_unit'
require 'active_support/inflector/transliterate'
-require 'active_support/core_ext/object/inclusion'
class TransliterateTest < ActiveSupport::TestCase
@@ -16,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| c.in?([0xD7, 0xF7])}.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(string)
end
diff --git a/ci/travis.rb b/ci/travis.rb
index fc120f80ba..b03ac4fe35 100755
--- a/ci/travis.rb
+++ b/ci/travis.rb
@@ -100,9 +100,6 @@ ENV['GEM'].split(',').each do |gem|
build = Build.new(gem, :isolated => isolated)
results[build.key] = build.run!
- if build.activerecord?
- results[build.key] = build.run!
- end
end
end
diff --git a/guides/code/getting_started/app/views/comments/_comment.html.erb b/guides/code/getting_started/app/views/comments/_comment.html.erb
index 0cebe0bd96..3d2bc1590e 100644
--- a/guides/code/getting_started/app/views/comments/_comment.html.erb
+++ b/guides/code/getting_started/app/views/comments/_comment.html.erb
@@ -10,6 +10,6 @@
<p>
<%= link_to 'Destroy Comment', [comment.post, comment],
- :confirm => 'Are you sure?',
- :method => :delete %>
+ :method => :delete,
+ :data => { :confirm => 'Are you sure?' } %>
</p>
diff --git a/guides/code/getting_started/app/views/posts/index.html.erb b/guides/code/getting_started/app/views/posts/index.html.erb
index 7b72720d50..9a0e90eadc 100644
--- a/guides/code/getting_started/app/views/posts/index.html.erb
+++ b/guides/code/getting_started/app/views/posts/index.html.erb
@@ -17,7 +17,7 @@
<td><%= post.text %></td>
<td><%= link_to 'Show', :action => :show, :id => post.id %>
<td><%= link_to 'Edit', :action => :edit, :id => post.id %>
- <td><%= link_to 'Destroy', { :action => :destroy, :id => post.id }, :method => :delete, :confirm => 'Are you sure?' %>
+ <td><%= link_to 'Destroy', { :action => :destroy, :id => post.id }, :method => :delete, :data => { :confirm => 'Are you sure?' } %>
</tr>
<% end %>
</table>
diff --git a/guides/code/getting_started/config/initializers/session_store.rb b/guides/code/getting_started/config/initializers/session_store.rb
index 1a67af58b5..3b2ca93ab9 100644
--- a/guides/code/getting_started/config/initializers/session_store.rb
+++ b/guides/code/getting_started/config/initializers/session_store.rb
@@ -1,8 +1,3 @@
# Be sure to restart your server when you modify this file.
Blog::Application.config.session_store :cookie_store, key: '_blog_session'
-
-# Use the database for sessions instead of the cookie-based default,
-# which shouldn't be used to store highly confidential information
-# (create the session table with "rails generate session_migration")
-# Blog::Application.config.session_store :active_record_store
diff --git a/guides/rails_guides/textile_extensions.rb b/guides/rails_guides/textile_extensions.rb
index 0a002a785f..1faddd4ca0 100644
--- a/guides/rails_guides/textile_extensions.rb
+++ b/guides/rails_guides/textile_extensions.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/object/inclusion'
-
module RedCloth::Formatters::HTML
def emdash(opts)
"--"
diff --git a/guides/source/2_2_release_notes.textile b/guides/source/2_2_release_notes.textile
index 3a0f2efbaf..eb4b32329b 100644
--- a/guides/source/2_2_release_notes.textile
+++ b/guides/source/2_2_release_notes.textile
@@ -118,9 +118,9 @@ h4. Transactional Migrations
Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.
-* Lead Contributor: "Adam Wiggins":http://adam.blog.heroku.com/
+* Lead Contributor: "Adam Wiggins":http://adam.heroku.com/
* More information:
-** "DDL Transactions":http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/
+** "DDL Transactions":http://adam.heroku.com/past/2008/9/3/ddl_transactions/
** "A major milestone for DB2 on Rails":http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/
h4. Connection Pooling
diff --git a/guides/source/2_3_release_notes.textile b/guides/source/2_3_release_notes.textile
index 15abba66ab..36f425574b 100644
--- a/guides/source/2_3_release_notes.textile
+++ b/guides/source/2_3_release_notes.textile
@@ -561,7 +561,7 @@ This will layer the changes from the template on top of whatever code the projec
h4. Quieter Backtraces
-Building on Thoughtbot's "Quiet Backtrace":http://www.thoughtbot.com/projects/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace.
+Building on Thoughtbot's "Quiet Backtrace":https://github.com/thoughtbot/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace.
h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload
diff --git a/guides/source/4_0_release_notes.textile b/guides/source/4_0_release_notes.textile
index b7ac11999a..0e03779e0d 100644
--- a/guides/source/4_0_release_notes.textile
+++ b/guides/source/4_0_release_notes.textile
@@ -82,8 +82,6 @@ will generate the model with <tt>belongs_to :supplier, polymorphic: true</tt> as
* Load all environments available in <tt>config.paths["config/environments"]</tt>.
-* The application generator generates <tt>public/humans.txt</tt> with some basic data.
-
* Add <tt>config.queue_consumer</tt> to allow the default consumer to be configurable.
* Add <tt>Rails.queue</tt> as an interface with a default implementation that consumes jobs in a separate thread.
@@ -122,6 +120,16 @@ h3. Action Pack
h4. Action Controller
+* Add <tt>ActionController::Flash.add_flash_types</tt> method to allow people to register their own flash types. e.g.:
+
+<ruby>
+class ApplicationController
+ add_flash_types :error, :warning
+end
+</ruby>
+
+If you add the above code, you can use <tt><%= error %></tt> in an erb, and <tt>redirect_to /foo, :error => 'message'</tt> in a controller.
+
* Remove Active Model dependency from Action Pack.
* Support unicode characters in routes. Route will be automatically escaped, so instead of manually escaping:
@@ -186,6 +194,39 @@ h5(#actioncontroller_deprecations). Deprecations
h4. Action Dispatch
+* Add Routing Concerns to declare common routes that can be reused inside others resources and routes.
+
+Code before:
+
+<ruby>
+resources :messages do
+ resources :comments
+end
+
+resources :posts do
+ resources :comments
+ resources :images, only: :index
+end
+</ruby>
+
+Code after:
+
+<ruby>
+concern :commentable do
+ resources :comments
+end
+
+concern :image_attachable do
+ resources :images, only: :index
+end
+
+resources :messages, concerns: :commentable
+
+resources :posts, concerns: [:commentable, :image_attachable]
+</ruby>
+
+* Show routes in exception page while debugging a <tt>RoutingError</tt> in development.
+
* Include <tt>mounted_helpers</tt> (helpers for accessing mounted engines) in <tt>ActionDispatch::IntegrationTest</tt> by default.
* Added <tt>ActionDispatch::SSL</tt> middleware that when included force all the requests to be under HTTPS protocol.
@@ -438,35 +479,10 @@ end
User.stored_attributes[:settings] # [:color, :homepage]
</ruby>
-* <tt>composed_of</tt> was removed. You'll have to write your own accessor and mutator methods if you'd like to use value objects to represent some portion of your models. So, instead of:
-
-<ruby>
-class Person < ActiveRecord::Base
- composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-end
-</ruby>
-
-you could write something like this:
-
-<ruby>
-def address
- @address ||= Address.new(address_street, address_city)
-end
-
-def address=(address)
- self[:address_street] = @address.street
- self[:address_city] = @address.city
-
- @address = address
-end
-</ruby>
-
* PostgreSQL default log level is now 'warning', to bypass the noisy notice messages. You can change the log level using the <tt>min_messages</tt> option available in your <tt>config/database.yml</tt>.
* Add uuid datatype support to PostgreSQL adapter.
-* <tt>update_attribute</tt> has been removed. Use <tt>update_column</tt> if you want to bypass mass-assignment protection, validations, callbacks, and touching of updated_at. Otherwise please use <tt>update_attributes</tt>.
-
* Added <tt>ActiveRecord::Migration.check_pending!</tt> that raises an error if migrations are pending.
* Added <tt>#destroy!</tt> which acts like <tt>#destroy</tt> but will raise an <tt>ActiveRecord::RecordNotDestroyed</tt> exception instead of returning <tt>false</tt>.
@@ -687,6 +703,10 @@ where(...).remove_conditions # => still has conditions
* New rails application would be generated with the config.active_record.dependent_restrict_raises = false in the application config.
+* The migration generator now creates a join table with (commented) indexes every time the migration name contains the word "join_table".
+
+* <tt>ActiveRecord::SessionStore</tt> is removed from Rails 4.0 and is now a separate "gem":https://github.com/rails/activerecord-session_store.
+
h3. Active Model
* Changed <tt>AM::Serializers::JSON.include_root_in_json</tt> default value to false. Now, AM Serializers and AR objects have the same default behaviour.
@@ -733,6 +753,8 @@ h3. Active Resource
h3. Active Support
+* Add default values to all <tt>ActiveSupport::NumberHelper</tt> methods, to avoid errors with empty locales or missing values.
+
* <tt>Time#change</tt> now works with time values with offsets other than UTC or the local time zone.
* Add <tt>Time#prev_quarter</tt> and <tt>Time#next_quarter</tt> short-hands for <tt>months_ago(3)</tt> and <tt>months_since(3)</tt>.
diff --git a/guides/source/action_controller_overview.textile b/guides/source/action_controller_overview.textile
index cc3350819b..1d43b44391 100644
--- a/guides/source/action_controller_overview.textile
+++ b/guides/source/action_controller_overview.textile
@@ -168,8 +168,8 @@ h3. Session
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
* ActionDispatch::Session::CookieStore - Stores everything on the client.
-* ActiveRecord::SessionStore - Stores the data in a database using Active Record.
* ActionDispatch::Session::CacheStore - Stores the data in the Rails cache.
+* ActionDispatch::Session::ActiveRecordStore - Stores the data in a database using Active Record. (require `activerecord-session_store` gem).
* ActionDispatch::Session::MemCacheStore - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
@@ -187,7 +187,7 @@ If you need a different session storage mechanism, you can change it in the +con
<ruby>
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
-# (create the session table with "script/rails g session_migration")
+# (create the session table with "script/rails g active_record:session_migration")
# YourApp::Application.config.session_store :active_record_store
</ruby>
@@ -278,26 +278,31 @@ To reset the entire session, use +reset_session+.
h4. The Flash
-The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.
+
+It is accessed in much the same way as the session, as a hash (it's a "FlashHash":http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html instance).
+
+Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
<ruby>
class LoginsController < ApplicationController
def destroy
session[:current_user_id] = nil
- flash[:notice] = "You have successfully logged out"
+ flash[:notice] = "You have successfully logged out."
redirect_to root_url
end
end
</ruby>
-Note it is also possible to assign a flash message as part of the redirection.
+Note that it is also possible to assign a flash message as part of the redirection. You can assign +:notice+, +:alert+ or the general purpose +:flash+:
<ruby>
-redirect_to root_url, :notice => "You have successfully logged out"
+redirect_to root_url, :notice => "You have successfully logged out."
+redirect_to root_url, :alert => "You're stuck here!"
+redirect_to root_url, :flash => { :referral_code => 1234 }
</ruby>
-
-The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
+The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display any error alerts or notices from the flash in the application's layout:
<ruby>
<html>
@@ -306,15 +311,23 @@ The +destroy+ action redirects to the application's +root_url+, where the messag
<% if flash[:notice] %>
<p class="notice"><%= flash[:notice] %></p>
<% end %>
- <% if flash[:error] %>
- <p class="error"><%= flash[:error] %></p>
+ <% if flash[:alert] %>
+ <p class="alert"><%= flash[:alert] %></p>
<% end %>
<!-- more content -->
</body>
</html>
</ruby>
-This way, if an action sets an error or a notice message, the layout will display it automatically.
+This way, if an action sets a notice or an alert message, the layout will display it automatically.
+
+You can pass anything that the session can store; you're not limited to notices and alerts:
+
+<ruby>
+<% if flash[:just_signed_up] %>
+ <p class="welcome">Welcome to our site!</p>
+<% end %>
+</ruby>
If you want a flash value to be carried over to another request, use the +keep+ method:
@@ -478,9 +491,9 @@ class ChangesController < ActionController::Base
end
</ruby>
-Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview.
+Note that an around filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
-They can choose not to yield and build the response themselves, in which case the action is not run.
+You can choose not to yield and build the response yourself, in which case the action will not be run.
h4. Other Ways to Use Filters
diff --git a/guides/source/action_mailer_basics.textile b/guides/source/action_mailer_basics.textile
index 7c61cc4a8d..bca403ae72 100644
--- a/guides/source/action_mailer_basics.textile
+++ b/guides/source/action_mailer_basics.textile
@@ -4,7 +4,7 @@ This guide should provide you with all you need to get started in sending and re
endprologue.
-WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails.
+WARNING. This guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails.
h3. Introduction
@@ -84,7 +84,7 @@ Create a file called +welcome_email.html.erb+ in +app/views/user_mailer/+. This
</html>
</erb>
-It is also a good idea to make a text part for this email, to do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+:
+It is also a good idea to make a text part for this email. To do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+:
<erb>
Welcome to example.com, <%= @user.name %>
@@ -144,7 +144,7 @@ The method +welcome_email+ returns a <tt>Mail::Message</tt> object which can the
NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.
-WARNING: Sending out an email should only take a fraction of a second, but if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
+WARNING: Sending out an email should only take a fraction of a second. If you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
h4. Auto encoding header values
@@ -152,14 +152,14 @@ Action Mailer now handles the auto encoding of multibyte characters inside of he
If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and Action Mailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII.
-For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library.
+For more complex examples such as defining alternate character sets or self-encoding text first, please refer to the Mail library.
h4. Complete List of Action Mailer Methods
There are just three methods that you need to send pretty much any email message:
-* <tt>headers</tt> - Specifies any header on the email you want, you can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>
-* <tt>attachments</tt> - Allows you to add attachments to your email, for example <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>
+* <tt>headers</tt> - Specifies any header on the email you want. You can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>.
+* <tt>attachments</tt> - Allows you to add attachments to your email. For example, <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>.
* <tt>mail</tt> - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
h5. Custom Headers
@@ -184,7 +184,7 @@ headers["X-Spam"] = value
headers {"X-Spam" => value, "X-Special" => another_value}
</ruby>
-TIP: All <tt>X-Value</tt> headers per the RFC2822 can appear more than one time. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>.
+TIP: All <tt>X-Value</tt> headers per the RFC2822 can appear more than once. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>.
h5. Adding Attachments
@@ -196,7 +196,7 @@ Adding attachments has been simplified in Action Mailer 3.0.
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
</ruby>
-NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
+NOTE: Mail will automatically Base64 encode an attachment. If you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
* Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
@@ -229,7 +229,7 @@ end
<%= image_tag attachments['image.jpg'].url %>
</erb>
-* As this is a standard call to +image_tag+ you can pass in an options hash after the attachment url as you could for any other image:
+* As this is a standard call to +image_tag+ you can pass in an options hash after the attachment URL as you could for any other image:
<erb>
<p>Hello there, this is our image</p>
@@ -240,7 +240,7 @@ end
h5. Sending Email To Multiple Recipients
-It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
+It is possible to send email to one or more recipients in one email (e.g., informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
<ruby>
class AdminMailer < ActionMailer::Base
@@ -451,13 +451,14 @@ The following configuration options are best made in one of the environment file
|+template_root+|Determines the base from which template references will be made.|
|+logger+|Generates information on the mailing run if available. Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and +Log4r+ loggers.|
-|+smtp_settings+|Allows detailed configuration for <tt>:smtp</tt> delivery method:<ul><li><tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li><tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li><tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.</li><li><tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.</li><li><tt>:password</tt> - If your mail server requires authentication, set the password in this setting.</li><li><tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.</li></ul>|
+|+smtp_settings+|Allows detailed configuration for <tt>:smtp</tt> delivery method:<ul><li><tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li><tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li><tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.</li><li><tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.</li><li><tt>:password</tt> - If your mail server requires authentication, set the password in this setting.</li><li><tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.</li><li><tt>:enable_starttls_auto</tt> - Set this to <tt>false</tt> if there is a problem with your server certificate that you cannot resolve.</li></ul>|
|+sendmail_settings+|Allows you to override options for the <tt>:sendmail</tt> delivery method.<ul><li><tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.</li><li><tt>:arguments</tt> - The command line arguments to be passed to sendmail. Defaults to <tt>-i -t</tt>.</li></ul>|
|+raise_delivery_errors+|Whether or not errors should be raised if the email fails to be delivered.|
|+delivery_method+|Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, <tt>:file</tt> and <tt>:test</tt>.|
|+perform_deliveries+|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
|+deliveries+|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
|+async+|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to <tt>Rails.queue</tt> for processing.|
+|+default_options+|Allows you to set default values for the <tt>mail</tt> method options (<tt>:from</tt>, <tt>:reply_to</tt>, etc.).|
h4. Example Action Mailer Configuration
@@ -472,6 +473,7 @@ config.action_mailer.delivery_method = :sendmail
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
+config.action_mailer.default_options = {from: "no-replay@example.org"}
</ruby>
h4. Action Mailer Configuration for GMail
@@ -508,8 +510,8 @@ class UserMailerTest < ActionMailer::TestCase
# Test the body of the sent email contains what we expect it to
assert_equal [user.email], email.to
assert_equal "Welcome to My Awesome Site", email.subject
- assert_match(/<h1>Welcome to example.com, #{user.name}<\/h1>/, email.encoded)
- assert_match(/Welcome to example.com, #{user.name}/, email.encoded)
+ assert_match "<h1>Welcome to example.com, #{user.name}</h1>", email.body.to_s
+ assert_match "you have joined to example.com community", email.body.to_s
end
end
</ruby>
diff --git a/guides/source/action_view_overview.textile b/guides/source/action_view_overview.textile
index fdfa97effa..1fd98a5bbe 100644
--- a/guides/source/action_view_overview.textile
+++ b/guides/source/action_view_overview.textile
@@ -785,7 +785,7 @@ h5. content_for
Calling +content_for+ stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to +yield+.
-For example, let's say we have a standard application layout, but also a special page that requires certain Javascript that the rest of the site doesn't need. We can use +content_for+ to include this Javascript on our special page without fattening up the rest of the site.
+For example, let's say we have a standard application layout, but also a special page that requires certain JavaScript that the rest of the site doesn't need. We can use +content_for+ to include this JavaScript on our special page without fattening up the rest of the site.
*app/views/layouts/application.html.erb*
diff --git a/guides/source/active_model_basics.textile b/guides/source/active_model_basics.textile
index 7cafff2ad8..2c30ddb84c 100644
--- a/guides/source/active_model_basics.textile
+++ b/guides/source/active_model_basics.textile
@@ -1,18 +1,18 @@
h2. Active Model Basics
-This guide should provide you with all you need to get started using model classes. Active Model allow for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.
+This guide should provide you with all you need to get started using model classes. Active Model allows for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.
endprologue.
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
+WARNING. This guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
h3. Introduction
-Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below -
+Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below.
h4. AttributeMethods
-AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.
+The AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.
<ruby>
class Person
@@ -92,7 +92,7 @@ person.to_param #=> nil
h4. Dirty
-An object becomes dirty when an object is gone through one or more changes to its attributes and not yet saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Lets consider a Person class with attributes first_name and last_name
+An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes first_name and last_name
<ruby>
require 'active_model'
@@ -168,7 +168,7 @@ Track what was the previous value of the attribute.
person.first_name_was #=> "First Name"
</ruby>
-Track both previous and current value of the changed attribute. Returns an array if changed else returns nil
+Track both previous and current value of the changed attribute. Returns an array if changed, else returns nil.
<ruby>
#attr_name_change
diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile
index 101988c59e..80c9260a0d 100644
--- a/guides/source/active_record_querying.textile
+++ b/guides/source/active_record_querying.textile
@@ -12,8 +12,6 @@ This guide covers different ways to retrieve data from the database using Active
endprologue.
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails.
-
If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
Code examples throughout this guide will refer to one or more of the following models:
@@ -53,20 +51,29 @@ h3. Retrieving Objects from the Database
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
The methods are:
-* +where+
-* +select+
+* +bind+
+* +create_with+
+* +eager_load+
+* +extending+
+* +from+
* +group+
-* +order+
-* +reorder+
-* +reverse_order+
-* +limit+
-* +offset+
-* +joins+
+* +having+
* +includes+
+* +joins+
+* +limit+
* +lock+
+* +none+
+* +offset+
+* +order+
+* +none+
+* +preload+
* +readonly+
-* +from+
-* +having+
+* +references+
+* +reorder+
+* +reverse_order+
+* +select+
+* +uniq+
+* +where+
All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.
@@ -488,7 +495,7 @@ This code will generate SQL like this:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
</sql>
-h3. Ordering
+h3(#ordering). Ordering
To retrieve records from the database in a specific order, you can use the +order+ method.
@@ -514,6 +521,13 @@ Client.order("orders_count ASC, created_at DESC")
Client.order("orders_count ASC", "created_at DESC")
</ruby>
+If you want to call +order+ multiple times e.g. in different context, new order will prepend previous one
+
+<ruby>
+Client.order("orders_count ASC").order("created_at DESC")
+# SELECT * FROM clients ORDER BY created_at DESC, orders_count ASC
+</ruby>
+
h3. Selecting Specific Fields
By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
@@ -1039,7 +1053,7 @@ Even though Active Record lets you specify conditions on the eager loaded associ
However if you must do this, you may use +where+ as you would normally.
<ruby>
-Post.includes(:comments).where("comments.visible", true)
+Post.includes(:comments).where("comments.visible" => true)
</ruby>
This would generate a query which contains a +LEFT OUTER JOIN+ whereas the +joins+ method would generate one using the +INNER JOIN+ function instead.
@@ -1128,21 +1142,6 @@ Using a class method is the preferred way to accept arguments for scopes. These
category.posts.created_before(time)
</ruby>
-h4. Working with scopes
-
-Where a relational object is required, the +scoped+ method may come in handy. This will return an +ActiveRecord::Relation+ object which can have further scoping applied to it afterwards. A place where this may come in handy is on associations
-
-<ruby>
-client = Client.find_by_first_name("Ryan")
-orders = client.orders.scoped
-</ruby>
-
-With this new +orders+ object, we are able to ascertain that this object can have more scopes applied to it. For instance, if we wanted to return orders only in the last 30 days at a later point.
-
-<ruby>
-orders.where("created_at > ?", 30.days.ago)
-</ruby>
-
h4. Applying a default scope
If we wish for a scope to be applied across all queries to the model we can use the +default_scope+ method within the model itself.
diff --git a/guides/source/active_record_validations_callbacks.textile b/guides/source/active_record_validations_callbacks.textile
index f49d91fd3c..b866337e3f 100644
--- a/guides/source/active_record_validations_callbacks.textile
+++ b/guides/source/active_record_validations_callbacks.textile
@@ -86,6 +86,7 @@ The following methods skip validations, and will save the object to the database
* +update_all+
* +update_attribute+
* +update_column+
+* +update_columns+
* +update_counters+
Note that +save+ also has the ability to skip validations if passed +:validate => false+ as argument. This technique should be used with caution.
@@ -373,6 +374,8 @@ class LineItem < ActiveRecord::Base
end
</ruby>
+If you validate the presence of an object associated via a +has_one+ or +has_many+ relationship, it will check that the object is neither +blank?+ nor +marked_for_destruction?+.
+
Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use <tt>validates :field_name, :inclusion => { :in => [true, false] }</tt>.
The default error message is "_can't be empty_".
@@ -529,6 +532,16 @@ end
Person.new.valid? => ActiveModel::StrictValidationFailed: Name can't be blank
</ruby>
+There is also an ability to pass custom exception to +:strict+ option
+
+<ruby>
+class Person < ActiveRecord::Base
+ validates :token, :presence => true, :uniqueness => true, :strict => TokenGenerationException
+end
+
+Person.new.valid? => TokenGenerationException: Token can't be blank
+</ruby>
+
h3. Conditional Validation
Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string, a +Proc+ or an +Array+. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
@@ -1082,6 +1095,7 @@ Just as with validations, it is also possible to skip callbacks. These methods s
* +toggle+
* +touch+
* +update_column+
+* +update_columns+
* +update_all+
* +update_counters+
diff --git a/guides/source/active_support_core_extensions.textile b/guides/source/active_support_core_extensions.textile
index 99b8bdd3fd..8748817eb8 100644
--- a/guides/source/active_support_core_extensions.textile
+++ b/guides/source/active_support_core_extensions.textile
@@ -1325,6 +1325,41 @@ that amount of leading whitespace.
NOTE: Defined in +active_support/core_ext/string/strip.rb+.
+h4. +indent+
+
+Indents the lines in the receiver:
+
+<ruby>
+<<EOS.indent(2)
+def some_method
+ some_code
+end
+EOS
+# =>
+ def some_method
+ some_code
+ end
+</ruby>
+
+The second argument, +indent_string+, specifies which indent string to use. The default is +nil+, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.
+
+<ruby>
+" foo".indent(2) # => " foo"
+"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
+"foo".indent(2, "\t") # => "\t\tfoo"
+</ruby>
+
+While +indent_string+ is tipically one space or tab, it may be any string.
+
+The third argument, +indent_empty_lines+, is a flag that says whether empty lines should be indented. Default is false.
+
+<ruby>
+"foo\n\nbar".indent(2) # => " foo\n\n bar"
+"foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
+</ruby>
+
+The +indent!+ method performs indentation in-place.
+
h4. Access
h5. +at(position)+
@@ -1456,13 +1491,9 @@ For example, Action Pack uses this method to load the class that provides a cert
<ruby>
# action_controller/metal/session_management.rb
def session_store=(store)
- if store == :active_record_store
- self.session_store = ActiveRecord::SessionStore
- else
- @@session_store = store.is_a?(Symbol) ?
- ActionDispatch::Session.const_get(store.to_s.camelize) :
- store
- end
+ @@session_store = store.is_a?(Symbol) ?
+ ActionDispatch::Session.const_get(store.to_s.camelize) :
+ store
end
</ruby>
@@ -2783,27 +2814,7 @@ The method +assert_valid_keys+ receives an arbitrary number of arguments, and ch
{:a => 1}.assert_valid_keys("a") # ArgumentError
</ruby>
-Active Record does not accept unknown options when building associations for example. It implements that control via +assert_valid_keys+:
-
-<ruby>
-mattr_accessor :valid_keys_for_has_many_association
-@@valid_keys_for_has_many_association = [
- :class_name, :table_name, :foreign_key, :primary_key,
- :dependent,
- :select, :conditions, :include, :order, :group, :having, :limit, :offset,
- :as, :through, :source, :source_type,
- :uniq,
- :finder_sql, :counter_sql,
- :before_add, :after_add, :before_remove, :after_remove,
- :extend, :readonly,
- :validate, :inverse_of
-]
-
-def create_has_many_reflection(association_id, options, &extension)
- options.assert_valid_keys(valid_keys_for_has_many_association)
- ...
-end
-</ruby>
+Active Record does not accept unknown options when building associations, for example. It implements that control via +assert_valid_keys+.
NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
diff --git a/guides/source/ajax_on_rails.textile b/guides/source/ajax_on_rails.textile
index e23fdf9a74..67b0c9f0d3 100644
--- a/guides/source/ajax_on_rails.textile
+++ b/guides/source/ajax_on_rails.textile
@@ -28,7 +28,7 @@ the +ul+ node.
h4. Asynchronous JavaScript + XML
AJAX means Asynchronous JavaScript + XML. Asynchronous means that the page is not
-reloaded, the request made is separate from the regular page request. Javascript
+reloaded, the request made is separate from the regular page request. JavaScript
is used to evaluate the response and the XML part is a bit misleading as XML is
not required, you respond to the HTTP request with JSON or regular HTML as well.
@@ -129,7 +129,7 @@ will produce
<ruby>
button_to 'Delete Image', { action: 'delete', id: @image.id },
- confirm: 'Are you sure?', method: :delete
+ method: :delete, data: { confirm: 'Are you sure?' }
</ruby>
will produce
@@ -144,8 +144,8 @@ will produce
</html>
<ruby>
-button_to 'Destroy', 'http://www.example.com', confirm: 'Are you sure?',
- method: 'delete', remote: true, data: { disable_with: 'loading...' }
+button_to 'Destroy', 'http://www.example.com',
+ method: 'delete', remote: true, data: { disable_with: 'loading...', confirm: 'Are you sure?' }
</ruby>
will produce
@@ -217,7 +217,6 @@ link_to_remote "Delete the item",
Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
** *JavaScript filters* You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
-*** +:confirm+ =&gt; +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled.
*** +:condition+ =&gt; +code+ Evaluates +code+ (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
*** +:before+ =&gt; +code+ Evaluates the +code+ just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
*** +:after+ =&gt; +code+ Evaluates the +code+ after launching the request. Note that this is different from the +:success+ or +:complete+ callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to +:after+ is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
@@ -307,4 +306,4 @@ JavaScript testing reminds me the definition of the world 'classic' by Mark Twai
* Cucumber+Webrat
* Mention stuff like screw.unit/jsSpec
-Note to self: check out the RailsConf JS testing video \ No newline at end of file
+Note to self: check out the RailsConf JS testing video
diff --git a/guides/source/api_documentation_guidelines.textile b/guides/source/api_documentation_guidelines.textile
index c6aa1f0a2b..3de5b119ee 100644
--- a/guides/source/api_documentation_guidelines.textile
+++ b/guides/source/api_documentation_guidelines.textile
@@ -127,7 +127,7 @@ class Array
end
</ruby>
-WARNING: Using a pair of +&#43;...&#43;+ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w&#43;\z</tt>. For anything else use +&lt;tt&gt;...&lt;/tt&gt;+, notably symbols, setters, inline snippets, etc:
+WARNING: Using a pair of +&#43;...&#43;+ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w&#43;\z</tt>. For anything else use +&lt;tt&gt;...&lt;/tt&gt;+, notably symbols, setters, inline snippets, etc.
h4. Regular Font
diff --git a/guides/source/asset_pipeline.textile b/guides/source/asset_pipeline.textile
index d0952fcf29..2a15e95282 100644
--- a/guides/source/asset_pipeline.textile
+++ b/guides/source/asset_pipeline.textile
@@ -70,11 +70,11 @@ The query string strategy has several disadvantages:
<ol>
<li>
- <strong>Not all caches will reliably cache content where the filename only differs by query parameters</strong>.<br>
+ <strong>Not all caches will reliably cache content where the filename only differs by query parameters</strong>.<br />
"Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
</li>
<li>
- <strong>The file name can change between nodes in multi-server environments.</strong><br>
+ <strong>The file name can change between nodes in multi-server environments.</strong><br />
The default query string in Rails 2.x is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request.
</li>
<li>
@@ -121,7 +121,7 @@ h5. Search paths
When a file is referenced from a manifest or a helper, Sprockets searches the three default asset locations for it.
-The default locations are: +app/assets/images+ and the subdirectories +javascripts+ and +stylesheets+ in all three asset locations.
+The default locations are: +app/assets/images+ and the subdirectories +javascripts+ and +stylesheets+ in all three asset locations, but these subdirectories are not special. Any path under +assets/*+ will be searched.
For example, these files:
@@ -129,6 +129,7 @@ For example, these files:
app/assets/javascripts/home.js
lib/assets/javascripts/moovinator.js
vendor/assets/javascripts/slider.js
+vendor/assets/somepackage/phonebox.js
</plain>
would be referenced in a manifest like this:
@@ -137,6 +138,7 @@ would be referenced in a manifest like this:
//= require home
//= require moovinator
//= require slider
+//= require phonebox
</plain>
Assets inside subdirectories can also be accessed.
@@ -153,13 +155,13 @@ is referenced as:
You can view the search path by inspecting +Rails.application.config.assets.paths+ in the Rails console.
-Additional (fully qualified) paths can be added to the pipeline in +config/application.rb+. For example:
+Besides the standard +assets/*+ paths, additional (fully qualified) paths can be added to the pipeline in +config/application.rb+. For example:
<ruby>
-config.assets.paths << Rails.root.join("app", "assets", "flash")
+config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
</ruby>
-Paths are traversed in the order that they occur in the search path.
+Paths are traversed in the order that they occur in the search path. By default, this means the files in +app/assets+ take precedence, and will mask corresponding paths in +lib+ and +vendor+.
It is important to note that files you want to reference outside a manifest must be added to the precompile array or they will not be available in the production environment.
@@ -430,7 +432,7 @@ NOTE. If you are precompiling your assets locally, you can use +bundle install -
The default matcher for compiling files includes +application.js+, +application.css+ and all non-JS/CSS files (this will include all image assets automatically):
<ruby>
-[ Proc.new{ |path| !File.extname(path).in?(['.js', '.css']) }, /application.(css|js)$/ ]
+[ Proc.new{ |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ]
</ruby>
NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, +.coffee+ and +.scss+ files are *not* automatically included as they compile to JS/CSS.
@@ -441,6 +443,8 @@ If you have other manifests or individual stylesheets and JavaScript files to in
config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
</erb>
+NOTE. Always specify an expected compiled filename that ends with js or css, even if you want to add Sass or CoffeeScript files to the precompile array.
+
The rake task also generates a +manifest.yml+ that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods to avoid handing the mapping requests back to Sprockets. A typical manifest file looks like:
<plain>
@@ -469,6 +473,7 @@ Precompiled assets exist on the filesystem and are served directly by your web s
For Apache:
<plain>
+# The Expires* directives requires the Apache module +mod_expires+ to be enabled.
<LocationMatch "^/assets/.*$">
# Use of ETag is discouraged when Last-Modified is present
Header unset ETag
@@ -651,7 +656,7 @@ WARNING: If you are upgrading an existing application and intend to use this opt
h3. Assets Cache Store
-Sprockets uses the default Rails cache store will be used to cache assets in development and production. This can be changed by setting +config.assets.cache_store+.
+The default Rails cache store will be used by Sprockets to cache assets in development and production. This can be changed by setting +config.assets.cache_store+.
<ruby>
config.assets.cache_store = :memory_store
diff --git a/guides/source/association_basics.textile b/guides/source/association_basics.textile
index 8ddc56bef1..d4c0a1ba74 100644
--- a/guides/source/association_basics.textile
+++ b/guides/source/association_basics.textile
@@ -630,12 +630,12 @@ The <tt>create_<em>association</em></tt> method returns a new object of the asso
h5. Options for +belongs_to+
-While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this assocation uses two such options:
<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true,
- :conditions => "active = 1"
+ belongs_to :customer, :dependent => :destroy,
+ :counter_cache => true
end
</ruby>
@@ -643,15 +643,11 @@ The +belongs_to+ association supports these options:
* +:autosave+
* +:class_name+
-* +:conditions+
* +:counter_cache+
* +:dependent+
* +:foreign_key+
-* +:include+
* +:inverse_of+
* +:polymorphic+
-* +:readonly+
-* +:select+
* +:touch+
* +:validate+
@@ -669,16 +665,6 @@ class Order < ActiveRecord::Base
end
</ruby>
-h6(#belongs_to-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :conditions => "active = 1"
-end
-</ruby>
-
h6(#belongs_to-counter_cache). +:counter_cache+
The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
@@ -737,35 +723,31 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-h6(#belongs_to-includes). +:include+
+h6(#belongs_to-inverse_of). +:inverse_of+
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options.
<ruby>
-class LineItem < ActiveRecord::Base
- belongs_to :order
+class Customer < ActiveRecord::Base
+ has_many :orders, :inverse_of => :customer
end
class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-
-class Customer < ActiveRecord::Base
- has_many :orders
+ belongs_to :customer, :inverse_of => :orders
end
</ruby>
-If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
+h6(#belongs_to-polymorphic). +:polymorphic+
-<ruby>
-class LineItem < ActiveRecord::Base
- belongs_to :order, :include => :customer
-end
+Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
+
+h6(#belongs_to-touch). +:touch+
+
+If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
+<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
+ belongs_to :customer, :touch => true
end
class Customer < ActiveRecord::Base
@@ -773,43 +755,58 @@ class Customer < ActiveRecord::Base
end
</ruby>
-NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
-
-h6(#belongs_to-inverse_of). +:inverse_of+
-
-The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options.
+In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :inverse_of => :customer
-end
-
class Order < ActiveRecord::Base
- belongs_to :customer, :inverse_of => :orders
+ belongs_to :customer, :touch => :orders_updated_at
end
</ruby>
-h6(#belongs_to-polymorphic). +:polymorphic+
+h6(#belongs_to-validate). +:validate+
-Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-h6(#belongs_to-readonly). +:readonly+
+h5(#belongs_to-scopes_for_belongs_to). Scopes for +belongs_to+
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+There may be times when you wish to customize the query used by +belongs_to+. Such customizations can be achieved via a scope block. For example:
-h6(#belongs_to-select). +:select+
+<ruby>
+class Order < ActiveRecord::Base
+ belongs_to :customer, -> { where :active => true },
+ :dependent => :destroy
+end
+</ruby>
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
-TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
+* +where+
+* +includes+
+* +readonly+
+* +select+
-h6(#belongs_to-touch). +:touch+
+h6(#belongs_to-where). +where+
-If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
+The +where+ method lets you specify the conditions that the associated object must meet.
<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer, :touch => true
+ belongs_to :customer, -> { where :active => true }
+end
+</ruby>
+
+h6(#belongs_to-includes). +includes+
+
+You can use the +includes+ method let you specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+<ruby>
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
end
class Customer < ActiveRecord::Base
@@ -817,17 +814,34 @@ class Customer < ActiveRecord::Base
end
</ruby>
-In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
+If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
<ruby>
+class LineItem < ActiveRecord::Base
+ belongs_to :order, -> { includes :customer }
+end
+
class Order < ActiveRecord::Base
- belongs_to :customer, :touch => :orders_updated_at
+ belongs_to :customer
+ has_many :line_items
+end
+
+class Customer < ActiveRecord::Base
+ has_many :orders
end
</ruby>
-h6(#belongs_to-validate). +:validate+
+NOTE: There's no need to use +includes+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+h6(#belongs_to-readonly). +readonly+
+
+If you use +readonly+, then the associated object will be read-only when retrieved via the association.
+
+h6(#belongs_to-select). +select+
+
+The +select+ method lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
+TIP: If you use the +select+ method on a +belongs_to+ association, you should also set the +:foreign_key+ option to guarantee the correct results.
h5(#belongs_to-do_any_associated_objects_exist). Do Any Associated Objects Exist?
@@ -924,15 +938,10 @@ The +has_one+ association supports these options:
* +:as+
* +:autosave+
* +:class_name+
-* +:conditions+
* +:dependent+
* +:foreign_key+
-* +:include+
* +:inverse_of+
-* +:order+
* +:primary_key+
-* +:readonly+
-* +:select+
* +:source+
* +:source_type+
* +:through+
@@ -956,22 +965,15 @@ class Supplier < ActiveRecord::Base
end
</ruby>
-h6(#has_one-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account, :conditions => "confirmed = 1"
-end
-</ruby>
-
h6(#has_one-dependent). +:dependent+
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
-If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised.
+Controls what happens to the associated object when its owner is destroyed:
-NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config.
+* +:destroy+ causes the associated object to also be destroyed
+* +:delete+ causes the asssociated object to be deleted directly from the database (so callbacks will not execute)
+* +:nullify+ causes the foreign key to be set to +NULL+. Callbacks are not executed.
+* +:restrict_with_exception+ causes an exception to be raised if there is an associated record
+* +:restrict_with_error+ causes an error to be added to the owner if there is an associated object
h6(#has_one-foreign_key). +:foreign_key+
@@ -985,30 +987,74 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-h6(#has_one-include). +:include+
+h6(#has_one-inverse_of). +:inverse_of+
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
<ruby>
class Supplier < ActiveRecord::Base
- has_one :account
+ has_one :account, :inverse_of => :supplier
end
class Account < ActiveRecord::Base
- belongs_to :supplier
- belongs_to :representative
+ belongs_to :supplier, :inverse_of => :account
end
+</ruby>
-class Representative < ActiveRecord::Base
- has_many :accounts
+h6(#has_one-primary_key). +:primary_key+
+
+By convention, Rails assumes that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+
+h6(#has_one-source). +:source+
+
+The +:source+ option specifies the source association name for a +has_one :through+ association.
+
+h6(#has_one-source_type). +:source_type+
+
+The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
+
+h6(#has_one-through). +:through+
+
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
+
+h6(#has_one-validate). +:validate+
+
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+
+h5(#belongs_to-scopes_for_has_one). Scopes for +has_one+
+
+There may be times when you wish to customize the query used by +has_one+. Such customizations can be achieved via a scope block. For example:
+
+<ruby>
+class Supplier < ActiveRecord::Base
+ has_one :account, -> { where :active => true }
end
</ruby>
-If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
+
+* +where+
+* +includes+
+* +readonly+
+* +select+
+
+h6(#has_one-where). +where+
+
+The +where+ method lets you specify the conditions that the associated object must meet.
+
+<ruby>
+class Supplier < ActiveRecord::Base
+ has_one :account, -> { where "confirmed = 1" }
+end
+</ruby>
+
+h6(#has_one-includes). +includes+
+
+You can use the +includes+ method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
<ruby>
class Supplier < ActiveRecord::Base
- has_one :account, :include => :representative
+ has_one :account
end
class Account < ActiveRecord::Base
@@ -1021,51 +1067,30 @@ class Representative < ActiveRecord::Base
end
</ruby>
-h6(#has_one-inverse_of). +:inverse_of+
-
-The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
+If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
<ruby>
class Supplier < ActiveRecord::Base
- has_one :account, :inverse_of => :supplier
+ has_one :account, -> { includes :representative }
end
class Account < ActiveRecord::Base
- belongs_to :supplier, :inverse_of => :account
+ belongs_to :supplier
+ belongs_to :representative
end
-</ruby>
-
-h6(#has_one-order). +:order+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-
-h6(#has_one-primary_key). +:primary_key+
-
-By convention, Rails assumes that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-h6(#has_one-readonly). +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-
-h6(#has_one-select). +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-h6(#has_one-source). +:source+
-
-The +:source+ option specifies the source association name for a +has_one :through+ association.
-
-h6(#has_one-source_type). +:source_type+
-
-The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
+class Representative < ActiveRecord::Base
+ has_many :accounts
+end
+</ruby>
-h6(#has_one-through). +:through+
+h6(#has_one-readonly). +readonly+
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
+If you use the +readonly+ method, then the associated object will be read-only when retrieved via the association.
-h6(#has_one-validate). +:validate+
+h6(#has_one-select). +select+
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+The +select+ method lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
h5(#has_one-do_any_associated_objects_exist). Do Any Associated Objects Exist?
@@ -1256,25 +1281,13 @@ The +has_many+ association supports these options:
* +:as+
* +:autosave+
* +:class_name+
-* +:conditions+
-* +:counter_sql+
* +:dependent+
-* +:extend+
-* +:finder_sql+
* +:foreign_key+
-* +:group+
-* +:include+
* +:inverse_of+
-* +:limit+
-* +:offset+
-* +:order+
* +:primary_key+
-* +:readonly+
-* +:select+
* +:source+
* +:source_type+
* +:through+
-* +:uniq+
* +:validate+
h6(#has_many-as). +:as+
@@ -1295,85 +1308,127 @@ class Customer < ActiveRecord::Base
end
</ruby>
-h6(#has_many-conditions). +:conditions+
+h6(#has_many-dependent). +:dependent+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
+Controls what happens to the associated objects when their owner is destroyed:
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
- :conditions => "confirmed = 1"
-end
-</ruby>
+* +:destroy+ causes all the associated objects to also be destroyed
+* +:delete_all+ causes all the asssociated objects to be deleted directly from the database (so callbacks will not execute)
+* +:nullify+ causes the foreign keys to be set to +NULL+. Callbacks are not executed.
+* +:restrict_with_exception+ causes an exception to be raised if there are any associated records
+* +:restrict_with_error+ causes an error to be added to the owner if there are any associated objects
-You can also set conditions via a hash:
+NOTE: This option is ignored when you use the +:through+ option on the association.
+
+h6(#has_many-foreign_key). +:foreign_key+
+
+By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
<ruby>
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
- :conditions => { :confirmed => true }
+ has_many :orders, :foreign_key => "cust_id"
end
</ruby>
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-If you need to evaluate conditions dynamically at runtime, use a proc:
+h6(#has_many-inverse_of). +:inverse_of+
+
+The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
<ruby>
class Customer < ActiveRecord::Base
- has_many :latest_orders, :class_name => "Order",
- :conditions => proc { ["orders.created_at > ?", 10.hours.ago] }
+ has_many :orders, :inverse_of => :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, :inverse_of => :orders
end
</ruby>
-h6(#has_many-counter_sql). +:counter_sql+
+h6(#has_many-primary_key). +:primary_key+
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+By convention, Rails assumes that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting the +SELECT ... FROM+ clause of your +:finder_sql+ statement by +SELECT COUNT(*) FROM+.
+h6(#has_many-source). +:source+
-h6(#has_many-dependent). +:dependent+
+The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
-If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised.
+h6(#has_many-source_type). +:source_type+
-NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config.
+The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
-NOTE: This option is ignored when you use the +:through+ option on the association.
+h6(#has_many-through). +:through+
-h6(#has_many-extend). +:extend+
+The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has_many-through-association">earlier in this guide</a>.
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
+h6(#has_many-validate). +:validate+
-h6(#has_many-finder_sql). +:finder_sql+
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+h5(#has_many-scopes_for_has_many). Scopes for +has_many+
-h6(#has_many-foreign_key). +:foreign_key+
+There may be times when you wish to customize the query used by +has_many+. Such customizations can be achieved via a scope block. For example:
-By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+<ruby>
+class Customer < ActiveRecord::Base
+ has_many :orders, -> { where :processed => true }
+end
+</ruby>
+
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
+
+* +where+
+* +extending+
+* +group+
+* +includes+
+* +limit+
+* +offset+
+* +order+
+* +readonly+
+* +select+
+* +uniq+
+
+h6(#has_many-where). +where+
+
+The +where+ method lets you specify the conditions that the associated object must meet.
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders, :foreign_key => "cust_id"
+ has_many :confirmed_orders, -> { where "confirmed = 1" },
+ :class_name => "Order"
end
</ruby>
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+You can also set conditions via a hash:
-h6(#has_many-group). +:group+
+<ruby>
+class Customer < ActiveRecord::Base
+ has_many :confirmed_orders, -> { where :confirmed => true },
+ :class_name => "Order"
+end
+</ruby>
+
+If you use a hash-style +where+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+h6(#has_many-extending). +extending+
+
+The +extending+ method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
+
+h6(#has_many-group). +group+
+
+The +group+ method supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
<ruby>
class Customer < ActiveRecord::Base
- has_many :line_items, :through => :orders, :group => "orders.id"
+ has_many :line_items, -> { group 'orders.id' },
+ :through => :orders
end
</ruby>
-h6(#has_many-include). +:include+
+h6(#has_many-includes). +includes+
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+You can use the +includes+ method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
<ruby>
class Customer < ActiveRecord::Base
@@ -1394,7 +1449,7 @@ If you frequently retrieve line items directly from customers (+@customer.orders
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders, :include => :line_items
+ has_many :orders, -> { includes :line_items }
end
class Order < ActiveRecord::Base
@@ -1407,74 +1462,45 @@ class LineItem < ActiveRecord::Base
end
</ruby>
-h6(#has_many-inverse_of). +:inverse_of+
+h6(#has_many-limit). +limit+
-The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
+The +limit+ method lets you restrict the total number of objects that will be fetched through an association.
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders, :inverse_of => :customer
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer, :inverse_of => :orders
+ has_many :recent_orders,
+ -> { order('order_date desc').limit(100) },
+ :class_name => "Order",
end
</ruby>
-h6(#has_many-limit). +:limit+
+h6(#has_many-offset). +offset+
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => "Order",
- :order => "order_date DESC", :limit => 100
-end
-</ruby>
+The +offset+ method lets you specify the starting offset for fetching objects via an association. For example, +-> { offset(11) }+ will skip the first 11 records.
-h6(#has_many-offset). +:offset+
+h6(#has_many-order). +order+
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
-
-h6(#has_many-order). +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
+The +order+ method dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders, :order => "date_confirmed DESC"
+ has_many :orders, -> { order "date_confirmed DESC" }
end
</ruby>
-h6(#has_many-primary_key). +:primary_key+
-
-By convention, Rails assumes that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-h6(#has_many-readonly). +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-
-h6(#has_many-select). +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-
-WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
+h6(#has_many-readonly). +readonly+
-h6(#has_many-source). +:source+
-
-The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
-
-h6(#has_many-source_type). +:source_type+
+If you use the +readonly+ method, then the associated objects will be read-only when retrieved via the association.
-The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
+h6(#has_many-select). +select+
-h6(#has_many-through). +:through+
+The +select+ method lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has_many-through-association">earlier in this guide</a>.
+WARNING: If you specify your own +select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
-h6(#has_many-uniq). +:uniq+
+h6(#has_many-uniq). +uniq+
-Set the +:uniq+ option to true to keep the collection free of duplicates. This is mostly useful together with the +:through+ option.
+Use the +uniq+ method to keep the collection free of duplicates. This is mostly useful together with the +:through+ option.
<ruby>
class Person < ActiveRecord::Base
@@ -1492,12 +1518,12 @@ Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Readin
In the above case there are two readings and +person.posts+ brings out both of them even though these records are pointing to the same post.
-Now let's set +:uniq+ to true:
+Now let's set +uniq+:
<ruby>
class Person
has_many :readings
- has_many :posts, :through => :readings, :uniq => true
+ has_many :posts, -> { uniq }, :through => :readings
end
person = Person.create(:name => 'honda')
@@ -1510,10 +1536,6 @@ Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Readin
In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records.
-h6(#has_many-validate). +:validate+
-
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-
h5(#has_many-when_are_objects_saved). When are Objects Saved?
When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
@@ -1699,22 +1721,8 @@ The +has_and_belongs_to_many+ association supports these options:
* +:association_foreign_key+
* +:autosave+
* +:class_name+
-* +:conditions+
-* +:counter_sql+
-* +:delete_sql+
-* +:extend+
-* +:finder_sql+
* +:foreign_key+
-* +:group+
-* +:include+
-* +:insert_sql+
* +:join_table+
-* +:limit+
-* +:offset+
-* +:order+
-* +:readonly+
-* +:select+
-* +:uniq+
* +:validate+
h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+
@@ -1745,120 +1753,126 @@ class Parts < ActiveRecord::Base
end
</ruby>
-h6(#has_and_belongs_to_many-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
- :conditions => "factory = 'Seattle'"
-end
-</ruby>
+h6(#has_and_belongs_to_many-foreign_key). +:foreign_key+
-You can also set conditions via a hash:
+By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
- :conditions => { :factory => 'Seattle' }
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id",
+ :association_foreign_key => "other_user_id"
end
</ruby>
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the +factory+ column has the value "Seattle".
-
-h6(#has_and_belongs_to_many-counter_sql). +:counter_sql+
+h6(#has_and_belongs_to_many-join_table). +:join_table+
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting the +SELECT ... FROM+ clause of your +:finder_sql+ statement by +SELECT COUNT(*) FROM+.
+h6(#has_and_belongs_to_many-validate). +:validate+
-h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
+h5(#has_and_belongs_to_many-scopes_for_has_and_belongs_to_many). Scopes for +has_and_belongs_to_many+
-h6(#has_and_belongs_to_many-extend). +:extend+
+There may be times when you wish to customize the query used by +has_and_belongs_to_many+. Such customizations can be achieved via a scope block. For example:
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
+<ruby>
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, -> { where :active => true }
+end
+</ruby>
-h6(#has_and_belongs_to_many-finder_sql). +:finder_sql+
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+* +where+
+* +extending+
+* +group+
+* +includes+
+* +limit+
+* +offset+
+* +order+
+* +readonly+
+* +select+
+* +uniq+
-h6(#has_and_belongs_to_many-foreign_key). +:foreign_key+
+h6(#has_and_belongs_to_many-where). +where+
-By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+The +where+ method lets you specify the conditions that the associated object must meet.
<ruby>
-class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
- :association_foreign_key => "other_user_id"
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,
+ -> { where "factory = 'Seattle'" }
end
</ruby>
-h6(#has_and_belongs_to_many-group). +:group+
-
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+You can also set conditions via a hash:
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :group => "factory"
+ has_and_belongs_to_many :assemblies,
+ -> { where :factory => 'Seattle' }
end
</ruby>
-h6(#has_and_belongs_to_many-include). +:include+
+If you use a hash-style +where+, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the +factory+ column has the value "Seattle".
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
+h6(#has_and_belongs_to_many-extending). +extending+
-h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+
+The +extending+ method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
-Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
+h6(#has_and_belongs_to_many-group). +group+
-h6(#has_and_belongs_to_many-join_table). +:join_table+
+The +group+ method supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
+<ruby>
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, -> { group "factory" }
+end
+</ruby>
+
+h6(#has_and_belongs_to_many-includes). +includes+
-h6(#has_and_belongs_to_many-limit). +:limit+
+You can use the +includes+ method to specify second-order associations that should be eager-loaded when this association is used.
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
+h6(#has_and_belongs_to_many-limit). +limit+
+
+The +limit+ method lets you restrict the total number of objects that will be fetched through an association.
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "created_at DESC",
- :limit => 50
+ has_and_belongs_to_many :assemblies,
+ -> { order("created_at DESC").limit(50) }
end
</ruby>
-h6(#has_and_belongs_to_many-offset). +:offset+
+h6(#has_and_belongs_to_many-offset). +offset+
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
+The +offset+ method lets you specify the starting offset for fetching objects via an association. For example, if you set +offset(11)+, it will skip the first 11 records.
-h6(#has_and_belongs_to_many-order). +:order+
+h6(#has_and_belongs_to_many-order). +order+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
+The +order+ method dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+ has_and_belongs_to_many :assemblies,
+ -> { order "assembly_name ASC" }
end
</ruby>
-h6(#has_and_belongs_to_many-readonly). +:readonly+
+h6(#has_and_belongs_to_many-readonly). +readonly+
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
+If you use the +readonly+ method, then the associated objects will be read-only when retrieved via the association.
-h6(#has_and_belongs_to_many-select). +:select+
+h6(#has_and_belongs_to_many-select). +select+
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+The +select+ method lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-h6(#has_and_belongs_to_many-uniq). +:uniq+
+h6(#has_and_belongs_to_many-uniq). +uniq+
-Specify the +:uniq => true+ option to remove duplicates from the collection.
-
-h6(#has_and_belongs_to_many-validate). +:validate+
-
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
+Use the +uniq+ method to remove duplicates from the collection.
h5(#has_and_belongs_to_many-when_are_objects_saved). When are Objects Saved?
@@ -1938,20 +1952,11 @@ module FindRecentExtension
end
class Customer < ActiveRecord::Base
- has_many :orders, :extend => FindRecentExtension
+ has_many :orders, -> { extending FindRecentExtension }
end
class Supplier < ActiveRecord::Base
- has_many :deliveries, :extend => FindRecentExtension
-end
-</ruby>
-
-To include more than one extension module in a single association, specify an array of modules:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders,
- :extend => [FindRecentExtension, FindActiveExtension]
+ has_many :deliveries, -> { extending FindRecentExtension }
end
</ruby>
diff --git a/guides/source/caching_with_rails.textile b/guides/source/caching_with_rails.textile
index 3ee36ae971..815b2ef9c2 100644
--- a/guides/source/caching_with_rails.textile
+++ b/guides/source/caching_with_rails.textile
@@ -33,7 +33,7 @@ class ProductsController < ActionController
caches_page :index
def index
- @products = Products.all
+ @products = Product.all
end
end
</ruby>
@@ -52,7 +52,7 @@ class ProductsController < ActionController
caches_page :index
def index
- @products = Products.all
+ @products = Product.all
end
def create
diff --git a/guides/source/command_line.textile b/guides/source/command_line.textile
index 19e42cea93..39b75c2781 100644
--- a/guides/source/command_line.textile
+++ b/guides/source/command_line.textile
@@ -160,7 +160,7 @@ $ rails generate controller Greetings hello
create app/assets/stylesheets/greetings.css.scss
</shell>
-What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a javascript file and a stylesheet file.
+What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file and a stylesheet file.
Check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+):
@@ -477,6 +477,53 @@ h4. Miscellaneous
* +rake secret+ will give you a pseudo-random key to use for your session secret.
* <tt>rake time:zones:all</tt> lists all the timezones Rails knows about.
+h4. Writing Rake Tasks
+
+If you have (or want to write) any automation scripts outside your app (data import, checks, etc), you can make them as rake tasks. It's easy.
+
+INFO: "Complete guide about how to write tasks":http://rake.rubyforge.org/files/doc/rakefile_rdoc.html is available in the official documentation.
+
+Tasks should be placed in <tt>Rails.root/lib/tasks</tt> and should have a +.rake+ extension.
+
+Each task should be defined in next format (dependencies are optional):
+
+<ruby>
+desc "I am short, but comprehensive description for my cool task"
+task :task_name => [:prerequisite_task, :another_task_we_depend_on] do
+ # All your magick here
+ # Any valid Ruby code is allowed
+end
+</ruby>
+
+If you need to pass parameters, you can use next format (both arguments and dependencies are optional):
+
+<ruby>
+task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
+ # You can use args from here
+end
+</ruby>
+
+You can group tasks by placing them in namespaces:
+
+<ruby>
+namespace :do
+ desc "This task does nothing"
+ task :nothing do
+ # Seriously, nothing
+ end
+end
+</ruby>
+
+You can see your tasks to be listed by <tt>rake -T</tt> command. And, according to the examples above, you can invoke them as follows:
+
+<shell>
+rake task_name
+rake "task_name[value 1]" # entire argument string should be quoted
+rake do:nothing
+</shell>
+
+NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the +environment+ task, which will load your application code.
+
h3. The Rails Advanced Command Line
More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile
index cd9aab4892..9db375c2ca 100644
--- a/guides/source/configuring.textile
+++ b/guides/source/configuring.textile
@@ -50,8 +50,6 @@ config.after_initialize do
end
</ruby>
-* +config.allow_concurrency+ should be true to allow concurrent (threadsafe) action processing. False by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Can also be enabled with +threadsafe!+.
-
* +config.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of +config.action_controller.asset_host+.
* +config.asset_path+ lets you decorate asset paths. This can be a callable, a string, or be +nil+ which is the default. For example, the normal path for +blog.js+ would be +/javascripts/blog.js+, let that absolute path be +path+. If +config.asset_path+ is a callable, Rails calls it when generating asset paths passing +path+ as argument. If +config.asset_path+ is a string, it is expected to be a +sprintf+ format string with a +%s+ where +path+ will get inserted. In either case, Rails outputs the decorated path. Shorter version of +config.action_controller.asset_path+.
@@ -89,6 +87,10 @@ end
* +config.dependency_loading+ is a flag that allows you to disable constant autoloading setting it to false. It only has effect if +config.cache_classes+ is true, which it is by default in production mode. This flag is set to false by +config.threadsafe!+.
+* +config.eager_load+ when true, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks and any other registered namespace.
+
+* +config.eager_load_namespaces+ registers namespaces that are eager loaded when +config.eager_load+ is true. All namespaces in the list must respond to the +eager_load!+ method.
+
* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application.
* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8.
@@ -109,8 +111,6 @@ end
* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":#configuring-middleware section below.
-* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Enabled by +config.threadsafe!+. Defaults to +nil+, so is disabled.
-
* +config.queue+ configures a different queue implementation for the application. Defaults to +Rails::Queueing::Queue+. Note that, if the default queue is changed, the default +queue_consumer+ is not going to be initialized, it is up to the new queue implementation to handle starting and shutting down its own consumer(s).
* +config.queue_consumer+ configures a different consumer implementation for the default queue. Defaults to +Rails::Queueing::ThreadedConsumer+.
@@ -127,11 +127,7 @@ end
config.session_store :my_custom_store
</ruby>
-This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. In addition to symbols, they can also be objects implementing a certain API, like +ActiveRecord::SessionStore+, in which case no special namespace is required.
-
-* +config.threadsafe!+ enables +allow_concurrency+, +cache_classes+, +dependency_loading+ and +preload_frameworks+ to make the application threadsafe.
-
-WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+.
+This custom store must be defined as +ActionDispatch::Session::MyCustomStore+.
* +config.time_zone+ sets the default time zone for the application and enables time zone awareness for Active Record.
@@ -157,7 +153,7 @@ Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets wit
* +config.assets.digest+ enables the use of MD5 fingerprints in asset names. Set to +true+ by default in +production.rb+.
-* +config.assets.debug+ disables the concatenation and compression of assets. Set to +false+ by default in +development.rb+.
+* +config.assets.debug+ disables the concatenation and compression of assets. Set to +true+ by default in +development.rb+.
* +config.assets.manifest+ defines the full path to be used for the asset precompiler's manifest file. Defaults to using +config.assets.prefix+.
@@ -186,7 +182,7 @@ The full set of methods that can be used in this block are as follows:
* +force_plural+ allows pluralized model names. Defaults to +false+.
* +helper+ defines whether or not to generate helpers. Defaults to +true+.
* +integration_tool+ defines which integration tool to use. Defaults to +nil+.
-* +javascripts+ turns on the hook for javascripts in generators. Used in Rails for when the +scaffold+ generator is run. Defaults to +true+.
+* +javascripts+ turns on the hook for JavaScript files in generators. Used in Rails for when the +scaffold+ generator is run. Defaults to +true+.
* +javascript_engine+ configures the engine to be used (for eg. coffee) when generating assets. Defaults to +nil+.
* +orm+ defines which orm to use. Defaults to +false+ and will use Active Record by default.
* +performance_tool+ defines which performance tool to use. Defaults to +nil+.
@@ -203,7 +199,7 @@ Every Rails application comes with a standard set of middleware which it uses in
* +ActionDispatch::SSL+ forces every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to +true+. Options passed to this can be configured by using +config.ssl_options+.
* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is +true+.
-* +Rack::Lock+ wraps the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to +false+, which it is by default.
+* +Rack::Lock+ wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when +config.cache_classes_+ is +false+.
* +ActiveSupport::Cache::Strategy::LocalCache+ serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
* +Rack::Runtime+ sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request.
* +Rails::Rack::Logger+ notifies the logs that the request has began. After request is complete, flushes all the logs.
@@ -286,8 +282,6 @@ h4. Configuring Active Record
* +config.active_record.auto_explain_threshold_in_seconds+ configures the threshold for automatic EXPLAINs (+nil+ disables this feature). Queries exceeding the threshold get their query plan logged. Default is 0.5 in development mode.
-* +config.active_record.dependent_restrict_raises+ will control the behavior when an object with a <tt>:dependent => :restrict</tt> association is deleted. Setting this to false will prevent +DeleteRestrictionError+ from being raised and instead will add an error on the model object. Defaults to false in the development mode.
-
* +config.active_record.mass_assignment_sanitizer+ will determine the strictness of the mass assignment sanitization within Rails. Defaults to +:strict+. In this mode, mass assigning any non-+attr_accessible+ attribute in a +create+ or +update_attributes+ call will raise an exception. Setting this option to +:logger+ will only print to the log file when an attribute is being assigned and will not raise an exception.
The MySQL adapter adds one additional configuration option:
@@ -328,18 +322,16 @@ The caching code adds two additional settings:
* +ActionController::Base.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+.
-The Active Record session store can also be configured:
-
-* +ActiveRecord::SessionStore::Session.table_name+ sets the name of the table used to store sessions. Defaults to +sessions+.
-
-* +ActiveRecord::SessionStore::Session.primary_key+ sets the name of the ID column used in the sessions table. Defaults to +session_id+.
-
-* +ActiveRecord::SessionStore::Session.data_column_name+ sets the name of the column which stores marshaled session data. Defaults to +data+.
-
h4. Configuring Action Dispatch
* +config.action_dispatch.session_store+ sets the name of the store for session data. The default is +:cookie_store+; other valid options include +:active_record_store+, +:mem_cache_store+ or the name of your own custom class.
+* +config.action_dispatch.default_headers+ is a hash with HTTP headers that are set by default in each response. By default, this is defined as:
+
+<ruby>
+config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X-XSS-Protection' => '1; mode=block', 'X-Content-Type-Options' => 'nosniff' }
+</ruby>
+
* +config.action_dispatch.tld_length+ sets the TLD (top-level domain) length for the application. Defaults to +1+.
* +ActionDispatch::Callbacks.before+ takes a block of code to run before the request.
@@ -652,8 +644,6 @@ Serves as a placeholder so that +:load_environment_config+ can be defined to run
*+load_active_support+* Requires +active_support/dependencies+ which sets up the basis for Active Support. Optionally requires +active_support/all+ if +config.active_support.bare+ is un-truthful, which is the default.
-*+preload_frameworks+* Loads all autoload dependencies of Rails automatically if +config.preload_frameworks+ is +true+ or "truthful". By default this configuration option is disabled. In Rails, when internal classes are referenced for the first time they are autoloaded. +:preload_frameworks+ loads all of this at once on initialization.
-
*+initialize_logger+* Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, provided that no initializer inserted before this point has defined +Rails.logger+.
*+initialize_cache+* If +Rails.cache+ isn't set yet, initializes the cache by referencing the value in +config.cache_store+ and stores the outcome as +Rails.cache+. If this object responds to the +middleware+ method, its middleware is inserted before +Rack::Runtime+ in the middleware stack.
@@ -748,13 +738,13 @@ The error occurred while evaluating nil.each
*+build_middleware_stack+* Builds the middleware stack for the application, returning an object which has a +call+ method which takes a Rack environment object for the request.
-*+eager_load!+* If +config.cache_classes+ is true, runs the +config.before_eager_load+ hooks and then calls +eager_load!+ which will load all the Ruby files from +config.eager_load_paths+.
+*+eager_load!+* If +config.eager_load+ is true, runs the +config.before_eager_load+ hooks and then calls +eager_load!+ which will load all +config.eager_load_namespaces+.
*+finisher_hook+* Provides a hook for after the initialization of process of the application is complete, as well as running all the +config.after_initialize+ blocks for the application, railties and engines.
*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
-*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to true and +config.dependency_loading+ is set to false.
+*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.eager_load+ is set to true.
h3. Database pooling
diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile
index 1dadce2083..427733fe03 100644
--- a/guides/source/contributing_to_ruby_on_rails.textile
+++ b/guides/source/contributing_to_ruby_on_rails.textile
@@ -34,20 +34,28 @@ h4. What about Feature Requests?
Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
-h3. Running the Test Suite
+If you'd like feedback on an idea for a feature before doing the work for make a patch, please send an email to the "rails-core mailing list":https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core. You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted." But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require.
+
+h3. Setting Up a Development Environment
To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
-h4. Install Git
+h4. The Easy Way
+
+The easiest way to get a development environment ready to hack is to use the "Rails development box":https://github.com/rails/rails-dev-box.
+
+h4. The Hard Way
+
+h5. Install Git
-Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git:
+Ruby on Rails uses Git for source code control. The "Git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with Git:
-* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about git to get by.
-* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
-* "GitHub":http://help.github.com offers links to a variety of git resources.
-* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
+* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about Git to get by.
+* The "PeepCode screencast":https://peepcode.com/products/git on Git ($9) is easier to follow.
+* "GitHub":http://help.github.com offers links to a variety of Git resources.
+* "Pro Git":http://git-scm.com/book is an entire book about Git with a Creative Commons license.
-h4. Clone the Ruby on Rails Repository
+h5. Clone the Ruby on Rails Repository
Navigate to the folder where you want the Ruby on Rails source code (it will create its own +rails+ subdirectory) and run:
@@ -56,7 +64,7 @@ $ git clone git://github.com/rails/rails.git
$ cd rails
</shell>
-h4. Set up and Run the Tests
+h5. Set up and Run the Tests
The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests.
@@ -66,12 +74,26 @@ Install first libxml2 and libxslt together with their development files for Noko
$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev
</shell>
+If you are on Fedora or CentOS, you can run
+
+<shell>
+$ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel
+</shell>
+
+If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions at the "Red Hat/CentOS section of the Nokogiri tutorials":http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos .
+
Also, SQLite3 and its development files for the +sqlite3-ruby+ gem -- in Ubuntu you're done with just
<shell>
$ sudo apt-get install sqlite3 libsqlite3-dev
</shell>
+And if you are on Fedora or CentOS, you're done with
+
+<shell>
+$ sudo yum install sqlite3 sqlite3-devel
+</shell>
+
Get a recent version of "Bundler":http://gembundler.com/:
<shell>
@@ -112,42 +134,30 @@ $ cd actionpack
$ bundle exec ruby -Itest test/template/form_helper_test.rb
</shell>
-h4. Warnings
-
-The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.
-
-As of this writing (December, 2010) they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
-
-<shell>
-$ RUBYOPT=-W0 bundle exec rake test
-</shell>
-
-h4. Testing Active Record
+h5. Active Record Setup
The test suite of Active Record attempts to run four times: once for SQLite3, once for each of the two MySQL gems (+mysql+ and +mysql2+), and once for PostgreSQL. We are going to see now how to set up the environment for them.
WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
-h5. Database Configuration
+h6. Database Configuration
The Active Record test suite requires a custom config file: +activerecord/test/config.yml+. An example is provided in +activerecord/test/config.example.yml+ which can be copied and used as needed for your environment.
-h5. SQLite3
+h6. MySQL and PostgreSQL
-The gem +sqlite3-ruby+ does not belong to the "db" group. Indeed, if you followed the instructions above you're ready. This is how you run the Active Record test suite only for SQLite3:
+To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run
<shell>
-$ cd activerecord
-$ bundle exec rake test_sqlite3
+$ sudo apt-get install mysql-server libmysqlclient15-dev
+$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
</shell>
-h5. MySQL and PostgreSQL
-
-To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run
+On Fedora or CentOS, just run:
<shell>
-$ sudo apt-get install mysql-server libmysqlclient15-dev
-$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
+$ sudo yum install mysql-server mysql-devel
+$ sudo yum install postgresql-server postgresql-devel
</shell>
After that run:
@@ -172,7 +182,7 @@ and create the test databases:
<shell>
$ cd activerecord
-$ rake mysql:build_databases
+$ bundle exec rake mysql:build_databases
</shell>
PostgreSQL's authentication works differently. A simple way to set up the development environment for example is to run with your development account
@@ -185,14 +195,23 @@ and then create the test databases with
<shell>
$ cd activerecord
-$ rake postgresql:build_databases
+$ bundle exec rake postgresql:build_databases
</shell>
NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
NOTE: You'll see the following warning (or localized warning) during activating HStore extension in PostgreSQL 9.1.x or earlier: "WARNING: => is deprecated as an operator".
-If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files to provide different credentials on your machine if you must, but obviously you should not push any such changes back to Rails.
+If you’re using another database, check the file +activerecord/test/config.yml+ or +activerecord/test/config.example.yml+ for default connection information. You can edit +activerecord/test/config.yml+ to provide different credentials on your machine if you must, but obviously you should not push any such changes back to Rails.
+
+h3. Testing Active Record
+
+This is how you run the Active Record test suite only for SQLite3:
+
+<shell>
+$ cd activerecord
+$ bundle exec rake test_sqlite3
+</shell>
You can now run the tests as you did for +sqlite3+. The tasks are respectively
@@ -202,7 +221,7 @@ test_mysql2
test_postgresql
</shell>
-As we mentioned before
+Finally,
<shell>
$ bundle exec rake test
@@ -218,6 +237,16 @@ $ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.
You can invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+ also. See the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/travis.rb+ for the test suite run by the continuous integration server.
+h4. Warnings
+
+The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.
+
+As of this writing (December, 2010) they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
+
+<shell>
+$ RUBYOPT=-W0 bundle exec rake test
+</shell>
+
h4. Older Versions of Ruby on Rails
If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 3-0-stable branch:
@@ -227,7 +256,7 @@ $ git branch --track 3-0-stable origin/3-0-stable
$ git checkout 3-0-stable
</shell>
-TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
+TIP: You may want to "put your Git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
h3. Helping to Resolve Existing Issues
@@ -308,7 +337,7 @@ $ cd rails
$ git checkout -b my_new_branch
</shell>
-It doesn’t matter much what name you use, because this branch will only exist on your local computer and your personal repository on Github. It won't be part of the Rails git repository.
+It doesn’t matter much what name you use, because this branch will only exist on your local computer and your personal repository on Github. It won't be part of the Rails Git repository.
h4. Write Your Code
@@ -336,6 +365,31 @@ Rails follows a simple set of coding style conventions.
The above are guidelines -- please use your best judgment in using them.
+h4. Updating the CHANGELOG
+
+The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version.
+
+You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, commiting a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG.
+
+A CHANGELOG entry should summarize what was changed and should end with author's name. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach issue's number. Here is an example CHANGELOG entry:
+
+<plain>
+* Summary of a change that briefly describes what was changed. You can use multiple
+ lines and wrap them at around 80 characters. Code examples are ok, too, if needed:
+
+ class Foo
+ def bar
+ puts 'baz'
+ end
+ end
+
+ You can continue after the code example and you can attach issue number. GH#1234
+
+ *Your Name*
+</plain>
+
+Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.
+
h4. Sanity Check
You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
@@ -344,7 +398,7 @@ You might want also to check out the "RailsBridge BugMash":http://wiki.railsbrid
h4. Commit Your Changes
-When you're happy with the code on your computer, you need to commit the changes to git:
+When you're happy with the code on your computer, you need to commit the changes to Git:
<shell>
$ git commit -a
@@ -363,7 +417,7 @@ the commit content is obvious, it may not be obvious to others. You
should add such description also if it's already present in bug tracker,
it should not be necessary to visit a webpage to check the history.
-Description can have multiple paragraps and you can use code examples
+Description can have multiple paragraphs and you can use code examples
inside, just indent it with 4 spaces:
class PostsController
@@ -472,7 +526,7 @@ It’s entirely possible that the feedback you get will suggest changes. Don’t
h4. Backporting
-Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a rails team member before backporting your changes to avoid wasted effort.
+Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort.
For simple fixes, the easiest way to backport your changes is to "extract a diff from your changes in master and apply them to the target branch":http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git.
@@ -497,9 +551,9 @@ $ git apply ~/my_changes.patch
This works well for simple changes. However, if your changes are complicated or if the code in master has deviated significantly from your target branch, it might require more work on your part. The difficulty of a backport varies greatly from case to case, and sometimes it is simply not worth the effort.
-Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the ruby versions listed in +.travis.yml+ before submitting your pull request.
+Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the Ruby versions listed in +.travis.yml+ before submitting your pull request.
-And then ... think about your next contribution!
+And then... think about your next contribution!
h3. Rails Contributors
diff --git a/guides/source/credits.html.erb b/guides/source/credits.html.erb
index 04deec6a11..e25168d58d 100644
--- a/guides/source/credits.html.erb
+++ b/guides/source/credits.html.erb
@@ -64,7 +64,7 @@ Oscar Del Ben is a software engineer at <a href="http://www.wildfireapp.com/">Wi
<% end %>
<%= author('Pratik Naik', 'lifo') do %>
- Pratik Naik is a Ruby on Rails consultant with <a href="http://www.actionrails.com">ActionRails</a> and also a member of the <a href="http://rubyonrails.org/core">Rails core team</a>. He maintains a blog at <a href="http://m.onkey.org">has_many :bugs, :through =&gt; :rails</a> and has an active <a href="http://twitter.com/lifo">twitter account</a>.
+ Pratik Naik is a Ruby on Rails developer at <a href="http://www.37signals.com">37signals</a> and also a member of the <a href="http://rubyonrails.org/core">Rails core team</a>. He maintains a blog at <a href="http://m.onkey.org">has_many :bugs, :through =&gt; :rails</a> and has a semi-active <a href="http://twitter.com/lifo">twitter account</a>.
<% end %>
<%= author('Emilio Tagua', 'miloops') do %>
diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile
index cc172042e9..667f2d2140 100644
--- a/guides/source/debugging_rails_applications.textile
+++ b/guides/source/debugging_rails_applications.textile
@@ -626,7 +626,7 @@ In this section, you will learn how to find and fix such leaks by using tools su
h4. BleakHouse
-"BleakHouse":https://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks.
+"BleakHouse":https://github.com/evan/bleak_house/ is a library for finding memory leaks.
If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
@@ -675,7 +675,7 @@ To analyze it, just run the listed command. The top 20 leakiest lines will be li
This way you can find where your application is leaking memory and fix it.
-If "BleakHouse":https://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
+If "BleakHouse":https://github.com/evan/bleak_house/ doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
h4. Valgrind
@@ -708,4 +708,4 @@ h3. References
* "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html
* "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/
* "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging
-* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html
+* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/
diff --git a/guides/source/engines.textile b/guides/source/engines.textile
index 86e7254201..fe8fcfbb3f 100644
--- a/guides/source/engines.textile
+++ b/guides/source/engines.textile
@@ -217,7 +217,7 @@ This helps prevent conflicts with any other engine or application that may have
Finally, two files that are the assets for this resource are generated, +app/assets/javascripts/blorgh/posts.js+ and +app/assets/javascripts/blorgh/posts.css+. You'll see how to use these a little later.
-By default, the scaffold styling is not applied to the engine as the engine's layout file, +app/views/blorgh/application.html.erb+ doesn't load it. To make this apply, insert this line into the +<head>+ tag of this layout:
+By default, the scaffold styling is not applied to the engine as the engine's layout file, +app/views/blorgh/application.html.erb+ doesn't load it. To make this apply, insert this line into the +&lt;head&gt;+ tag of this layout:
<erb>
<%= stylesheet_link_tag "scaffold" %>
@@ -347,7 +347,7 @@ The form will be making a +POST+ request to +/posts/:post_id/comments+, which wi
<ruby>
def create
@post = Post.find(params[:post_id])
- @comment = @post.comments.build(params[:comment])
+ @comment = @post.comments.create(params[:comment])
flash[:notice] = "Comment has been created!"
redirect_to post_path
end
@@ -369,7 +369,7 @@ This partial will be responsible for rendering just the comment text, for now. C
<%= comment_counter + 1 %>. <%= comment.text %>
</erb>
-The +comment_counter+ local variable is given to us by the +<%= render @post.comments %>+ call, as it will define this automatically and increment the counter as it iterates through each comment. It's used in this example to display a small number next to each comment when it's created.
+The +comment_counter+ local variable is given to us by the +&lt;%= render @post.comments %&gt;+ call, as it will define this automatically and increment the counter as it iterates through each comment. It's used in this example to display a small number next to each comment when it's created.
That completes the comment function of the blogging engine. Now it's time to use it within an application.
@@ -536,7 +536,7 @@ Finally, the author's name should be displayed on the post's page. Add this code
</p>
</erb>
-By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly:
+By outputting +@post.author+ using the +&lt;%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly:
<plain>
#<User:0x00000100ccb3b0>
@@ -563,7 +563,7 @@ end
By default, the engine's controllers inherit from <tt>Blorgh::ApplicationController</tt>. So, after making this change they will have access to the main applications +ApplicationController+ as though they were part of the main application.
-This change does require that the engine is run from a Rails application that has an +ApplicationController+.
+This change does require that the engine is run from a Rails application that has an +ApplicationController+.
h4. Configuring an engine
@@ -655,7 +655,125 @@ This tells the application that you still want to perform a +GET+ request to the
h3. Improving engine functionality
-This section looks at overriding or adding functionality to the views, controllers and models provided by an engine.
+This section explains how to add and/or override engine MVC functionality in the main Rails application.
+
+h4. Overriding Models and Controllers
+
+Engine model and controller classes can be extended by open classing them in the main Rails application (since model and controller classes are just Ruby classes that inherit Rails specific functionality). Open classing an Engine class redefines it for use in the main applicaiton. This is usually implemented by using the decorator pattern.
+
+For simple class modifications use Class#class_eval, and for complex class modifications, consider using ActiveSupport::Concern.
+
+h5. Implementing Decorator Pattern Using Class#class_eval
+
+**Adding** Post#time_since_created,
+
+<ruby>
+# MyApp/app/decorators/models/blorgh/post_decorator.rb
+
+Blorgh::Post.class_eval do
+ def time_since_created
+ Time.current - created_at
+ end
+end
+</ruby>
+
+<ruby>
+# Blorgh/app/models/post.rb
+
+class Post < ActiveRecord::Base
+ :has_many :comments
+end
+</ruby>
+
+
+**Overriding** Post#summary
+
+<ruby>
+# MyApp/app/decorators/models/blorgh/post_decorator.rb
+
+Blorgh::Post.class_eval do
+ def summary
+ "#{title} - #{truncate(text)}"
+ end
+end
+</ruby>
+
+<ruby>
+# Blorgh/app/models/post.rb
+
+class Post < ActiveRecord::Base
+ :has_many :comments
+ def summary
+ "#{title}"
+ end
+end
+</ruby>
+
+
+h5. Implementing Decorator Pattern Using ActiveSupport::Concern
+
+Using Class#class_eval is great for simple adjustments, but for more complex class modifications, you might want to consider using ActiveSupport::Concern. ["**ActiveSupport::Concern**":http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html] helps manage load order of interlinked dependencies at run time allowing you to significantly modularize your code.
+
+**Adding** Post#time_since_created<br/>
+**Overriding** Post#summary
+
+<ruby>
+# MyApp/app/models/blorgh/post.rb
+
+class Blorgh::Post < ActiveRecord::Base
+ include Blorgh::Concerns::Models::Post
+
+ def time_since_created
+ Time.current - created_at
+ end
+
+ def summary
+ "#{title} - #{truncate(text)}"
+ end
+end
+</ruby>
+
+<ruby>
+# Blorgh/app/models/post.rb
+
+class Post < ActiveRecord::Base
+ include Blorgh::Concerns::Models::Post
+end
+</ruby>
+
+<ruby>
+# Blorgh/lib/concerns/models/post
+
+module Blorgh::Concerns::Models::Post
+ extend ActiveSupport::Concern
+
+ # 'included do' causes the included code to be evaluated in the
+ # conext where it is included (post.rb), rather than be
+ # executed in the module's context (blorgh/concerns/models/post).
+ included do
+ attr_accessor :author_name
+ belongs_to :author, :class_name => "User"
+
+ before_save :set_author
+
+ private
+
+ def set_author
+ self.author = User.find_or_create_by_name(author_name)
+ end
+ end
+
+ def summary
+ "#{title}"
+ end
+
+ module ClassMethods
+ def some_class_method
+ 'some class method string'
+ end
+ end
+end
+</ruby>
h4. Overriding views
@@ -734,12 +852,14 @@ You can also specify these assets as dependencies of other assets using the Asse
*/
</plain>
+INFO. Remember that in order to use languages like Sass or CoffeeScript, you should add the relevant library to your engine's +.gemspec+.
+
h4. Separate Assets & Precompiling
There are some situations where your engine's assets not required by the host application. For example, say that you've created
an admin functionality that only exists for your engine. In this case, the host application doesn't need to require +admin.css+
or +admin.js+. Only the gem's admin layout needs these assets. It doesn't make sense for the host app to include +"blorg/admin.css"+ in it's stylesheets. In this situation, you should explicitly define these assets for precompilation.
-This tells sprockets to add you engine assets when +rake assets:precompile+ is ran.
+This tells sprockets to add you engine assets when +rake assets:precompile+ is ran.
You can define assets for precompilation in +engine.rb+
@@ -753,18 +873,40 @@ For more information, read the "Asset Pipeline guide":http://guides.rubyonrails.
h4. Other gem dependencies
-Gem dependencies inside an engine should be specified inside the +.gemspec+ file that's at the root of the engine. The reason for this is because the engine may be installed as a gem. If dependencies were to be specified inside the +Gemfile+, these would not be recognised by a traditional gem install and so they would not be installed, causing the engine to malfunction.
+Gem dependencies inside an engine should be specified inside the +.gemspec+ file
+that's at the root of the engine. The reason for this is because the engine may
+be installed as a gem. If dependencies were to be specified inside the +Gemfile+,
+these would not be recognised by a traditional gem install and so they would not
+be installed, causing the engine to malfunction.
-To specify a dependency that should be installed with the engine during a traditional +gem install+, specify it inside the +Gem::Specification+ block inside the +.gemspec+ file in the engine:
+To specify a dependency that should be installed with the engine during a
+traditional +gem install+, specify it inside the +Gem::Specification+ block
+inside the +.gemspec+ file in the engine:
<ruby>
s.add_dependency "moo"
</ruby>
-To specify a dependency that should only be installed as a development dependency of the application, specify it like this:
+To specify a dependency that should only be installed as a development
+dependency of the application, specify it like this:
<ruby>
s.add_development_dependency "moo"
</ruby>
-Both kinds of dependencies will be installed when +bundle install+ is run inside the application. The development dependencies for the gem will only be used when the tests for the engine are running.
+Both kinds of dependencies will be installed when +bundle install+ is run inside
+the application. The development dependencies for the gem will only be used when
+the tests for the engine are running.
+
+Note that if you want to immediately require dependencies when the engine is
+required, you should require them before engine's initialization. For example:
+
+<ruby>
+require 'other_engine/engine'
+require 'yet_another_engine/engine'
+
+module MyEngine
+ class Engine < ::Rails::Engine
+ end
+end
+</ruby> \ No newline at end of file
diff --git a/guides/source/form_helpers.textile b/guides/source/form_helpers.textile
index 1851aceff8..d507a04c1b 100644
--- a/guides/source/form_helpers.textile
+++ b/guides/source/form_helpers.textile
@@ -10,7 +10,7 @@ In this guide you will:
* Understand the date and time helpers Rails provides
* Learn what makes a file upload form different
* Learn some cases of building forms to external resources
-* Find out where to look for complex forms
+* Find out how to build complex forms
endprologue.
@@ -98,7 +98,7 @@ form_tag({:controller => "people", :action => "search"}, :method => "get", :clas
h4. Helpers for Generating Form Elements
-Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as +text_field_tag+ and +check_box_tag+), generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the +params+ hash in the controller with the value entered by the user for that field. For example, if the form contains +<%= text_field_tag(:query) %>+, then you would be able to get the value of this field in the controller with +params[:query]+.
+Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as +text_field_tag+ and +check_box_tag+), generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the +params+ hash in the controller with the value entered by the user for that field. For example, if the form contains +&lt;%= text_field_tag(:query) %&gt;+, then you would be able to get the value of this field in the controller with +params[:query]+.
When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in +params+. You can read more about them in "chapter 7 of this guide":#understanding-parameter-naming-conventions. For details on the precise usage of these helpers, please refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html.
@@ -654,7 +654,7 @@ If +f+ is an instance of FormBuilder then this will render the +form+ partial, s
h3. Understanding Parameter Naming Conventions
As you've seen in the previous sections, values from forms can be at the top level of the +params+ hash or nested in another hash. For example in a standard +create+
-action for a Person model, +params[:model]+ would usually be a hash of all the attributes for the person to create. The +params+ hash can also contain arrays, arrays of hashes and so on.
+action for a Person model, +params[:person]+ would usually be a hash of all the attributes for the person to create. The +params+ hash can also contain arrays, arrays of hashes and so on.
Fundamentally HTML forms don't know about any sort of structured data, all they generate is name–value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses.
@@ -816,11 +816,130 @@ Or if you don't want to render an +authenticity_token+ field:
h3. Building Complex Forms
-Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:
+Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary.
-* As of Rails 2.3, Rails includes "Nested Attributes":./2_3_release_notes.html#nested-attributes and "Nested Object Forms":./2_3_release_notes.html#nested-object-forms
-* Ryan Bates' series of Railscasts on "complex forms":http://railscasts.com/episodes/75
-* Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf
-* Eloy Duran's "complex-forms-examples":https://github.com/alloy/complex-form-examples/ application
-* Lance Ivy's "nested_assignment":https://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":https://github.com/cainlevy/complex-form-examples/tree/cainlevy
-* James Golick's "attribute_fu":https://github.com/jamesgolick/attribute_fu plugin
+h4. Configuring the Model
+
+Active Record provides model level support via the +accepts_nested_attributes_for+ method:
+
+<ruby>
+class Person < ActiveRecord::Base
+ has_many :addresses
+ accepts_nested_attributes_for :addresses
+
+ attr_accessible :name, :addresses_attributes
+end
+
+class Address < ActiveRecord::Base
+ belongs_to :person
+ attr_accessible :kind, :street
+end
+</ruby>
+
+This creates an +addresses_attributes=+ method on +Person+ that allows you to create, update and (optionally) destroy addresses. When using +attr_accessible+ or +attr_protected+ you must mark +addresses_attributes+ as accessible as well as the other attributes of +Person+ and +Address+ that should be mass assigned.
+
+h4. Building the Form
+
+The following form allows a user to create a +Person+ and its associated addresses.
+
+<erb>
+<%= form_for @person do |f| %>
+ Addresses:
+ <ul>
+ <%= f.fields_for :addresses do |addresses_form| %>
+ <li>
+ <%= addresses_form.label :kind %>
+ <%= addresses_form.text_field :kind %>
+
+ <%= addresses_form.label :street %>
+ <%= addresses_form.text_field :street %>
+ ...
+ </li>
+ <% end %>
+ </ul>
+<% end %>
+</erb>
+
+
+When an association accepts nested attributes +fields_for+ renders its block once for every element of the association. In particular, if a person has no addresses it renders nothing. A common pattern is for the controller to build one or more empty children so that at least one set of fields is shown to the user. The example below would result in 3 sets of address fields being rendered on the new person form.
+
+<ruby>
+def new
+ @person = Person.new
+ 3.times { @person.addresses.build}
+end
+</ruby>
+
++fields_for+ yields a form builder that names parameters in the format expected the accessor generated by +accepts_nested_attributes_for+. For example when creating a user with 2 addresses, the submitted parameters would look like
+
+<ruby>
+{
+ :person => {
+ :name => 'John Doe',
+ :addresses_attributes => {
+ '0' => {
+ :kind => 'Home',
+ :street => '221b Baker Street',
+ },
+ '1' => {
+ :kind => 'Office',
+ :street => '31 Spooner Street'
+ }
+ }
+ }
+}
+</ruby>
+
+The keys of the +:addresses_attributes+ hash are unimportant, they need merely be different for each address.
+
+If the associated object is already saved, +fields_for+ autogenerates a hidden input with the +id+ of the saved record. You can disable this by passing +:include_id => false+ to +fields_for+. You may wish to do this if the autogenerated input is placed in a location where an input tag is not valid HTML or when using an ORM where children do not have an id.
+
+h4. The Controller
+
+You do not need to write any specific controller code to use nested attributes. Create and update records as you would with a simple form.
+
+h4. Removing Objects
+
+You can allow users to delete associated objects by passing +allow_destroy => true+ to +accepts_nested_attributes_for+
+
+<ruby>
+class Person < ActiveRecord::Base
+ has_many :addresses
+ accepts_nested_attributes_for :addresses, :allow_destroy => true
+end
+</ruby>
+
+If the hash of attributes for an object contains the key +_destroy+ with a value of '1' or 'true' then the object will be destroyed. This form allows users to remove addresses:
+
+<erb>
+<%= form_for @person do |f| %>
+ Addresses:
+ <ul>
+ <%= f.fields_for :addresses do |addresses_form| %>
+ <li>
+ <%= check_box :_destroy%>
+ <%= addresses_form.label :kind %>
+ <%= addresses_form.text_field :kind %>
+ ...
+ </li>
+ <% end %>
+ </ul>
+<% end %>
+</erb>
+
+h4. Preventing Empty Records
+
+It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a +:reject_if+ proc to +accepts_nested_attributes_for+. This proc will be called with each hash of attributes submitted by the form. If the proc returns +false+ then Active Record will not build an associated object for that hash. The example below only tries to build an address if the +kind+ attribute is set.
+
+<ruby>
+class Person < ActiveRecord::Base
+ has_many :addresses
+ accepts_nested_attributes_for :addresses, :reject_if => lambda {|attributes| attributes['kind'].blank?}
+end
+</ruby>
+
+As a convenience you can instead pass the symbol +:all_blank+ which will create a proc that will reject records where all the attributes are blank excluding any value for +_destroy+.
+
+h4. Adding Fields on the Fly
+
+Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new child' button. Rails does not provide any builtin support for this. When generating new sets of fields you must ensure the the key of the associated array is unique - the current javascript date (milliseconds after the epoch) is a common choice. \ No newline at end of file
diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile
index 07419d11b4..226c3dce14 100644
--- a/guides/source/getting_started.textile
+++ b/guides/source/getting_started.textile
@@ -124,7 +124,7 @@ application. Most of the work in this tutorial will happen in the +app/+ folder,
|config.ru|Rack configuration for Rack based servers used to start the application.|
|db/|Contains your current database schema, as well as the database migrations.|
|doc/|In-depth documentation for your application.|
-|Gemfile<BR />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see "the Bundler website":http://gembundler.com |
+|Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see "the Bundler website":http://gembundler.com |
|lib/|Extended modules for your application.|
|log/|Application log files.|
|public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
@@ -373,7 +373,7 @@ Edit the +form_for+ line inside +app/views/posts/new.html.erb+ to look like this
In this example, a +Hash+ object is passed to the +:url+ option. What Rails will do with this is that it will point the form to the +create+ action of the current controller, the +PostsController+, and will send a +POST+ request to that route. For this to work, you will need to add a route to +config/routes.rb+, right underneath the one for "posts/new":
<ruby>
-post "posts/create"
+post "posts" => "posts#create"
</ruby>
By using the +post+ method rather than the +get+ method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web.
@@ -1064,13 +1064,13 @@ received an error before.
<shell>
# rake routes
- posts GET /posts(.:format) posts#index
- posts_new GET /posts/new(.:format) posts#new
-posts_create POST /posts/create(.:format) posts#create
- GET /posts/:id(.:format) posts#show
- GET /posts/:id/edit(.:format) posts#edit
- PUT /posts/:id(.:format) posts#update
- root / welcome#index
+ posts GET /posts(.:format) posts#index
+posts_new GET /posts/new(.:format) posts#new
+ POST /posts(.:format) posts#create
+ GET /posts/:id(.:format) posts#show
+ GET /posts/:id/edit(.:format) posts#edit
+ PUT /posts/:id(.:format) posts#update
+ root / welcome#index
</shell>
To fix this, open +config/routes.rb+ and modify the +get "posts/:id"+
@@ -1144,7 +1144,7 @@ together.
<td><%= post.text %></td>
<td><%= link_to 'Show', :action => :show, :id => post.id %></td>
<td><%= link_to 'Edit', :action => :edit, :id => post.id %></td>
- <td><%= link_to 'Destroy', { :action => :destroy, :id => post.id }, :method => :delete, :confirm => 'Are you sure?' %></td>
+ <td><%= link_to 'Destroy', { :action => :destroy, :id => post.id }, :method => :delete, :data => { :confirm => 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
@@ -1152,13 +1152,12 @@ together.
Here we're using +link_to+ in a different way. We wrap the
+:action+ and +:id+ attributes in a hash so that we can pass those two keys in
-first as one argument, and then the final two keys as another argument. The +:method+ and +:confirm+
+first as one argument, and then the final two keys as another argument. The +:method+ and +:'data-confirm'+
options are used as HTML5 attributes so that when the link is clicked,
-Rails will first show a confirm dialog to the user, and then submit the
-link with method +delete+. This is done via the JavaScript file +jquery_ujs+
-which is automatically included into your application's layout
-(+app/views/layouts/application.html.erb+) when you generated the application.
-Without this file, the confirmation dialog box wouldn't appear.
+Rails will first show a confirm dialog to the user, and then submit the link with method +delete+.
+This is done via the JavaScript file +jquery_ujs+ which is automatically included
+into your application's layout (+app/views/layouts/application.html.erb+) when you
+generated the application. Without this file, the confirmation dialog box wouldn't appear.
!images/getting_started/confirm_dialog.png(Confirm Dialog)!
@@ -1176,7 +1175,7 @@ declaring separate routes with the appropriate verbs into
<ruby>
get "posts" => "posts#index"
get "posts/new"
-post "posts/create"
+post "posts" => "posts#create"
get "posts/:id" => "posts#show", :as => :post
get "posts/:id/edit" => "posts#edit"
put "posts/:id" => "posts#update"
@@ -1248,6 +1247,7 @@ First, take a look at +comment.rb+:
<ruby>
class Comment < ActiveRecord::Base
belongs_to :post
+ attr_accessible :body, :commenter
end
</ruby>
@@ -1626,8 +1626,8 @@ So first, let's add the delete link in the
<p>
<%= link_to 'Destroy Comment', [comment.post, comment],
- :confirm => 'Are you sure?',
- :method => :delete %>
+ :method => :delete,
+ :data => { :confirm => 'Are you sure?' } %>
</p>
</erb>
diff --git a/guides/source/i18n.textile b/guides/source/i18n.textile
index ee7176a6c8..67863e590c 100644
--- a/guides/source/i18n.textile
+++ b/guides/source/i18n.textile
@@ -220,7 +220,7 @@ Every helper method dependent on +url_for+ (e.g. helpers for named routes like +
You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
-You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Dutch locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+path_prefix+":http://api.rubyonrails.org/classes/ActionController/Resources.html#M000354 option in this way:
+You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Dutch locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+scoping+":http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html option in this way:
<ruby>
# config/routes.rb
@@ -405,6 +405,10 @@ So that would give you:
TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use.
+h4. Inflection Rules For Other Locales
+
+Rails 4.0 allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In +config/initializers/inflections.rb+, you can define these rules for multiple locales. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit.
+
h4. Localized Views
Rails 2.3 introduces another convenient localization feature: localized views (templates). Let's say you have a _BooksController_ in your application. Your _index_ action renders content in +app/views/books/index.html.erb+ template. When you put a _localized variant_ of this template: *+index.es.html.erb+* in the same directory, Rails will render content in this template, when the locale is set to +:es+. When the locale is set to the default locale, the generic +index.html.erb+ view will be used. (Future Rails versions may well bring this _automagic_ localization to assets in +public+, etc.)
@@ -561,7 +565,7 @@ I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'
</ruby>
-If a translation uses +:default+ or +:scope+ as an interpolation variable, an I+18n::ReservedInterpolationKey+ exception is raised. If a translation expects an interpolation variable, but this has not been passed to +#translate+, an +I18n::MissingInterpolationArgument+ exception is raised.
+If a translation uses +:default+ or +:scope+ as an interpolation variable, an +I18n::ReservedInterpolationKey+ exception is raised. If a translation expects an interpolation variable, but this has not been passed to +#translate+, an +I18n::MissingInterpolationArgument+ exception is raised.
h4. Pluralization
diff --git a/guides/source/initialization.textile b/guides/source/initialization.textile
index 43d89eac4b..b23f31cb1a 100644
--- a/guides/source/initialization.textile
+++ b/guides/source/initialization.textile
@@ -17,7 +17,7 @@ NOTE: Paths in this guide are relative to Rails or a Rails application unless ot
TIP: If you want to follow along while browsing the Rails "source
code":https://github.com/rails/rails, we recommend that you use the +t+
-key binding to open the file finder inside github and find files
+key binding to open the file finder inside GitHub and find files
quickly.
h3. Launch!
@@ -359,7 +359,7 @@ set earlier) is required.
h4. +config/application+
When +require APP_PATH+ is executed, +config/application.rb+ is loaded.
-This is a file exists in your app and it's free for you to change based
+This file exists in your app and it's free for you to change based
on your needs.
h4. +Rails::Server#start+
@@ -453,7 +453,7 @@ end
The interesting part for a Rails app is the last line, +server.run+. Here we encounter the +wrapped_app+ method again, which this time
we're going to explore more (even though it was executed before, and
-thus memoized by now).
+thus memorized by now).
<ruby>
@wrapped_app ||= build_app app
@@ -540,12 +540,12 @@ end
</ruby>
This is where all the Rails frameworks are loaded and thus made
-available to the application. We wont go into detail of what happens
+available to the application. We won't go into detail of what happens
inside each of those frameworks, but you're encouraged to try and
explore them on your own.
For now, just keep in mind that common functionality like Rails engines,
-I18n and Rails configuration is all bein defined here.
+I18n and Rails configuration is all being defined here.
h4. Back to +config/environment.rb+
@@ -657,10 +657,10 @@ def self.run(app, options={})
end
</ruby>
-We wont dig into the server configuration itself, but this is
+We won't dig into the server configuration itself, but this is
the last piece of our journey in the Rails initialization process.
-This high level overview will help you understand when you code is
+This high level overview will help you understand when your code is
executed and how, and overall become a better Rails developer. If you
still want to know more, the Rails source code itself is probably the
best place to go next.
diff --git a/guides/source/kindle/KINDLE.md b/guides/source/kindle/KINDLE.md
index a7d9a4e4cf..08937e053e 100644
--- a/guides/source/kindle/KINDLE.md
+++ b/guides/source/kindle/KINDLE.md
@@ -9,16 +9,16 @@
## Resources
- * [StackOverflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format)
+ * [Stack Overflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format)
* Example Periodical [.ncx](https://gist.github.com/808c971ed087b839d462) and [.opf](https://gist.github.com/d6349aa8488eca2ee6d0)
- * [Kindle Publishing guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf)
+ * [Kindle Publishing Guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf)
* [KindleGen & Kindle Previewer](http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000234621)
## TODO
### Post release
- * Integrate generated Kindle document in to published HTML guides
+ * Integrate generated Kindle document into published HTML guides
* Tweak heading styles (most docs use h3/h4/h5, which end up being smaller than the text under it)
* Tweak table styles (smaller text? Many of the tables are unusable on a Kindle in portrait mode)
* Have the HTML/XML TOC 'drill down' into the TOCs of the individual guides
diff --git a/guides/source/kindle/welcome.html.erb b/guides/source/kindle/welcome.html.erb
index e30704c4e6..610a71570f 100644
--- a/guides/source/kindle/welcome.html.erb
+++ b/guides/source/kindle/welcome.html.erb
@@ -2,4 +2,4 @@
<h3>Kindle Edition</h3>
-The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome, please see the "Feedback" section at the end of each guide for instructions.
+The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome. Please see the "Feedback" section at the end of each guide for instructions.
diff --git a/guides/source/layouts_and_rendering.textile b/guides/source/layouts_and_rendering.textile
index 55bd521419..32ceecea18 100644
--- a/guides/source/layouts_and_rendering.textile
+++ b/guides/source/layouts_and_rendering.textile
@@ -78,7 +78,7 @@ If we want to display the properties of all the books in our view, we can do so
<td><%= book.content %></td>
<td><%= link_to "Show", book %></td>
<td><%= link_to "Edit", edit_book_path(book) %></td>
- <td><%= link_to "Remove", book, :confirm => "Are you sure?", :method => :delete %></td>
+ <td><%= link_to "Remove", book, :method => :delete, :data => { :confirm => "Are you sure?" } %></td>
</tr>
<% end %>
</table>
diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile
index 342b5a4d57..a7de21b754 100644
--- a/guides/source/migrations.textile
+++ b/guides/source/migrations.textile
@@ -14,7 +14,7 @@ Migrations also allow you to describe these transformations using Ruby. The
great thing about this is that (like most of Active Record's functionality) it
is database independent: you don't need to worry about the precise syntax of
+CREATE TABLE+ any more than you worry about variations on +SELECT *+ (you can
-drop down to raw SQL for database specific features). For example you could use
+drop down to raw SQL for database specific features). For example, you could use
SQLite3 in development, but MySQL in production.
In this guide, you'll learn all about migrations including:
@@ -111,6 +111,7 @@ Active Record provides methods that perform common data definition tasks in a
database independent way (you'll read about them in detail later):
* +add_column+
+* +add_reference+
* +add_index+
* +change_column+
* +change_table+
@@ -120,11 +121,12 @@ database independent way (you'll read about them in detail later):
* +remove_column+
* +remove_index+
* +rename_column+
+* +remove_reference+
-If you need to perform tasks specific to your database (for example create a
+If you need to perform tasks specific to your database (e.g., create a
"foreign key":#active-record-and-referential-integrity constraint) then the
+execute+ method allows you to execute arbitrary SQL. A migration is just a
-regular Ruby class so you're not limited to these functions. For example after
+regular Ruby class so you're not limited to these functions. For example, after
adding a column you could write code to set the value of that column for
existing records (if necessary using your models).
@@ -163,7 +165,7 @@ config.active_record.timestamped_migrations = false
The combination of timestamps and recording which migrations have been run
allows Rails to handle common situations that occur with multiple developers.
-For example Alice adds migrations +20080906120000+ and +20080906123000+ and Bob
+For example, Alice adds migrations +20080906120000+ and +20080906123000+ and Bob
adds +20080906124500+ and runs it. Alice finishes her changes and checks in her
migrations and Bob pulls down the latest changes. When Bob runs +rake db:migrate+,
Rails knows that it has not run Alice's two migrations so it executes the +up+ method for each migration.
@@ -180,7 +182,7 @@ migration again: Rails thinks it has already run the migration and so will do
nothing when you run +rake db:migrate+. You must rollback the migration (for
example with +rake db:rollback+), edit your migration and then run +rake db:migrate+ to run the corrected version.
-In general editing existing migrations is not a good idea: you will be creating
+In general, editing existing migrations is not a good idea. You will be creating
extra work for yourself and your co-workers and cause major headaches if the
existing version of the migration has already been run on production machines.
Instead, you should write a new migration that performs the changes you require.
@@ -207,8 +209,7 @@ Active Record supports the following database column types:
These will be mapped onto an appropriate underlying database type. For example,
with MySQL the type +:string+ is mapped to +VARCHAR(255)+. You can create
-columns of types not supported by Active Record when using the non-sexy syntax,
-for example
+columns of types not supported by Active Record when using the non-sexy syntax such as
<ruby>
create_table :products do |t|
@@ -253,7 +254,7 @@ by Active Record).
h4. Creating a Standalone Migration
-If you are creating migrations for other purposes (for example to add a column
+If you are creating migrations for other purposes (e.g., to add a column
to an existing table) then you can also use the migration generator:
<shell>
@@ -307,7 +308,7 @@ class RemovePartNumberFromProducts < ActiveRecord::Migration
end
</ruby>
-You are not limited to one magically generated column, for example
+You are not limited to one magically generated column. For example
<shell>
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
@@ -332,6 +333,51 @@ NOTE: The generated migration file for destructive migrations will still be
old-style using the +up+ and +down+ methods. This is because Rails needs to know
the original data types defined when you made the original changes.
+Also, the generator accepts column type as +references+(also available as +belongs_to+). For instance
+
+<shell>
+$ rails generate migration AddUserRefToProducts user:references
+</shell>
+
+generates
+
+<ruby>
+class AddUserRefToProducts < ActiveRecord::Migration
+ def change
+ add_reference :products, :user, :index => true
+ end
+end
+</ruby>
+
+This migration will create a user_id column and appropriate index.
+
+h4. Supported type modifiers
+
+You can also specify some options just after the field type between curly braces. You can use the
+following modifiers:
+
+* +limit+ Sets the maximum size of the +string/text/binary/integer+ fields
+* +precision+ Defines the precision for the +decimal+ fields
+* +scale+ Defines the scale for the +decimal+ fields
+* +polymorphic+ Adds a +type+ column for +belongs_to+ associations
+
+For instance, running
+
+<shell>
+$ rails generate migration AddDetailsToProducts price:decimal{5,2} supplier:references{polymorphic}
+</shell>
+
+will produce a migration that looks like this
+
+<ruby>
+class AddDetailsToProducts < ActiveRecord::Migration
+ def change
+ add_column :products, :price, :precision => 5, :scale => 2
+ add_reference :products, :user, :polymorphic => true, :index => true
+ end
+end
+</ruby>
+
h3. Writing a Migration
Once you have created your migration using one of the generators it's time to
@@ -494,8 +540,8 @@ support":#active-record-and-referential-integrity.
If the helpers provided by Active Record aren't enough you can use the +execute+
method to execute arbitrary SQL.
-For more details and examples of individual methods, check the API documentation,
-in particular the documentation for
+For more details and examples of individual methods, check the API documentation.
+In particular the documentation for
"<tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html
(which provides the methods available in the +up+ and +down+ methods),
"<tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html
@@ -597,7 +643,7 @@ down to, but not including, 20080906120000.
h4. Rolling Back
-A common task is to rollback the last migration, for example if you made a
+A common task is to rollback the last migration. For example, if you made a
mistake in it and wish to correct it. Rather than tracking down the version
number associated with the previous migration you can run
@@ -792,7 +838,7 @@ An error has occurred, this and all later migrations canceled:
undefined method `fuzz' for #<Product:0x000001049b14a0>
</plain>
-A fix for this is to create a local model within the migration. This keeps rails
+A fix for this is to create a local model within the migration. This keeps Rails
from running the validations, so that the migrations run to completion.
When using a faux model, it's a good idea to call
diff --git a/guides/source/performance_testing.textile b/guides/source/performance_testing.textile
index 982fd1b070..6c5676c346 100644
--- a/guides/source/performance_testing.textile
+++ b/guides/source/performance_testing.textile
@@ -1,40 +1,55 @@
h2. Performance Testing Rails Applications
-This guide covers the various ways of performance testing a Ruby on Rails application. By referring to this guide, you will be able to:
-
-* Understand the various types of benchmarking and profiling metrics
-* Generate performance and benchmarking tests
-* Install and use a GC-patched Ruby binary to measure memory usage and object allocation
-* Understand the benchmarking information provided by Rails inside the log files
-* Learn about various tools facilitating benchmarking and profiling
-
-Performance testing is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a pleasant browsing experience for end users and cutting the cost of unnecessary hardware is important for any non-trivial web application.
+This guide covers the various ways of performance testing a Ruby on Rails
+application. By referring to this guide, you will be able to:
+
+* Understand the various types of benchmarking and profiling metrics.
+* Generate performance and benchmarking tests.
+* Install and use a GC-patched Ruby binary to measure memory usage and object
+ allocation.
+* Understand the benchmarking information provided by Rails inside the log files.
+* Learn about various tools facilitating benchmarking and profiling.
+
+Performance testing is an integral part of the development cycle. It is very
+important that you don't make your end users wait for too long before the page
+is completely loaded. Ensuring a pleasant browsing experience for end users and
+cutting the cost of unnecessary hardware is important for any non-trivial web
+application.
endprologue.
h3. Performance Test Cases
-Rails performance tests are a special type of integration tests, designed for benchmarking and profiling the test code. With performance tests, you can determine where your application's memory or speed problems are coming from, and get a more in-depth picture of those problems.
+Rails performance tests are a special type of integration tests, designed for
+benchmarking and profiling the test code. With performance tests, you can
+determine where your application's memory or speed problems are coming from,
+and get a more in-depth picture of those problems.
-In a freshly generated Rails application, +test/performance/browsing_test.rb+ contains an example of a performance test:
+In a freshly generated Rails application, +test/performance/browsing_test.rb+
+contains an example of a performance test:
<ruby>
require 'test_helper'
require 'rails/performance_test_help'
-# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionDispatch::PerformanceTest
- def test_homepage
+ # Refer to the documentation for all available options
+ # self.profile_options = { runs: 5, metrics: [:wall_time, :memory],
+ # output: 'tmp/performance', formats: [:flat] }
+
+ test "homepage" do
get '/'
end
end
</ruby>
-This example is a simple performance test case for profiling a GET request to the application's homepage.
+This example is a simple performance test case for profiling a GET request to
+the application's homepage.
h4. Generating Performance Tests
-Rails provides a generator called +performance_test+ for creating new performance tests:
+Rails provides a generator called +performance_test+ for creating new
+performance tests:
<shell>
$ rails generate performance_test homepage
@@ -47,8 +62,11 @@ require 'test_helper'
require 'rails/performance_test_help'
class HomepageTest < ActionDispatch::PerformanceTest
- # Replace this with your real tests.
- def test_homepage
+ # Refer to the documentation for all available options
+ # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory],
+ # :output => 'tmp/performance', :formats => [:flat] }
+
+ test "homepage" do
get '/'
end
end
@@ -60,7 +78,7 @@ Let's assume your application has the following controller and model:
<ruby>
# routes.rb
-root :to => 'home#index'
+root to: 'home#dashboard'
resources :posts
# home_controller.rb
@@ -97,9 +115,11 @@ end
h5. Controller Example
-Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them.
+Because performance tests are a special kind of integration test, you can use
+the +get+ and +post+ methods in them.
-Here's the performance test for +HomeController#dashboard+ and +PostsController#create+:
+Here's the performance test for +HomeController#dashboard+ and
++PostsController#create+:
<ruby>
require 'test_helper'
@@ -111,21 +131,24 @@ class PostPerformanceTest < ActionDispatch::PerformanceTest
login_as(:lifo)
end
- def test_homepage
+ test "homepage" do
get '/dashboard'
end
- def test_creating_new_post
- post '/posts', :post => { :body => 'lifo is fooling you' }
+ test "creating new post" do
+ post '/posts', post: { body: 'lifo is fooling you' }
end
end
</ruby>
-You can find more details about the +get+ and +post+ methods in the "Testing Rails Applications":testing.html guide.
+You can find more details about the +get+ and +post+ methods in the
+"Testing Rails Applications":testing.html guide.
h5. Model Example
-Even though the performance tests are integration tests and hence closer to the request/response cycle by nature, you can still performance test pure model code.
+Even though the performance tests are integration tests and hence closer to
+the request/response cycle by nature, you can still performance test pure model
+code.
Performance test for +Post+ model:
@@ -134,11 +157,11 @@ require 'test_helper'
require 'rails/performance_test_help'
class PostModelTest < ActionDispatch::PerformanceTest
- def test_creation
- Post.create :body => 'still fooling you', :cost => '100'
+ test "creation" do
+ Post.create body: 'still fooling you', cost: '100'
end
- def test_slow_method
+ test "slow method" do
# Using posts(:awesome) fixture
posts(:awesome).slow_method
end
@@ -151,7 +174,8 @@ Performance tests can be run in two modes: Benchmarking and Profiling.
h5. Benchmarking
-Benchmarking makes it easy to quickly gather a few metrics about each test run. By default, each test case is run *4 times* in benchmarking mode.
+Benchmarking makes it easy to quickly gather a few metrics about each test run.
+By default, each test case is run *4 times* in benchmarking mode.
To run performance tests in benchmarking mode:
@@ -161,7 +185,10 @@ $ rake test:benchmark
h5. Profiling
-Profiling allows you to make an in-depth analysis of each of your tests by using an external profiler. Depending on your Ruby interpreter, this profiler can be native (Rubinius, JRuby) or not (MRI, which uses RubyProf). By default, each test case is run *once* in profiling mode.
+Profiling allows you to make an in-depth analysis of each of your tests by using
+an external profiler. Depending on your Ruby interpreter, this profiler can be
+native (Rubinius, JRuby) or not (MRI, which uses RubyProf). By default, each
+test case is run *once* in profiling mode.
To run performance tests in profiling mode:
@@ -171,23 +198,33 @@ $ rake test:profile
h4. Metrics
-Benchmarking and profiling run performance tests and give you multiple metrics. The availability of each metric is determined by the interpreter being used—none of them support all metrics—and by the mode in use. A brief description of each metric and their availability across interpreters/modes is given below.
+Benchmarking and profiling run performance tests and give you multiple metrics.
+The availability of each metric is determined by the interpreter being used—none
+of them support all metrics—and by the mode in use. A brief description of each
+metric and their availability across interpreters/modes is given below.
h5. Wall Time
-Wall time measures the real world time elapsed during the test run. It is affected by any other processes concurrently running on the system.
+Wall time measures the real world time elapsed during the test run. It is
+affected by any other processes concurrently running on the system.
h5. Process Time
-Process time measures the time taken by the process. It is unaffected by any other processes running concurrently on the same system. Hence, process time is likely to be constant for any given performance test, irrespective of the machine load.
+Process time measures the time taken by the process. It is unaffected by any
+other processes running concurrently on the same system. Hence, process time
+is likely to be constant for any given performance test, irrespective of the
+machine load.
h5. CPU Time
-Similar to process time, but leverages the more accurate CPU clock counter available on the Pentium and PowerPC platforms.
+Similar to process time, but leverages the more accurate CPU clock counter
+available on the Pentium and PowerPC platforms.
h5. User Time
-User time measures the amount of time the CPU spent in user-mode, i.e. within the process. This is not affected by other processes and by the time it possibly spends blocked.
+User time measures the amount of time the CPU spent in user-mode, i.e. within
+the process. This is not affected by other processes and by the time it possibly
+spends blocked.
h5. Memory
@@ -223,11 +260,13 @@ h6(#profiling_1). Profiling
|_.Rubinius | yes | no | no | no | no | no | no | no |
|_.JRuby | yes | no | no | no | no | no | no | no |
-NOTE: To profile under JRuby you'll need to run +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api"+ *before* the performance tests.
+NOTE: To profile under JRuby you'll need to run +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api"+
+*before* the performance tests.
h4. Understanding the Output
-Performance tests generate different outputs inside +tmp/performance+ directory depending on their mode and metric.
+Performance tests generate different outputs inside +tmp/performance+ directory
+depending on their mode and metric.
h5(#output-benchmarking). Benchmarking
@@ -248,7 +287,9 @@ BrowsingTest#test_homepage (31 ms warmup)
h6. CSV Files
-Performance test results are also appended to +.csv+ files inside +tmp/performance+. For example, running the default +BrowsingTest#test_homepage+ will generate following five files:
+Performance test results are also appended to +.csv+ files inside +tmp/performance+.
+For example, running the default +BrowsingTest#test_homepage+ will generate
+following five files:
* BrowsingTest#test_homepage_gc_runs.csv
* BrowsingTest#test_homepage_gc_time.csv
@@ -256,7 +297,9 @@ Performance test results are also appended to +.csv+ files inside +tmp/performan
* BrowsingTest#test_homepage_objects.csv
* BrowsingTest#test_homepage_wall_time.csv
-As the results are appended to these files each time the performance tests are run in benchmarking mode, you can collect data over a period of time. This can be very helpful in analyzing the effects of code changes.
+As the results are appended to these files each time the performance tests are
+run in benchmarking mode, you can collect data over a period of time. This can
+be very helpful in analyzing the effects of code changes.
Sample output of +BrowsingTest#test_homepage_wall_time.csv+:
@@ -276,7 +319,10 @@ measurement,created_at,app,rails,ruby,platform
h5(#output-profiling). Profiling
-In profiling mode, performance tests can generate multiple types of outputs. The command line output is always presented but support for the others is dependent on the interpreter in use. A brief description of each type and their availability across interpreters is given below.
+In profiling mode, performance tests can generate multiple types of outputs.
+The command line output is always presented but support for the others is
+dependent on the interpreter in use. A brief description of each type and
+their availability across interpreters is given below.
h6. Command Line
@@ -291,15 +337,18 @@ BrowsingTest#test_homepage (58 ms warmup)
h6. Flat
-Flat output shows the metric—time, memory, etc—measure in each method. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html.
+Flat output shows the metric—time, memory, etc—measure in each method.
+"Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html.
h6. Graph
-Graph output shows the metric measure in each method, which methods call it and which methods it calls. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html.
+Graph output shows the metric measure in each method, which methods call it and
+which methods it calls. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html.
h6. Tree
-Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html and similar tools.
+Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html
+and similar tools.
h6. Output Availability
@@ -311,24 +360,24 @@ h6. Output Availability
h4. Tuning Test Runs
-Test runs can be tuned by setting the +profile_options+ class variable on your test class.
+Test runs can be tuned by setting the +profile_options+ class variable on your
+test class.
<ruby>
require 'test_helper'
require 'rails/performance_test_help'
-# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionDispatch::PerformanceTest
- self.profile_options = { :runs => 5,
- :metrics => [:wall_time, :memory] }
+ self.profile_options = { runs: 5, metrics: [:wall_time, :memory] }
- def test_homepage
+ test "homepage"
get '/'
end
end
</ruby>
-In this example, the test would run 5 times and measure wall time and memory. There are a few configurable options:
+In this example, the test would run 5 times and measure wall time and memory.
+There are a few configurable options:
|_.Option |_.Description|_.Default|_.Mode|
|+:runs+ |Number of runs.|Benchmarking: 4, Profiling: 1|Both|
@@ -346,11 +395,13 @@ Metrics and formats have different defaults depending on the interpreter in use.
|/2.JRuby |Benchmarking|+[:wall_time, :user_time, :memory, :gc_runs, :gc_time]+|N/A|
|Profiling |+[:wall_time]+|+[:flat, :graph]+|
-As you've probably noticed by now, metrics and formats are specified using a symbol array with each name "underscored.":http://api.rubyonrails.org/classes/String.html#method-i-underscore
+As you've probably noticed by now, metrics and formats are specified using a
+symbol array with each name "underscored.":http://api.rubyonrails.org/classes/String.html#method-i-underscore
h4. Performance Test Environment
-Performance tests are run in the +test+ environment. But running performance tests will set the following configuration parameters:
+Performance tests are run in the +test+ environment. But running performance
+tests will set the following configuration parameters:
<shell>
ActionController::Base.perform_caching = true
@@ -358,11 +409,13 @@ ActiveSupport::Dependencies.mechanism = :require
Rails.logger.level = ActiveSupport::BufferedLogger::INFO
</shell>
-As +ActionController::Base.perform_caching+ is set to +true+, performance tests will behave much as they do in the +production+ environment.
+As +ActionController::Base.perform_caching+ is set to +true+, performance tests
+will behave much as they do in the +production+ environment.
h4. Installing GC-Patched MRI
-To get the best from Rails' performance tests under MRI, you'll need to build a special Ruby binary with some super powers.
+To get the best from Rails' performance tests under MRI, you'll need to build
+a special Ruby binary with some super powers.
The recommended patches for each MRI version are:
@@ -371,13 +424,18 @@ The recommended patches for each MRI version are:
|1.8.7|ruby187gc|
|1.9.2 and above|gcdata|
-All of these can be found on "RVM's _patches_ directory":https://github.com/wayneeseguin/rvm/tree/master/patches/ruby under each specific interpreter version.
+All of these can be found on "RVM's _patches_ directory":https://github.com/wayneeseguin/rvm/tree/master/patches/ruby
+under each specific interpreter version.
-Concerning the installation itself, you can either do this easily by using "RVM":http://rvm.beginrescueend.com or you can build everything from source, which is a little bit harder.
+Concerning the installation itself, you can either do this easily by using
+"RVM":http://rvm.beginrescueend.com or you can build everything from source,
+which is a little bit harder.
h5. Install Using RVM
-The process of installing a patched Ruby interpreter is very easy if you let RVM do the hard work. All of the following RVM commands will provide you with a patched Ruby interpreter:
+The process of installing a patched Ruby interpreter is very easy if you let RVM
+do the hard work. All of the following RVM commands will provide you with a
+patched Ruby interpreter:
<shell>
$ rvm install 1.9.2-p180 --patch gcdata
@@ -385,7 +443,8 @@ $ rvm install 1.8.7 --patch ruby187gc
$ rvm install 1.9.2-p180 --patch ~/Downloads/downloaded_gcdata_patch.patch
</shell>
-You can even keep your regular interpreter by assigning a name to the patched one:
+You can even keep your regular interpreter by assigning a name to the patched
+one:
<shell>
$ rvm install 1.9.2-p180 --patch gcdata --name gcdata
@@ -397,7 +456,9 @@ And it's done! You have installed a patched Ruby interpreter.
h5. Install From Source
-This process is a bit more complicated, but straightforward nonetheless. If you've never compiled a Ruby binary before, follow these steps to build a Ruby binary inside your home directory.
+This process is a bit more complicated, but straightforward nonetheless. If
+you've never compiled a Ruby binary before, follow these steps to build a
+Ruby binary inside your home directory.
h6. Download and Extract
@@ -417,7 +478,9 @@ $ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.8.7/ruby187g
h6. Configure and Install
-The following will install Ruby in your home directory's +/rubygc+ directory. Make sure to replace +&lt;homedir&gt;+ with a full patch to your actual home directory.
+The following will install Ruby in your home directory's +/rubygc+ directory.
+Make sure to replace +&lt;homedir&gt;+ with a full patch to your actual home
+directory.
<shell>
$ ./configure --prefix=/<homedir>/rubygc
@@ -438,23 +501,22 @@ alias gcrails='~/rubygc/bin/rails'
Don't forget to use your aliases from now on.
-h6. Install RubyGems (1.8 only!)
-
-Download "RubyGems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above.
-
h4. Using Ruby-Prof on MRI and REE
-Add Ruby-Prof to your applications' Gemfile if you want to benchmark/profile under MRI or REE:
+Add Ruby-Prof to your applications' Gemfile if you want to benchmark/profile
+under MRI or REE:
<ruby>
-gem 'ruby-prof', :git => 'git://github.com/wycats/ruby-prof.git'
+gem 'ruby-prof', git: 'git://github.com/wycats/ruby-prof.git'
</ruby>
Now run +bundle install+ and you're ready to go.
h3. Command Line Tools
-Writing performance test cases could be an overkill when you are looking for one time tests. Rails ships with two command line tools that enable quick and dirty performance testing:
+Writing performance test cases could be an overkill when you are looking for one
+time tests. Rails ships with two command line tools that enable quick and dirty
+performance testing:
h4. +benchmarker+
@@ -498,11 +560,14 @@ Example:
$ rails profiler 'Item.all' 'CouchItem.all' --runs 2 --metrics process_time --formats flat
</shell>
-NOTE: Metrics and formats vary from interpreter to interpreter. Pass +--help+ to each tool to see the defaults for your interpreter.
+NOTE: Metrics and formats vary from interpreter to interpreter. Pass +--help+ to
+each tool to see the defaults for your interpreter.
h3. Helper Methods
-Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a given piece of code. The method is called +benchmark()+ in all the three components.
+Rails provides various helper methods inside Active Record, Action Controller
+and Action View to measure the time taken by a given piece of code. The method
+is called +benchmark()+ in all the three components.
h4. Model
@@ -514,17 +579,19 @@ Project.benchmark("Creating project") do
end
</ruby>
-This benchmarks the code enclosed in the +Project.benchmark("Creating project") do...end+ block and prints the result to the log file:
+This benchmarks the code enclosed in the +Project.benchmark("Creating project") do...end+
+block and prints the result to the log file:
<ruby>
Creating project (185.3ms)
</ruby>
-Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001336 for additional options to +benchmark()+
+Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html#method-i-benchmark
+for additional options to +benchmark()+.
h4. Controller
-Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html
+Similarly, you could use this helper method inside "controllers.":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html
<ruby>
def process_projects
@@ -535,7 +602,7 @@ def process_projects
end
</ruby>
-NOTE: +benchmark+ is a class method inside controllers
+NOTE: +benchmark+ is a class method inside controllers.
h4. View
@@ -549,7 +616,8 @@ And in "views":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.ht
h3. Request Logging
-Rails log files contain very useful information about the time taken to serve each request. Here's a typical log file entry:
+Rails log files contain very useful information about the time taken to serve
+each request. Here's a typical log file entry:
<shell>
Processing ItemsController#index (for 127.0.0.1 at 2009-01-08 03:06:39) [GET]
@@ -564,9 +632,14 @@ For this section, we're only interested in the last line:
Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items]
</shell>
-This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measure the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
+This data is fairly straightforward to understand. Rails uses millisecond(ms) as
+the metric to measure the time taken. The complete request spent 5 ms inside
+Rails, out of which 2 ms were spent rendering views and none was spent
+communication with the database. It's safe to assume that the remaining 3 ms
+were spent inside the controller.
-Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second explaining the importance of using milliseconds as the metric.
+Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second
+explaining the importance of using milliseconds as the metric.
h3. Useful Links
@@ -576,6 +649,7 @@ h4. Rails Plugins and Gems
* "Palmist":http://www.flyingmachinestudios.com/programming/announcing-palmist
* "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master
* "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master
+* "MiniProfiler":http://www.miniprofiler.com
h4. Generic Tools
@@ -587,11 +661,12 @@ h4. Generic Tools
h4. Tutorials and Documentation
* "ruby-prof API Documentation":http://ruby-prof.rubyforge.org
-* "Request Profiling Railscast":http://railscasts.com/episodes/98-request-profiling - Outdated, but useful for understanding call graphs
+* "Request Profiling Railscast":http://railscasts.com/episodes/98-request-profiling - Outdated, but useful for understanding call graphs.
h3. Commercial Products
-Rails has been lucky to have a few companies dedicated to Rails-specific performance tools. A couple of those are:
+Rails has been lucky to have a few companies dedicated to Rails-specific
+performance tools. A couple of those are:
* "New Relic":http://www.newrelic.com
* "Scout":http://scoutapp.com
diff --git a/guides/source/plugins.textile b/guides/source/plugins.textile
index 95e38db483..50ea6b166a 100644
--- a/guides/source/plugins.textile
+++ b/guides/source/plugins.textile
@@ -13,7 +13,7 @@ After reading this guide you should be familiar with:
This guide describes how to build a test-driven plugin that will:
-* Extend core ruby classes like Hash and String
+* Extend core Ruby classes like Hash and String
* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
* Give you information about where to put generators in your plugin.
@@ -28,7 +28,7 @@ h3. Setup
_"vendored plugins"_ were available in previous versions of Rails, but they are deprecated in
Rails 3.2, and will not be available in the future.
-Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared accross
+Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared across
different rails applications using RubyGems and Bundler if desired.
h4. Generate a gemified plugin.
@@ -174,11 +174,11 @@ require 'test_helper'
class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal :last_squawk, Hickwall.yaffle_text_field
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
- assert_equal :last_tweet, Wickwall.yaffle_text_field
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
end
end
@@ -392,7 +392,7 @@ the creation of generators can be found in the "Generators Guide":generators.htm
h3. Publishing your Gem
Gem plugins currently in development can easily be shared from any Git repository. To share the Yaffle gem with others, simply
-commit the code to a Git repository (like Github) and add a line to the Gemfile of the application in question:
+commit the code to a Git repository (like GitHub) and add a line to the Gemfile of the application in question:
<ruby>
gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
@@ -401,7 +401,7 @@ gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
After running +bundle install+, your gem functionality will be available to the application.
When the gem is ready to be shared as a formal release, it can be published to "RubyGems":http://www.rubygems.org.
-For more information about publishing gems to RubyGems, see: "http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html
+For more information about publishing gems to RubyGems, see: "Creating and Publishing Your First Ruby Gem":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html
h3. RDoc Documentation
@@ -414,7 +414,7 @@ The first step is to update the README file with detailed information about how
* How to add the functionality to the app (several examples of common use cases)
* Warnings, gotchas or tips that might help users and save them time
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not included in the public api.
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not included in the public API.
Once your comments are good to go, navigate to your plugin directory and run:
@@ -425,6 +425,6 @@ $ rake rdoc
h4. References
* "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md
-* "Using Gemspecs As Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/
+* "Using .gemspecs as Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/
* "Gemspec Reference":http://docs.rubygems.org/read/chapter/20
-* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
+* "GemPlugins: A Brief Introduction to the Future of Rails Plugins":http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
diff --git a/guides/source/rails_application_templates.textile b/guides/source/rails_application_templates.textile
index f50ced3307..2fa40bc4cc 100644
--- a/guides/source/rails_application_templates.textile
+++ b/guides/source/rails_application_templates.textile
@@ -38,7 +38,7 @@ rake("db:migrate")
git :init
git :add => "."
-git :commit => "-a -m 'Initial commit'"
+git :commit => %Q{ -m 'Initial commit' }
</ruby>
The following sections outlines the primary methods provided by the API:
diff --git a/guides/source/routing.textile b/guides/source/routing.textile
index cffbf9bec4..bed7d03e06 100644
--- a/guides/source/routing.textile
+++ b/guides/source/routing.textile
@@ -273,6 +273,36 @@ The corresponding route helper would be +publisher_magazine_photo_url+, requirin
TIP: _Resources should never be nested more than 1 level deep._
+h4. Routing concerns
+
+Routing Concerns allows you to declare common routes that can be reused inside others resources and routes.
+
+<ruby>
+concern :commentable do
+ resources :comments
+end
+
+concern :image_attachable do
+ resources :images, only: :index
+end
+</ruby>
+
+These concerns can be used in resources to avoid code duplication and share behavior across routes.
+
+<ruby>
+resources :messages, concerns: :commentable
+
+resources :posts, concerns: [:commentable, :image_attachable]
+</ruby>
+
+Also you can use them in any place that you want inside the routes, for example in a scope or namespace call:
+
+<ruby>
+namespace :posts do
+ concerns :commentable
+end
+</ruby>
+
h4. Creating Paths and URLs From Objects
In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
diff --git a/guides/source/security.textile b/guides/source/security.textile
index 626d6fa508..4c6c78a353 100644
--- a/guides/source/security.textile
+++ b/guides/source/security.textile
@@ -81,9 +81,7 @@ This will also be a good idea, if you modify the structure of an object and old
h4. Session Storage
-NOTE: _Rails provides several storage mechanisms for the session hashes. The most important are +ActiveRecord::SessionStore+ and +ActionDispatch::Session::CookieStore+._
-
-There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecord::SessionStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecord::SessionStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
+NOTE: _Rails provides several storage mechanisms for the session hashes. The most important is +ActionDispatch::Session::CookieStore+._
Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
@@ -608,7 +606,7 @@ This URL passes the filter because the regular expression matches – the second
link_to "Homepage", @user.homepage
</ruby>
-The link looks innocent to visitors, but when it's clicked, it will execute the javascript function "exploit_code" or any other javascript the attacker provides.
+The link looks innocent to visitors, but when it's clicked, it will execute the JavaScript function "exploit_code" or any other JavaScript the attacker provides.
To fix the regular expression, \A and \z should be used instead of ^ and $, like so:
@@ -851,7 +849,7 @@ Network traffic is mostly based on the limited Western alphabet, so new characte
&amp;#108;&amp;#101;&amp;#114;&amp;#116;&amp;#40;&amp;#39;&amp;#88;&amp;#83;&amp;#83;&amp;#39;&amp;#41;>
</html>
-This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":http://www.businessinfo.co.uk/labs/hackvertor/hackvertor.php. Rails' sanitize() method does a good job to fend off encoding attacks.
+This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":https://hackvertor.co.uk/public. Rails' sanitize() method does a good job to fend off encoding attacks.
h5. Examples from the Underground
@@ -1021,6 +1019,47 @@ Content-Type: text/html
Under certain circumstances this would present the malicious HTML to the victim. However, this only seems to work with Keep-Alive connections (and many browsers are using one-time connections). But you can't rely on this. _(highlight)In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks._
+h3. Default Headers
+
+Every HTTP response from your Rails application receives the following default security headers.
+
+<ruby>
+config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff'
+}
+</ruby>
+
+You can configure default headers in <ruby>config/application.rb</ruby>.
+
+<ruby>
+config.action_dispatch.default_headers = {
+ 'Header-Name' => 'Header-Value',
+ 'X-Frame-Options' => 'DENY'
+}
+</ruby>
+
+Or you can remove them.
+
+<ruby>
+config.action_dispatch.default_headers.clear
+</ruby>
+
+Here is the list of common headers:
+* X-Frame-Options
+_'SAMEORIGIN' in Rails by default_ - allow framing on same domain. Set it to 'DENY' to deny framing at all or 'ALLOWALL' if you want to allow framing for all website.
+* X-XSS-Protection
+_'1; mode=block' in Rails by default_ - use XSS Auditor and block page if XSS attack is detected. Set it to '0;' if you want to switch XSS Auditor off(useful if response contents scripts from request parameters)
+* X-Content-Type-Options
+_'nosniff' in Rails by default_ - stops the browser from guessing the MIME type of a file.
+* X-Content-Security-Policy
+"A powerful mechanism for controlling which sites certain content types can be loaded from":http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html
+* Access-Control-Allow-Origin
+Used to control which sites are allowed to bypass same origin policies and send cross-origin requests.
+* Strict-Transport-Security
+"Used to control if the browser is allowed to only access a site over a secure connection":http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
+
h3. Additional Resources
The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:
diff --git a/guides/source/testing.textile b/guides/source/testing.textile
index d35be6a70e..4faf59fad8 100644
--- a/guides/source/testing.textile
+++ b/guides/source/testing.textile
@@ -1,62 +1,57 @@
h2. A Guide to Testing Rails Applications
-This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
+This guide covers built-in mechanisms offered by Rails to test your
+application. By referring to this guide, you will be able to:
* Understand Rails testing terminology
-* Write unit, functional and integration tests for your application
+* Write unit, functional, and integration tests for your application
* Identify other popular testing approaches and plugins
-This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
-
endprologue.
h3. Why Write Tests for your Rails Applications?
-* Rails makes it super easy to write your tests. It starts by producing skeleton test code in the background while you are creating your models and controllers.
-* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
-* Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
-
-h3. Introduction to Testing
-
-Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.
-h4. The Three Environments
+By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
-Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
+Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
-One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
+h3. Introduction to Testing
-* production
-* development
-* test
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
-This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
+h4. The Test Environment
-For example, suppose you need to test your new +delete_this_user_and_every_everything_associated_with_it+ function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not?
+By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in +config/database.yml+.
-When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+.
+A dedicated test database allows you to set up and interact with test data in isolation. Tests can mangle test data with confidence, that won't touch the data in the development or production databases.
h4. Rails Sets up for Testing from the Word Go
Rails creates a +test+ folder for you as soon as you create a Rails project using +rails new+ _application_name_. If you list the contents of this folder then you shall see:
<shell>
-$ ls -F test/
+$ ls -F test
-fixtures/ functional/ integration/ test_helper.rb unit/
+fixtures/ functional/ integration/ performance/ test_helper.rb unit/
</shell>
-The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests.
+The +unit+ directory is meant to hold tests for your models, the +functional+ directory is meant to hold tests for your controllers, the +integration+ directory is meant to hold tests that involve any number of controllers interacting, and the +performance+ directory is meant for performance tests.
+
+Fixtures are a way of organizing test data; they reside in the +fixtures+ folder.
+
+The +test_helper.rb+ file holds the default configuration for your tests.
h4. The Low-Down on Fixtures
For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
-h5. What are Fixtures?
+h5. What Are Fixtures?
-_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume a single format: *YAML*.
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent written in YAML. There is one file per model.
-You'll find fixtures under your +test/fixtures+ directory. When you run +rails generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
+You'll find fixtures under your +test/fixtures+ directory. When you run +rails generate model+ to create a new model fixture stubs will be automatically created and placed in this directory.
h5. YAML
@@ -77,35 +72,20 @@ steve:
profession: guy with keyboard
</yaml>
-Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
+Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
h5. ERB'in It Up
-ERB allows you to embed ruby code within templates. YAML fixture format is pre-processed with ERB when you load fixtures. This allows you to use Ruby to help you generate some sample data.
-
-<erb>
-<% earth_size = 20 %>
-mercury:
- size: <%= earth_size / 50 %>
- brightest_on: <%= 113.days.ago.to_s(:db) %>
-
-venus:
- size: <%= earth_size / 2 %>
- brightest_on: <%= 67.days.ago.to_s(:db) %>
-
-mars:
- size: <%= earth_size - 69 %>
- brightest_on: <%= 13.days.from_now.to_s(:db) %>
-</erb>
-
-Anything encased within the
+ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:
<erb>
-<% %>
+<% 1000.times do |n| %>
+user_<%= n %>:
+ username: <%= "user%03d" % n %>
+ email: <%= "user%03d@example.com" % n %>
+<% end %>
</erb>
-tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
-
h5. Fixtures in Action
Rails by default automatically loads all fixtures from the +test/fixtures+ folder for your unit and functional test. Loading involves three steps:
@@ -377,12 +357,12 @@ There are a bunch of different types of assertions you can use. Here's the compl
|_.Assertion |_.Purpose|
|+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
-|+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.|
-|+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.|
-|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
-|+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.|
+|+assert_equal( expected, actual, [msg] )+ |Ensures that +expected == actual+ is true.|
+|+assert_not_equal( expected, actual, [msg] )+ |Ensures that +expected != actual+ is true.|
+|+assert_same( expected, actual, [msg] )+ |Ensures that +expected.equal?(actual)+ is true.|
+|+assert_not_same( expected, actual, [msg] )+ |Ensures that +!expected.equal?(actual)+ is true.|
|+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
-|+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.|
+|+assert_not_nil( obj, [msg] )+ |Ensures that +!obj.nil?+ is true.|
|+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.|
|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't match the regular expression.|
|+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.|
@@ -526,7 +506,7 @@ You also have access to three instance variables in your functional tests:
h4. Testing Templates and Layouts
-If you want to make sure that the response rendered the correct template and layout, you can use the +assert_template+
+If you want to make sure that the response rendered the correct template and layout, you can use the +assert_template+
method:
<ruby>
diff --git a/guides/source/upgrading_ruby_on_rails.textile b/guides/source/upgrading_ruby_on_rails.textile
index 4bf4751127..70d4dabfe2 100644
--- a/guides/source/upgrading_ruby_on_rails.textile
+++ b/guides/source/upgrading_ruby_on_rails.textile
@@ -42,6 +42,10 @@ h4(#active_record4_0). Active Record
The <tt>delete</tt> method in collection associations can now receive <tt>Fixnum</tt> or <tt>String</tt> arguments as record ids, besides records, pretty much like the <tt>destroy</tt> method does. Previously it raised <tt>ActiveRecord::AssociationTypeMismatch</tt> for such arguments. From Rails 4.0 on <tt>delete</tt> automatically tries to find the records matching the given ids before deleting them.
+Rails 4.0 has changed how orders get stacked in +ActiveRecord::Relation+. In previous versions of rails new order was applied after previous defined order. But this is no long true. Check "ActiveRecord Query guide":active_record_querying.html#ordering for more information.
+
+Rails 4.0 has changed <tt>serialized_attributes</tt> and <tt>_attr_readonly</tt> to class methods only. Now you shouldn't use instance methods, it's deprecated. You must change them, e.g. <tt>self.serialized_attributes</tt> to <tt>self.class.serialized_attributes</tt>.
+
h4(#active_model4_0). Active Model
Rails 4.0 has changed how errors attach with the <tt>ActiveModel::Validations::ConfirmationValidator</tt>. Now when confirmation validations fail the error will be attached to <tt>:#{attribute}_confirmation</tt> instead of <tt>attribute</tt>.
@@ -50,7 +54,21 @@ h4(#action_pack4_0). Action Pack
Rails 4.0 changed how <tt>assert_generates</tt>, <tt>assert_recognizes</tt>, and <tt>assert_routing</tt> work. Now all these assertions raise <tt>Assertion</tt> instead of <tt>ActionController::RoutingError</tt>.
-Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, e.g. <tt>get Rack::Utils.escape('こんにちは'), :controller => 'welcome', :action => 'index'</tt> to <tt>get 'こんにちは', :controller => 'welcome', :action => 'index'</tt>.
+Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:
+
+<ruby>
+get Rack::Utils.escape('こんにちは'), :controller => 'welcome', :action => 'index'
+</ruby>
+
+becomes
+
+<ruby>
+get 'こんにちは', :controller => 'welcome', :action => 'index'
+</ruby>
+
+h4(#active_support4_0). Active Support
+
+Rails 4.0 Removed the <tt>j</tt> alias for <tt>ERB::Util#json_escape</tt> since <tt>j</tt> is already used for <tt>ActionView::Helpers::JavaScriptHelper#escape_javascript</tt>.
h4(#helpers_order). Helpers Loading Order
diff --git a/guides/w3c_validator.rb b/guides/w3c_validator.rb
index 5e340499c4..6ef3df45a9 100644
--- a/guides/w3c_validator.rb
+++ b/guides/w3c_validator.rb
@@ -5,9 +5,9 @@
# Guides are taken from the output directory, from where all .html files are
# submitted to the validator.
#
-# This script is prepared to be launched from the railties directory as a rake task:
+# This script is prepared to be launched from the guides directory as a rake task:
#
-# rake validate_guides
+# rake guides:validate
#
# If nothing is specified, all files will be validated, but you can check just
# some of them using this environment variable:
@@ -17,12 +17,12 @@
# enough:
#
# # validates only association_basics.html
-# ONLY=assoc rake validate_guides
+# rake guides:validate ONLY=assoc
#
# Separate many using commas:
#
# # validates only association_basics.html and migrations.html
-# ONLY=assoc,migrations rake validate_guides
+# rake guides:validate ONLY=assoc,migrations
#
# ---------------------------------------------------------------------------
@@ -38,7 +38,12 @@ module RailsGuides
errors_on_guides = {}
guides_to_validate.each do |f|
- results = validator.validate_file(f)
+ begin
+ results = validator.validate_file(f)
+ rescue Exception => e
+ puts "\nCould not validate #{f} because of #{e}"
+ next
+ end
if results.validity
print "."
@@ -53,15 +58,15 @@ module RailsGuides
private
def guides_to_validate
- guides = Dir["./guides/output/*.html"]
- guides.delete("./guides/output/layout.html")
+ guides = Dir["./output/*.html"]
+ guides.delete("./output/layout.html")
ENV.key?('ONLY') ? select_only(guides) : guides
end
def select_only(guides)
prefixes = ENV['ONLY'].split(",").map(&:strip)
guides.select do |guide|
- prefixes.any? {|p| guide.start_with?("./guides/output/#{p}")}
+ prefixes.any? {|p| guide.start_with?("./output/#{p}")}
end
end
diff --git a/rails.gemspec b/rails.gemspec
index 52f92f46c6..3600882c5c 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -24,6 +24,6 @@ Gem::Specification.new do |s|
s.add_dependency('activerecord', version)
s.add_dependency('actionmailer', version)
s.add_dependency('railties', version)
- s.add_dependency('bundler', '~> 1.1')
+ s.add_dependency('bundler', '~> 1.2')
s.add_dependency('sprockets-rails', '~> 1.0')
end
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 7223270210..b42ef8e14a 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,5 +1,23 @@
## Rails 4.0.0 (unreleased) ##
+* Correctly handle SCRIPT_NAME when generating routes to engine in application
+ that's mounted at a sub-uri. With this behavior, you *should not* use
+ default_url_options[:script_name] to set proper application's mount point by
+ yourself. *Piotr Sarnacki*
+
+* `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded *José Valim*
+
+* The migration generator will now produce AddXXXToYYY/RemoveXXXFromYYY migrations with references statements, for instance
+
+ rails g migration AddReferencesToProducts user:references supplier:references{polymorphic}
+
+ will generate the migration with:
+
+ add_reference :products, :user, index: true
+ add_reference :products, :supplier, polymorphic: true, index: true
+
+ *Aleksey Magusev*
+
* Allow scaffold/model/migration generators to accept a `polymorphic` modifier
for `references`/`belongs_to`, for instance
@@ -20,8 +38,6 @@
* Load all environments available in `config.paths["config/environments"]`. *Piotr Sarnacki*
-* The application generator generates `public/humans.txt` with some basic data. *Paul Campbell*
-
* Add `config.queue_consumer` to allow the default consumer to be configurable. *Carlos Antonio da Silva*
* Add Rails.queue as an interface with a default implementation that consumes jobs in a separate thread. *Yehuda Katz*
@@ -52,2482 +68,4 @@
* Set config.action_mailer.async = true to turn on asynchronous
message delivery *Brian Cardarella*
-
-## Rails 3.2.2 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.2.1 (January 26, 2012) ##
-
-* Documentation fixes.
-
-* Migration generation understands decimal{1.2} and decimal{1-2}, in
- addition to decimal{1,2}. *José Valim*
-
-
-## Rails 3.2.0 (January 20, 2012) ##
-
-* Turn gem has been removed from default Gemfile. We still looking for a best presentation for tests output. *Guillermo Iguaran*
-
-* Rails::Plugin is deprecated and will be removed in Rails 4.0. Instead of adding plugins to vendor/plugins use gems or bundler with path or git dependencies. *Santiago Pastorino*
-
-* Guides are available as a single .mobi for the Kindle and free Kindle readers apps. *Michael Pearson & Xavier Noria*
-
-* Allow scaffold/model/migration generators to accept a "index" and "uniq" modifiers, as in: "tracking_id:integer:uniq" in order to generate (unique) indexes. Some types also accept custom options, for instance, you can specify the precision and scale for decimals as "price:decimal{7,2}". *Dmitrii Samoilov*
-
-* Added `config.exceptions_app` to set the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`. *José Valim*
-
-* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting `config.reload_classes_only_on_change` to false. *José Valim*
-
-* New applications get a flag `config.active_record.auto_explain_threshold_in_seconds` in the environments configuration files. With a value of 0.5 in development.rb, and commented out in production.rb. No mention in test.rb. *fxn*
-
-* Add DebugExceptions middleware which contains features extracted from ShowExceptions middleware *José Valim*
-
-* Display mounted engine's routes in `rake routes` *Piotr Sarnacki*
-
-* Allow to change the loading order of railties with `config.railties_order=` *Piotr Sarnacki*
-
- Example:
- config.railties_order = [Blog::Engine, :main_app, :all]
-
-* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box *José Valim*
-
-* Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications *DHH*
-
-* Default options to `rails new` can be set in ~/.railsrc. You can specify extra command-line arguments to be used every time
- 'rails new' runs in the .railsrc configuration file in your home directory. *Guillermo Iguaran*
-
-* Add destroy alias to Rails engines *Guillermo Iguaran*
-
-* Add destroy alias for Rails command line. This allows the following: `rails d model post` *Andrey Ognevsky*
-
-* Attributes on scaffold and model generators default to string. This allows the following: "rails g scaffold Post title body:text author" *José Valim*
-
-* Remove old plugin generator (`rails generate plugin`) in favor of `rails plugin new` command *Guillermo Iguaran*
-
-* Remove old 'config.paths.app.controller' API in favor of 'config.paths["app/controller"]' API *Guillermo Iguaran*
-
-
-## Rails 3.1.4 (March 1, 2012) ##
-
-* Setting config.force_ssl also marks the session cookie as secure.
-
- *José Valim*
-
-* Add therubyrhino to Gemfile in new applications when running under JRuby.
-
- *Guillermo Iguaran*
-
-
-## Rails 3.1.3 (November 20, 2011) ##
-
-* New apps should be generated with a sass-rails dependency of 3.1.5, not 3.1.5.rc.2
-
-
-## Rails 3.1.2 (November 18, 2011) ##
-
-* Engines: don't blow up if db/seeds.rb is missing.
-
- *Jeremy Kemper*
-
-* `rails new foo --skip-test-unit` should not add the `:test` task to the rake default task.
- *GH 2564*
-
- *José Valim*
-
-## Rails 3.1.1 (October 07, 2011) ##
-
-* Add jquery-rails to Gemfile of plugins, test/dummy app needs it. Closes #3091. *Santiago Pastorino*
-
-* Add config.assets.initialize_on_precompile which, when set to false, forces
- `rake assets:precompile` to load the application but does not initialize it.
-
- To the app developer, this means configuration add in
- config/initializers/* will not be executed.
-
- Plugins developers need to special case their initializers that are
- meant to be run in the assets group by adding :group => :assets.
-
-## Rails 3.1.0 (August 30, 2011) ##
-
-* The default database schema file is written as UTF-8. *Aaron Patterson*
-
-* Generated apps with --dev or --edge flags depend on git versions of
- sass-rails and coffee-rails. *Santiago Pastorino*
-
-* Rack::Sendfile middleware is used only if x_sendfile_header is present. *Santiago Pastorino*
-
-* Add JavaScript Runtime name to the Rails Info properties. *DHH*
-
-* Make pp enabled by default in Rails console. *Akira Matsuda*
-
-* Add alias `r` for rails runner. *Jordi Romero*
-
-* Make sprockets/railtie require explicit and add --skip-sprockets to app generator *José Valim*
-
-* Added Rails.groups that automatically handles Rails.env and ENV["RAILS_GROUPS"] *José Valim*
-
-* The new rake task assets:clean removes precompiled assets. *fxn*
-
-* Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. *fxn*
-
-* Fixed database tasks for jdbc* adapters #jruby *Rashmi Yadav*
-
-* Template generation for jdbcpostgresql #jruby *Vishnu Atrai*
-
-* Template generation for jdbcmysql and jdbcsqlite3 #jruby *Arun Agrawal*
-
-* The -j option of the application generator accepts an arbitrary string. If passed "foo",
- the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest
- requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails"
- exist and provide those files via the asset pipeline. Default is "jquery". *fxn*
-
-* jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. *fxn*
-
-* Prototype and Scriptaculous are no longer vendored, they are provided from now on
- by the prototype-rails gem. *fxn*
-
-* The scaffold controller will now produce SCSS file if Sass is available *Prem Sichanugrist*
-
-* The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. *DHH*
-
-* jQuery is the new default JavaScript library. *fxn*
-
-* Changed scaffold, application, and mailer generator to create Ruby 1.9 style hash when running on Ruby 1.9 *Prem Sichanugrist*
-
- So instead of creating something like:
-
- redirect_to users_path, :notice => "User has been created"
-
- it will now be like this:
-
- redirect_to users_path, notice: "User has been created"
-
- You can also passing `--old-style-hash` to make Rails generate old style hash even you're on Ruby 1.9
-
-* Changed scaffold_controller generator to create format block for JSON instead of XML *Prem Sichanugrist*
-
-* Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) *DHH*
-
-* Direct logging of Active Record to STDOUT so it's shown inline with the results in the console *DHH*
-
-* Added `config.force_ssl` configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol *DHH, Prem Sichanugrist, and Josh Peek*
-
-* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing *Piotr Sarnacki*
-
-* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. *siong1987*
-
-* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack *José Valim*
-
-* Added Rack::Cache to the default middleware stack *Yehuda Katz and Carl Lerche*
-
-* Engine is now rack application *Piotr Sarnacki*
-
-* Added middleware stack to Engine *Piotr Sarnacki*
-
-* Engine can now load plugins *Piotr Sarnacki*
-
-* Engine can load its own environment file *Piotr Sarnacki*
-
-* Added helpers to call engines' route helpers from application and vice versa *Piotr Sarnacki*
-
-* Task for copying plugins' and engines' migrations to application's db/migrate directory *Piotr Sarnacki*
-
-* Changed ActionDispatch::Static to allow handling multiple directories *Piotr Sarnacki*
-
-* Added isolate_namespace() method to Engine, which sets Engine as isolated *Piotr Sarnacki*
-
-* Include all helpers from plugins and shared engines in application *Piotr Sarnacki*
-
-
-## Rails 3.0.12 (March 1, 2012) ##
-
-* No changes.
-
-
-## Rails 3.0.11 (November 18, 2011) ##
-
-* Updated Prototype UJS to lastest version fixing multiples errors in IE [Guillermo Iguaran]
-
-
-## Rails 3.0.10 (August 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.9 (June 16, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.8 (June 7, 2011) ##
-
-* Fix Rake 0.9.0 support.
-
-
-## Rails 3.0.7 (April 18, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.6 (April 5, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.5 (February 26, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.4 (February 8, 2011) ##
-
-* No changes.
-
-
-## Rails 3.0.3 (November 16, 2010) ##
-
-* No changes.
-
-
-## Rails 3.0.2 (November 15, 2010) ##
-
-* No changes.
-
-
-## Rails 3.0.1 (October 15, 2010) ##
-
-* No Changes, just a version bump.
-
-
-## Rails 3.0.0 (August 29, 2010) ##
-
-* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. *fxn*
-
-* Added console to Rails::Railtie as a hook called just after console starts. *José Valim*
-
-* Rails no longer autoload code in lib for application. You need to explicitly require it. *José Valim*
-
-* Rails::LogSubscriber was renamed to ActiveSupport::LogSubscriber *José Valim*
-
-* config.load_(once_)paths in config/application.rb got renamed to config.autoload_(once_)paths. *fxn*
-
-* Abort generation/booting on Ruby 1.9.1. *fxn*
-
-* Made the rails command work even when you're in a subdirectory *Chad Fowler*
-
-* Removed Rails Metal [Yehuda Katz, José Valim].
-
-* Renamed config.cookie_secret to config.secret_token and pass it as env key. *José Valim*
-
-* Session store configuration has changed *Yehuda Katz, Carl Lerche*
-
- config.session_store :cookie_store, {:key => "..."}
- config.cookie_secret = "fdsfhisdghfidugnfdlg"
-
-* railtie_name and engine_name are deprecated. You can now add any object to
- the configuration object: config.your_plugin = {} *José Valim*
-
-* Added config.generators.templates to provide alternative paths for the generators
- to look for templates *José Valim*
-
-* Added "rake about" as a replacement for script/about *DHH*
-
-* Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example:
-
- ./script/generate scaffold post title:string can now be called as rails g scaffold post title:string
-
- Run rails --help inside an app for more help.
-
-* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it *DHH*
-
-* Set config.time_zone to UTC by default *DHH*
-
-* Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) *DHH*
-
-* Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples:
-
- cookies.permanent[:prefers_open_id] = true
- # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
- cookies.signed[:discount] = 45
- # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
- cookies.signed[:discount]
- # => 45 (if the cookie was changed, you'll get a InvalidSignature exception)
-
- cookies.permanent.signed[:remember_me] = current_user.id
- # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
- ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
-
-* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed *DHH*
-
-* Fixed that the debugger wouldn't go into IRB mode because of left-over ARGVs *DHH*
-
-* I18n support for plugins. #2325 *Antonio Tapiador, Sven Fuchs*
-
-* Ruby 1.9: use UTF-8 for default internal and external encodings. *Jeremy Kemper*
-
-* Added db/seeds.rb as a default file for storing seed data for the database. Can be loaded with rake db:seed (or created alongside the db with db:setup). (This is also known as the "Stop Putting Gawd Damn Seed Data In Your Migrations" feature) *DHH*
-
-
-## 2.3.2 Final (March 15, 2009) ##
-
-* Remove outdated script/plugin options *Pratik Naik*
-
-* Allow metal to live in plugins #2045 *Matthew Rudy*
-
-* Added metal *Josh Peek*
-
-* Remove script/performance/request in favour of the performance integration tests. *Pratik Naik*
-
- To continue using script/performance/request, install the request_profiler plugin :
-
- script/plugin install git://github.com/rails/request_profiler.git
-
-* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb *Pratik Naik*
-
-* Add "-m/--template" option to Rails generator to apply a template to the generated application. *Jeremy McAnally*
-
- This has been extracted from rg - http://github.com/jeremymcanally/rg
-
- Example:
-
- # template.rb
-
- # Install plugins from git or svn
- plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
- plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
-
- # Add gems to environment.rb
- gem "jeremymcanally-context"
- gem "bluecloth"
-
- # Vendor file. Data in a string or...
- vendor("borrowed.rb", <<CODE
- def helpful_method
- do_something_helpful_here
- end
- CODE
-
- # ...file data from block return value.
- # #initializer creates a new initializer file
- initializer("crypto.rb") do
- salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
-
- "SPECIAL_SALT = '#{salt}'"
- end
-
- Usage:
-
- To use a template, provide a file path or URL:
-
- 1. Using a local file :
-
- rails <application name> -m /path/to/my/template.rb
-
- 2. Or directly from a URL :
-
- rails <application name> --template=http://gist.github.com/31208.txt
-
-* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts *David Heinemeier Hansson*
-
-* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 *Damian Janowski/?*
-
-* Added view path support for engines *David Heinemeier Hansson*
-
-* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) *David Heinemeier Hansson*
-
-* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) *David Heinemeier Hansson*
-
-* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! *Jeremy Kemper*
-
-* Add a rake task to generate dispatchers : rake rails:generate_dispatchers *Pratik Naik*
-
-* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. *Yaroslav Markin, Pratik Naik*
-
-* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 *kastner*
-
-* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) *David Heinemeier Hansson*
-
-* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. *Jeremy Kemper*
-
-* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale *David Heinemeier Hansson*
-
-* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version *David Heinemeier Hansson*
-
-
-## 2.2.1 RC2 (November 14th, 2008) ##
-
-* Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 *Mathias Meyer*
-
-* Update Prototype to 1.6.0.3 *sam*
-
-
-## 2.2.0 RC1 (October 24th, 2008) ##
-
-* Fixed that sqlite would report "db/development.sqlite3 already exists" whether true or not on db:create #614 *Antonio Cangiano*
-
-* Added config.threadsafe! to toggle allow concurrency settings and disable the dependency loader *Josh Peek*
-
-* Turn cache_classes on by default *Josh Peek*
-
-* Added configurable eager load paths. Defaults to app/models, app/controllers, and app/helpers *Josh Peek*
-
-* Introduce simple internationalization support. *Ruby i18n team*
-
-* Make script/plugin install <plugin> -r <revision> option work with git based plugins. #257. [Tim Pope Jakub Kuźma]. Example:
-
- script/plugin install git://github.com/mislav/will_paginate.git -r agnostic # Installs 'agnostic' branch
- script/plugin install git://github.com/dchelimsky/rspec.git -r 'tag 1.1.4'
-
-* Added Rails.initialized? flag *Josh Peek*
-
-* Make rake test:uncommitted work with Git. *Tim Pope*
-
-* Added Thin support to script/server. #488 *Bob Klosinski*
-
-* Fix script/about in production mode. #370 *Cheah Chu Yeow, Xavier Noria, David Krmpotic*
-
-* Add the gem load paths before the framework is loaded, so certain gems like RedCloth and BlueCloth can be frozen.
-
-* Fix discrepancies with loading rails/init.rb from gems.
-
-* Plugins check for the gem init path (rails/init.rb) before the standard plugin init path (init.rb) *Jacek Becela*
-
-* Changed all generated tests to use the test/do declaration style *David Heinemeier Hansson*
-
-* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? *David Heinemeier Hansson*
-
-* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) *#310 state:resolved*
-
-
-## 2.1.0 (May 31st, 2008) ##
-
-* script/dbconsole fires up the command-line database client. #102 *Steve Purcell*
-
-* Fix bug where plugin init.rb files from frozen gem specs weren't being run. (pjb3) *#122 state:resolved*
-
-* Made the location of the routes file configurable with config.routes_configuration_file (Scott Fleckenstein) *#88*
-
-* Rails Edge info returns the latest git commit hash *Francesc Esplugas*
-
-* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 *Nick Sieger*
-
-* rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere *Geoff Buesing*
-
-* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. *Rick Olson*
-
-* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. *Jonathan del Strother*
-
-* Flesh out rake gems:unpack to unpack all gems, and add rake gems:build for native extensions. #11513 *ddollar*
-
- rake gems:unpack # unpacks all gems
- rake gems:unpack GEM=mygem # unpacks only the gem 'mygem'
-
- rake gems:build # builds all unpacked gems
- rake gems:build GEM=mygem # builds only the gem 'mygem'
-
-* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb *Rick Olson*
-
-* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants *Pratik Naik*
-
-* Allow files in plugins to be reloaded like the rest of the application. *Rick Olson*
-
- Enables or disables plugin reloading.
-
- config.reload_plugins = true
-
- You can get around this setting per plugin.
- If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable:
-
- Dependencies.load_once_paths.delete lib_path
-
- If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
-
- Dependencies.load_once_paths << lib_path
-
-* Small tweak to allow plugins to specify gem dependencies. *Rick Olson*
-
- \# OLD open_id_authentication plugin init.rb
- require 'yadis'
- require 'openid'
- ActionController::Base.send :include, OpenIdAuthentication
-
- \# NEW
- config.gem "ruby-openid", :lib => "openid", :version => "1.1.4"
- config.gem "ruby-yadis", :lib => "yadis", :version => "0.3.4"
-
- config.after_initialize do
- ActionController::Base.send :include, OpenIdAuthentication
- end
-
-* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. *Rick Olson*
-
- Rails::Initializer.run do |config|
- config.gem "bj"
- config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
- config.gem "aws-s3", :lib => "aws/s3"
- end
-
- \# List required gems.
- rake gems
-
- \# Install all required gems:
- rake gems:install
-
- \# Unpack specified gem to vendor/gems/gem_name-x.x.x
- rake gems:unpack GEM=bj
-
-* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) *David Heinemeier Hansson*
-
-* config.time_zone accepts TZInfo::Timezone identifiers as well as Rails TimeZone identifiers *Geoff Buesing*
-
-* Rails::Initializer#initialize_time_zone raises an error if value assigned to config.time_zone is not recognized. Rake time zone tasks only require ActiveSupport instead of entire environment *Geoff Buesing*
-
-* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons *David Heinemeier Hansson*
-
-* Added that gems can now be plugins if they include rails/init.rb #11444 *John Barnette*
-
-* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 *James Adam*
-
- plugin = Rails::Plugin.new(path_to_my_plugin)
- plugin.about["author"] # => "James Adam"
- plugin.about["url"] # => "http://interblah.net"
-
-* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
-
-* Added config.time_zone = 'UTC' in the default environment.rb *Geoff Buesing*
-
-* Added rake tasks time:zones:all, time:zones:us and time:zones:local for finding time zone names for config.time_zone option *Geoff Buesing*
-
-* Add config.time_zone for configuring the default Time.zone value. #10982 *Geoff Buesing*
-
-* Added support for installing plugins hosted at git repositories #11294 *Jack Danger Canty*
-
-* Fixed that script/generate would not look for plugin generators in plugin_paths #11000 *glv*
-
-* Fixed database rake tasks to work with charset/collation and show proper error messages on failure. Closes #11301 *matt*
-
-* Added a -e/--export to script/plugin install, uses svn export. #10847 *jon@blankpad.net)*
-
-* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 *Rick Olson*
-
-* Git support for script/generate. #10690 *ssoroka*
-
-* Update scaffold to use labels instead of bold tags. Closes #10757 *zach-inglis-lt3*
-
-* Resurrect WordNet synonym lookups. #10710 *tom./, matt*
-
-* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) *David Heinemeier Hansson*
-
-* Added that rails:update is run when you do rails:freeze:edge to ensure you also get the latest JS and config files #10565 *jeff*
-
-* SQLite: db:drop:all doesn't fail silently if the database is already open. #10577 *Cheah Chu Yeow, mrichman*
-
-* Introduce native mongrel handler and push mutex into dispatcher. *Jeremy Kemper*
-
-* Ruby 1.9 compatibility. #1689, #10546 *Cheah Chu Yeow, frederico*
-
-
-## 2.0.2 (December 16th, 2007) ##
-
-* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" *David Heinemeier Hansson*
-
-* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) *David Heinemeier Hansson*
-
-* Introduce `rake secret` to output a crytographically secure secret key for use with cookie sessions #10363 *revans*
-
-* Fixed that local database creation should consider 127.0.0.1 local #9026 *parcelbrat*
-
-* Fixed that functional tests generated for scaffolds should use fixture calls instead of hard-coded IDs #10435 *boone*
-
-* Added db:migrate:redo and db:migrate:reset for rerunning existing migrations #10431, #10432 *matt*
-
-* RAILS_GEM_VERSION may be double-quoted also. #10443 *James Cox*
-
-* Update rails:freeze:gems to work with RubyGems 0.9.5. *Jeremy Kemper*
-
-
-## 2.0.1 (December 7th, 2007) ##
-
-* Fixed Active Record bug
-
-
-## 2.0.0 (December 6th, 2007) ##
-
-* The test task stops with a warning if you have pending migrations. #10377 *Josh Knowles*
-
-* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 *Thijs van der Vossen*
-
-* Update Prototype to 1.6.0.1. *sam*
-
-* Update script.aculo.us to 1.8.0.1. *madrobby*
-
-* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 *John Barnette*
-
-* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 *John Barnette*
-
-* Update to Prototype -r8232. *sam*
-
-* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 *Hongli Lai (Phusion)*
-
-* RAILS_GEM_VERSION may be set to any valid gem version specifier. #10057 *Chad Woolley, Cheah Chu Yeow*
-
-* Load config/preinitializer.rb, if present, before loading the environment. #9943 *Chad Woolley*
-
-* FastCGI handler ignores unsupported signals like USR2 on Windows. *Grzegorz Derebecki*
-
-* Only load ActionMailer::TestCase if ActionMailer is loaded. Closes #10137 *defunkt*
-
-* Fixed that db:reset would use migrations instead of loading db/schema.rb *David Heinemeier Hansson*
-
-* Ensure the plugin loader only loads plugins once. Closes #10102 *haruki_zaemon*
-
-* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 *James Adam*
-
-* Added --skip-timestamps to generators that produce models #10036 *Tim Pope*
-
-* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. *sam, madrobby*
-
-* Added db:rollback to rollback the schema one version (or multiple as specified by STEP) *Jeffrey Allan Hardy*
-
-* Fix typo in test_helper. Closes #9925 *viktor tron*
-
-* Request profiler. *Jeremy Kemper*
-
-* config/boot.rb correctly detects RAILS_GEM_VERSION. #9834 *alexch, thewoolleyman*
-
-* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 *Jeremy McAnally*
-
-* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. *sam, madrobby*
-
-* Generated fixtures use the actual primary key instead of id. #4343 *Frederick Ros, Tarmo Tänav*
-
-* Extend the console +helper+ method to allow you to include custom helpers. e.g:
- >> helper :posts
- >> helper.some_method_from_posts_helper(Post.find(1))
-
-* db:create works with remote databases whereas db:create:all only creates
- databases on localhost. #9753 *Trevor Wennblom*
-
-* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb *David Heinemeier Hansson*
-
-* Add --prefix option to script/server when using mongrel. *dacat*
-
-
-## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.1.4 - 1.2.3 ##
-
-* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 *evan*
-
-* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. *Rick Olson*
-
-* Moved Dispatcher to ActionController::Dispatcher. *Jeremy Kemper*
-
-* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [David Heinemeier Hansson]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
-
-* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised *David Heinemeier Hansson*
-
-* Added --skip-fixture option to script/generate model #6862 *sandofsky*
-
-* Print Rails version when starting console #7440 *eyematz*
-
-* Fixed the placement of fixture files for nested models when generating through script/generate model #7547 *jkit*
-
-* Added TEMPLATE option to rake doc:app to set a custom output template #7737 *Jakob Skjerning*
-
-* Added VERBOSE option to rake db:migrate to turn off output #8204 *John Barnette*
-
-* Fixed that rake doc:app should use UTF-8 #8906 *farzy*
-
-* Fixes rake annotations to search erb and builder files as well #9150 *m.langenberg*
-
-* Removed web_service generator *Michael Koziarski*
-
-* Added the :all option to config.plugins that'll include the rest of the plugins not already explicitly named #9613 [Frederick Cheung]. Example:
-
- # Loads :classic_pagination before all the other plugins
- config.plugins = [ :classic_pagination, :all ]
-
-* Added symbols as a legal way of specifying plugins in config.plugins #9629 *tom*
-
-* Removed deprecated task names, like clear_logs, in favor of the new namespaced style *David Heinemeier Hansson*
-
-* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 *Zach Dennis*
-
-* Added db:drop:all to drop all databases declared in config/database.yml *David Heinemeier Hansson*
-
-* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 *Pratik Naik*
-
- For example:
-
- ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string
-
- or
-
- ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
-
-* Add ActiveResource to Rails::Info. Closes #8741 *Chris Kampmeier*
-
-* use Gem.find_name instead of search when freezing gems. Prevent false positives for other gems with rails in the name. Closes #8729 *wselman*
-
-* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 *Ryan Davis*
-
-* Default to plural table name in Rails Generator if ActiveRecord is not present. Closes #8963 *evan*
-
-* Added rake routes for listing all the defined routes in the system. #8795 *Josh Peek*
-
-* db:create creates the database for the current environment if it's on localhost. db:create:all creates local databases for all environments. #8783 *matt*
-
-* Generators: look for generators in all gems, not just those suffixed with _generator, in the gem's generators or rails_generators directory. Allow use of the rails_generators directory instead of the standard generators directory in plugins also. #8730 *Dr Nic, topfunky*
-
-* MySQL, PostgreSQL: database.yml defaults to utf-8. #8701 *matt*
-
-* Added db:version to get the current schema number *via Err The Blog*
-
-* Added --skip-migration option to scaffold and resource generators #8656 *Michael Glaesemann*
-
-* Fix that FCGIs would leave log files open when asked to shut down by USR2. #3028 *Sebastian Kanthak, Josh Peek*
-
-* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. *Rick Olson*
-
-* Fix syntax error in dispatcher than wrecked failsafe responses. #8625 *mtitorenko*
-
-* Scaffolded validation errors set the appropriate HTTP status for XML responses. #6946, #8622 *Manfred Stienstra, mmmultiworks*
-
-* Sexy migrations for the session_migration generator. #8561 *Vladislav*
-
-* Console reload! runs to_prepare callbacks also. #8393 *f.svehla*
-
-* Generated migrations include timestamps by default. #8501 *Shane Vitarana*
-
-* Drop Action Web Service from rails:freeze:edge. *Jeremy Kemper*
-
-* Add db:create, drop, reset, charset, and collation tasks. #8448 *matt*
-
-* Scaffold generator depends on model generator instead of duplicating it. #7222 *bscofield*
-
-* Scaffold generator tests. #8443 *pelle*
-
-* Generated scaffold functional tests use assert_difference. #8421 *Norbert Crombach*
-
-* Update to Prototype 1.5.1. *Sam Stephenson*
-
-* Update to script.aculo.us 1.7.1_beta3. *Thomas Fuchs*
-
-* Generators use *.html.erb view template naming. #8278 *Tim Pope*
-
-* Updated resource_scaffold and model generators to use short-hand style migrations *David Heinemeier Hansson*
-
-* Updated initializer to only load #{RAILS_ENV}.rb once. Added deprecation warning for config.breakpoint_server. *Nicholas Seckar*
-
-* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back *David Heinemeier Hansson*
-
- To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
- (instead of 'breakpoint') where you want to jump into the debugger.
-
- BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb:
-
- config.breakpoint_server = true
-
- This configuration option is no longer available. Rails will fail to start in development mode as long as
- that's still present.
-
-* Resource scaffolding returns the created entity.to_xml. *Jeremy Kemper*
-
-* Resource scaffolding responds to new.xml. #8185 *Eric Mill*
-
-* Include Active Resource in rails:freeze:edge rake task. *Thomas Fuchs*
-
-* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
-
- config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
-
- ...or just gem 'actionwebservice'
-
-* Give generate scaffold a more descriptive database message. Closes #7316 *Jeremy McAnally*
-
-* Canonicalize RAILS_ROOT by using File.expand_path on Windows, which doesn't have to worry about symlinks, and Pathname#realpath elsewhere, which respects symlinks in relative paths but is incompatible with Windows. #6755 *Jeremy Kemper, trevor*
-
-* Deprecation: remove components from controller paths. *Jeremy Kemper*
-
-* Add environment variable RAILS_DEFAULT_DATABASE, which allows the builtin default of 'mysql' to be overridden. *Nicholas Seckar*
-
-* Windows: include MinGW in RUBY_PLATFORM check. #2982 *okkez000@gmail.com, Kaspar Schiess*
-
-* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. *Marcel Molina Jr.*
-
-* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. *Marcel Molina Jr.*
-
-* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license *David Heinemeier Hansson*
-
-* Added source-annotations extractor tasks to rake [Jamis Buck]. This allows you to add FIXME, OPTIMIZE, and TODO comments to your source code that can then be extracted in concert with rake notes (shows all), rake notes:fixme, rake notes:optimize and rake notes:todo.
-
-* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time *David Heinemeier Hansson*
-
-* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff *David Heinemeier Hansson*
-
-* For new apps, generate a random secret for the cookie-based session store. *Jeremy Kemper*
-
-* Stop swallowing errors during rake test *Michael Koziarski*
-
-* Update Rails Initializer to use ActionController::Base#view_paths *Rick Olson*
-
-* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ *Chad Fowler*
-
-* Plugins may be symlinked in vendor/plugins. #4245 *brandon, progrium@gmail.com*
-
-* Resource generator depends on the model generator rather than duplicating it. #7269 *bscofield*
-
-* Add/Update usage documentation for script/destroy, resource generator and scaffold_resource generator. Closes #7092, #7271, #7267. *bscofield*
-
-* Update to script.aculo.us 1.7.0. *Thomas Fuchs*
-
-* Update to Prototype 1.5.0. *Sam Stephenson*
-
-* Generator: use destination path for diff tempfiles. #7015 *alfeld*
-
-* Fixed that webrick would strip leading newlines and hang connection #4156 *psross*
-
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. *Rick Olson*
- If you really want your plugins to reload, add this to the very top of init.rb:
-
- Dependencies.load_once_paths.delete(lib_path)
-
-* Allow config.to_prepare to work, make the dispatcher safe to 're require'. *Michael Koziarski, Nicholas Seckar*
-
-* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 *fearoffish*
-
-* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 *Rick Olson*
-
-* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. *James Adam*
-
-* Don't generate a components directory in new Rails apps. *Jeremy Kemper*
-
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) *David Heinemeier Hansson*
-
-* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) *David Heinemeier Hansson*
-
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment *David Heinemeier Hansson*
-
-* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. *Nicholas Seckar*
-
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) *David Heinemeier Hansson*
-
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available *David Heinemeier Hansson*
-
-* Update to Prototype and script.aculo.us [5579]. *Thomas Fuchs*
-
-* Made script/server work with -e and -d when using Mongrel *David Heinemeier Hansson*
-
-* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again *Thomas Fuchs*
-
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action *Tobias Lütke*
-
-* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 *fearoffish*
-
-* Update to Prototype 1.5.0_rc2. *Sam Stephenson*
-
-* Add grep-based fallback to reaper, to work in pidless setups *Jamis Buck*
-
-* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. *Jeremy Kemper*
-
-* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. *Nicholas Seckar*
-
-* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 *jchris*
-
-* Remove temporary crutch to help ApplicationController be unloaded. Closes #6496. *Nicholas Seckar*
-
-* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 *Josh Susser*
-
-* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 *jeffw, Jeremy Kemper*
-
-* Generated directories are recursively svn added, like mkdir -p. #6416 *NeilW*
-
-* resource and scaffold_resource generators add a restful route to config/routes.rb *Jeremy Kemper*
-
-* Revert environment changes for autoload_paths. *Michael Koziarski*
-
-* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions *Thomas Fuchs*
-
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests *Michael Koziarski*
-
-* Added option to script/process/spawner of specifying the binding address #5133 *Dee Zsombor*
-
-* Update environment.rb comments to include config.autoload_paths. Closes #6478 *caio*
-
-* Update scaffold to use new form_tag block functionality. Closes #6480. *Bob Silva*
-
-* Plugin generator: check for class collisions. #4833 *vinbarnes@gmail.com*
-
-* Mailer generator: handle mailers in modules, set mime_version in unit test. *Jeremy Kemper*
-
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. *Michael Koziarski*
-
-* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
-
- config.plugins = %w[ routing_navigator simply_helpful ]
-
-* Clean up html on included error pages. *Tim Lucas*
-
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language *David Heinemeier Hansson*
-
-* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
-
-* PostgreSQL: db:test:purge closes open database connections first. #6236 *alex*
-
-* Fixed test:uncommitted on Windows (backslash issue) #4999 *paul@paulbutcher.com*
-
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 *Bob Silva*
-
-* Fixed rename_table on SQLite tables with indexes defined #5942 *brandon@opensoul.org*
-
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations *David Heinemeier Hansson*
-
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
-
- ./script/generate model post title:string created_on:date body:text published:boolean
-
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined *David Heinemeier Hansson*
-
-* script/runner can run files, pass on arguments, and be used as a shebang. #6286 *Tuxie, dlpond*
- #!/usr/bin/env /path/to/my/app/script/runner
- # Example: just start using your models as if you are in script/console
- Product.find(:all).each { |product| product.check_inventory }
-
-* Look for rake tasks in plugin subdirs. #6259 *obrie*
-
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb *David Heinemeier Hansson*
-
-* Updated prototype.js to 1.5.0_rc1 with latest fixes. *Rick Olson*
-
- - XPATH support
- - Make Form.getElements() return elements in the correct order
- - fix broken Form.serialize return
-
-* session_migration generator adds an index on updated_at. #6207 *grg*
-
-* script/server creates the tmp/pids directory. #6204 *jonathan*
-
-* Fix script/console --sandbox for internal transactions changes. #5738 *Chris McGrath, charles.gerungan@gmail.com*
-
-* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
- documented in initializer.rb, the workaround is:
-
- config.autoload_paths += Dir*RAILS_ROOT + '/app/models/*/'*
-
- References #6031. *Nicholas Seckar*
-
-* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
-
-* Update to Prototype 1.5.0_rc1 *sam*
-
-* Formally Deprecate the old rake tasks. *Michael Koziarski*
-
-* Thoroughly test the FCGI dispatcher. #5970 *Kevin Clark*
-
-* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. *Rick Olson*
-
-* Tighten rescue clauses. #5985 *james@grayproductions.net*
-
-* Cleaning up tests. *Kevin Clark, Jeremy Kemper*
-
-* Add Dependencies.load_once_paths. *Nicholas Seckar*
-
-* Updated to script.aculo.us 1.6.2 *Thomas Fuchs*
-
-* Assign Routing.controller_paths; fix script/about and rails info controller. *Nicholas Seckar*
-
-* Don't warn dispatcher of Reloadable deprecations. *Nicholas Seckar*
-
-* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base *Rick Olson*
-
- ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
- ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
-
-* Add missing mock directories from the autoload_paths configuration. *Rick Olson*
-
-* Nested controller scaffolding also nests the generated layout. *iain d broadfoot*
-
-* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. *Nicholas Seckar*
-
-* Add autoload_paths support to Initializer. *Nicholas Seckar*
-
-* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. *Rick Olson*
-
-* Clarify usage of script/plugin source. Closes #5344. *James Adam*
-
-* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. *Nicholas Seckar*
-
-* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. *Rick Olson*
-
-* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 *mats@imediatec.co.uk*
-
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 *Shugo Maeda*
-
-* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. *Rick Olson*
-
-* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. *Jamis Buck*
-
-* Fix script/plugin about so it uses about.yml and not meta.yml. *James Adam*
-
-* Dispatcher processes rescued actions with the same controller that processed the request. #4625 *sd@notso.net*
-
-* rails -d frontbase to create a new project with a frontbase database.yml. #4945 *mlaster@metavillage.com*
-
-* Ensure the logger is initialized. #5629 *mike@clarkware.com*
-
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
-
- spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
- spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
-
- Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
-
-* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 *evan@protest.net*
-
-* db:test:clone should remove existing tables before reloading the schema. #5607 *sveit@tradeharbor.com*
-
-* Fixed migration generation for class names like ACLController #5197 *brad@madriska.com*
-
-* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
-
- irb(#<TopController:0x40822a68>):002:0> show_source_list
- 0001 class TopController < ApplicationController
- 0002 def show
- 0003-> breakpoint
- 0004 end
- 0005
- 0006 def index
- 0007 end
- 0008
- => "/path/to/rails/root/app/controllers/top_controller.rb"
-
- irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- app/controllers/top_controller.rb:3:in `show'
- => "/path/to/rails/root/app/controllers/top_controller.rb:3"
-
-* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 *nils@alumni.rice.edu*
-
-* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 *mike@clarkware.com*
-
-* Don't assume Active Record is available. #5497 *bob@sporkmonger.com*
-
-* Mongrel: script/server works on Win32. #5499 *jeremydurham@gmail.com*
-
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. *Nick Sieger*
-
-* Mongrel support for script/server. #5475 *jeremydurham@gmail.com*
-
-* Fix script/plugin so it doesn't barf on invalid URLs *Rick Olson*
-
-* Fix plugin install bug at dir with space. (closes #5359) *Yoshimasa NIWA*
-
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. *Rick Olson*
-
-* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 *takiuchi@drecom.co.jp*
-
-* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 *elliot@townx.org*
-
-* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. *Jamis Buck*
-
-* Make "script/plugin install" work with svn+ssh URLs. *Sam Stephenson*
-
-* Added lib/ to the directories that will get application docs generated *David Heinemeier Hansson*
-
-* Add observer generator. Closes #5167. *François Beausoleil*
-
-* Session migration generator obeys pluralize_table_names. #5145 *James Adam*
-
-* rake test:recent understands subdirectories. #2925 *jerrett@bravenet.com*
-
-* The app generator detects the XAMPP package's MySQL socket location. #3832 *elliot@townx.org*
-
-* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 *rcoder, rails-bug@owl.me.uk*
-
-* Distinguish the spawners for different processes *David Heinemeier Hansson*
-
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) *David Heinemeier Hansson*
-
-* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) *Julian Tarkhanov*
-
-* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
-
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids *David Heinemeier Hansson*
-
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids *David Heinemeier Hansson*
-
-
-## 1.2.3 (March 12th, 2007) ##
-
-* Ruby 1.8.6 compatibility
-
-* Windows: include MinGW in RUBY_PLATFORM check. #2982 *okkez000@gmail.com, Kaspar Schiess*
-
-* Stop swallowing errors during rake test *Michael Koziarski*
-
-
-## 1.2.2 (February 5th, 2007) ##
-
-* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ *Chad Fowler*
-
-* Require the dispatcher for Rails::Configuration#to_prepare. *Rick Olson*
-
-
-## 1.2.1 (January 16th, 2007) ##
-
-* Updated to Active Record 1.15.1, Action Pack 1.13.1, Action Mailer 1.3.1, Action Web Service 1.2.1
-
-
-## 1.2.0 (January 16th, 2007) ##
-
-* Update to Prototype 1.5.0. *Sam Stephenson*
-
-* Generator: use destination path for diff tempfiles. #7015 *alfeld*
-
-* Fixed that webrick would strip leading newlines and hang connection #4156 *psross*
-
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. *Rick Olson*
- If you really want your plugins to reload, add this to the very top of init.rb:
-
- Dependencies.load_once_paths.delete(lib_path)
-
-* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 *fearoffish*
-
-* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 *Rick Olson*
-
-* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. *James Adam*
-
-* Don't generate a components directory in new Rails apps. *Jeremy Kemper*
-
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) *David Heinemeier Hansson*
-
-* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 *David Heinemeier Hansson*
-
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment *David Heinemeier Hansson*
-
-* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. *Nicholas Seckar*
-
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) *David Heinemeier Hansson*
-
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available *David Heinemeier Hansson*
-
-* Update to Prototype and script.aculo.us [5579]. *Sam Stephenson, Thomas Fuchs*
-
-* Made script/server work with -e and -d when using Mongrel *David Heinemeier Hansson*
-
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action *Tobias Lütke*
-
-* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 *fearoffish*
-
-* Add grep-based fallback to reaper, to work in pidless setups *Jamis Buck*
-
-* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. *Jeremy Kemper*
-
-* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. *Nicholas Seckar*
-
-* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 *jchris*
-
-* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 *Josh Susser*
-
-* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 *jeffw, Jeremy Kemper*
-
-* Generated directories are recursively svn added, like mkdir -p. #6416 *NeilW*
-
-* resource and scaffold_resource generators add a restful route to config/routes.rb *Jeremy Kemper*
-
-* Revert environment changes for autoload_paths. *Michael Koziarski*
-
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests *Michael Koziarski*
-
-* Added option to script/process/spawner of specifying the binding address #5133 *Dee Zsombor*
-
-* Update environment.rb comments to include config.autoload_paths. Closes #6478 *caio*
-
-* Update scaffold to use new form_tag block functionality. Closes #6480. *Bob Silva*
-
-* Plugin generator: check for class collisions. #4833 *vinbarnes@gmail.com*
-
-* Mailer generator: handle mailers in modules, set mime_version in unit test. *Jeremy Kemper*
-
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. *Michael Koziarski*
-
-* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
-
- config.plugins = %w[ routing_navigator simply_helpful ]
-
-* Clean up html on included error pages. *Tim Lucas*
-
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language *David Heinemeier Hansson*
-
-* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
-
-* PostgreSQL: db:test:purge closes open database connections first. #6236 *alex*
-
-* Fixed test:uncommitted on Windows (backslash issue) #4999 *paul@paulbutcher.com*
-
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 *Bob Silva*
-
-* Fixed rename_table on SQLite tables with indexes defined #5942 *brandon@opensoul.org*
-
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations *David Heinemeier Hansson*
-
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
-
- ./script/generate model post title:string created_on:date body:text published:boolean
-
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined *David Heinemeier Hansson*
-
-* script/runner can run files, pass on arguments, and be used as a shebang. #6286 *Tuxie, dlpond*
- #!/usr/bin/env /path/to/my/app/script/runner
- # Example: just start using your models as if you are in script/console
- Product.find(:all).each { |product| product.check_inventory }
-
-* Look for rake tasks in plugin subdirs. #6259 *obrie*
-
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb *David Heinemeier Hansson*
-
-* session_migration generator adds an index on updated_at. #6207 *grg*
-
-* script/server creates the tmp/pids directory. #6204 *jonathan*
-
-* Fix script/console --sandbox for internal transactions changes. #5738 *Chris McGrath, charles.gerungan@gmail.com*
-
-* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
- documented in initializer.rb, the workaround is:
-
- config.autoload_paths += Dir*RAILS_ROOT + '/app/models/*/'*
-
- References #6031. *Nicholas Seckar*
-
-* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
-
-* Formally Deprecate the old rake tasks. *Michael Koziarski*
-
-* Thoroughly test the FCGI dispatcher. #5970 *Kevin Clark*
-
-* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. *Rick Olson*
-
-* Tighten rescue clauses. #5985 *james@grayproductions.net*
-
-* Cleaning up tests. *Kevin Clark, Jeremy Kemper*
-
-* Add Dependencies.load_once_paths. *Nicholas Seckar*
-
-* Assign Routing.controller_paths; fix script/about and rails info controller. *Nicholas Seckar*
-
-* Don't warn dispatcher of Reloadable deprecations. *Nicholas Seckar*
-
-* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base *Rick Olson*
-
- ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
- ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
-
-* Add missing mock directories from the autoload_paths configuration. *Rick Olson*
-
-* Nested controller scaffolding also nests the generated layout. *iain d broadfoot*
-
-* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. *Nicholas Seckar*
-
-* Add autoload_paths support to Initializer. *Nicholas Seckar*
-
-* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. *Rick Olson*
-
-* Clarify usage of script/plugin source. Closes #5344. *James Adam*
-
-* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. *Nicholas Seckar*
-
-* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. *Rick Olson*
-
-* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 *mats@imediatec.co.uk*
-
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 *Shugo Maeda*
-
-* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. *Rick Olson*
-
-* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. *Jamis Buck*
-
-* Fix script/plugin about so it uses about.yml and not meta.yml. *James Adam*
-
-* Dispatcher processes rescued actions with the same controller that processed the request. #4625 *sd@notso.net*
-
-* rails -d frontbase to create a new project with a frontbase database.yml. #4945 *mlaster@metavillage.com*
-
-* Ensure the logger is initialized. #5629 *mike@clarkware.com*
-
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
-
- spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
- spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
-
- Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
-
-* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 *evan@protest.net*
-
-* db:test:clone should remove existing tables before reloading the schema. #5607 *sveit@tradeharbor.com*
-
-* Fixed migration generation for class names like ACLController #5197 *brad@madriska.com*
-
-* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
-
- irb(#<TopController:0x40822a68>):002:0> show_source_list
- 0001 class TopController < ApplicationController
- 0002 def show
- 0003-> breakpoint
- 0004 end
- 0005
- 0006 def index
- 0007 end
- 0008
- => "/path/to/rails/root/app/controllers/top_controller.rb"
-
- irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- app/controllers/top_controller.rb:3:in `show'
- => "/path/to/rails/root/app/controllers/top_controller.rb:3"
-
-* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 *nils@alumni.rice.edu*
-
-* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 *mike@clarkware.com*
-
-* Don't assume Active Record is available. #5497 *bob@sporkmonger.com*
-
-* Mongrel: script/server works on Win32. #5499 *jeremydurham@gmail.com*
-
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. *Nick Sieger*
-
-* Mongrel support for script/server. #5475 *jeremydurham@gmail.com*
-
-* Fix script/plugin so it doesn't barf on invalid URLs *Rick Olson*
-
-* Fix plugin install bug at dir with space. (closes #5359) *Yoshimasa NIWA*
-
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. *Rick Olson*
-
-* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 *takiuchi@drecom.co.jp*
-
-* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 *elliot@townx.org*
-
-* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. *Jamis Buck*
-
-* Make "script/plugin install" work with svn+ssh URLs. *Sam Stephenson*
-
-* Added lib/ to the directories that will get application docs generated *David Heinemeier Hansson*
-
-* Add observer generator. Closes #5167. *François Beausoleil*
-
-* Session migration generator obeys pluralize_table_names. #5145 *James Adam*
-
-* rake test:recent understands subdirectories. #2925 *jerrett@bravenet.com*
-
-* The app generator detects the XAMPP package's MySQL socket location. #3832 *elliot@townx.org*
-
-* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 *rcoder, rails-bug@owl.me.uk*
-
-* Distinguish the spawners for different processes *David Heinemeier Hansson*
-
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) *David Heinemeier Hansson*
-
-* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) *Julian Tarkhanov*
-
-* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
-
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids *David Heinemeier Hansson*
-
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids *David Heinemeier Hansson*
-
-
-## 1.1.6 (August 10th, 2006) ##
-
-* Additional security patch
-
-
-## 1.1.5 (August 8th, 2006) ##
-
-* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. #4857 *Alisdair McDiarmid*
-
-* Change the scaffolding layout to use yield rather than @content_for_layout. *Marcel Molina Jr.*
-
-* Includes critical security patch
-
-
-## 1.1.4 (June 29th, 2006) ##
-
-* Remove use of opts.on { |options[:name] } style hash assignment. References #4440. *headius@headius.com*
-
-* Updated to Action Pack 1.12.3, ActionWebService 1.1.4, ActionMailer 1.2.3
-
-
-## 1.1.3 (June 27th, 2006) ##
-
-* Updated to Active Record 1.14.3, Action Pack 1.12.2, ActionWebService 1.1.3, ActionMailer 1.2.2
-
-
-## 1.1.2 (April 9th, 2006) ##
-
-* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. Closes #4857. *Alisdair McDiarmid*
-
-* Change the scaffolding layout to use yield rather than @content_for_layout. *Marcel Molina Jr.*
-
-* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) *David Heinemeier Hansson*
-
-* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem *David Heinemeier Hansson*
-
-
-## 1.1.1 (April 6th, 2006) ##
-
-* Enhances plugin#discover allowing it to discover svn:// like URIs (closes #4565) *ruben.nine@gmail.com*
-
-* Update to Prototype 1.5.0_rc0 *Sam Stephenson*
-
-* Fixed that the -r/--ruby path option of the rails command was not being respected #4549 *ryan.raaum@gmail.com*
-
-* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html *David Heinemeier Hansson*
-
-* Fixed that rake clone_structure_to_test should quit on pgsql if the dump is unsuccesful #4585 *augustz@augustz.com*
-
-* Fixed that rails --version should have the return code of 0 (success) #4560 *blair@orcaware.com*
-
-* Install alias so Rails::InfoController is accessible at /rails_info. Closes #4546. *Nicholas Seckar*
-
-* Fixed that spawner should daemonize if running in repeat mode *David Heinemeier Hansson*
-
-* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release *David Heinemeier Hansson*
-
-* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us *Sam Stephenson, Thomas Fuchs*
-
-* Use --simple-prompt instead of --prompt-mode simple for console compatibility with Windows/Ruby 1.8.2 #4532 *starr@starrnhorne.com*
-
-* Make Rails::VERSION implicitly loadable #4491. *Nicholas Seckar*
-
-* Fixed rake rails:freeze:gems #4518 *benji@silverinsanity.com*
-
-* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with *David Heinemeier Hansson*
-
-* Added gem binding of apps generated through the rails command to the gems of they were generated with *Nicholas Seckar*
-
-* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf *David Heinemeier Hansson*
-
-* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf *David Heinemeier Hansson*
-
-* Avoid passing escapeHTML non-string in Rails' info controller *Nicholas Seckar*
-
-
-## 1.1.0 (March 27th, 2006) ##
-
-* Allow db:fixtures:load to load a subset of the applications fixtures. *Chad Fowler*
-
- ex.
-
- rake db:fixtures:load FIXTURES=customers,plans
-
-* Update to Prototype 1.5.0_pre1 *Sam Stephenson*
-
-* Update to script.aculo.us 1.6 *Thomas Fuchs*
-
-* Add an integration_test generator *Jamis Buck*
-
-* Make all ActionView helpers available in the console from the helper method for debugging purposes. n.b.: Only an 80% solution. Some stuff won't work, most will. *Marcel Molina Jr.*
-
- ex.
-
- >> puts helper.options_for_select([%w(a 1), %w(b 2), %w(c 3)])
- <option value="1">a</option>
- <option value="2">b</option>
- <option value="3">c</option>
- => nil
-
-* Replaced old session rake tasks with db:sessions:create to generate a migration, and db:sessions:clear to remove sessions. *Rick Olson*
-
-* Reject Ruby 1.8.3 when loading Rails; extract version checking code. *Chad Fowler*
-
-* Remove explicit loading of RailsInfo and RailsInfoController. *Nicholas Seckar*
-
-* Move RailsInfo and RailsInfoController to Rails::Info and Rails::InfoController. *Nicholas Seckar*
-
-* Extend load path with Railties' builtin directory to make adding support code easy. *Nicholas Seckar*
-
-* Fix the rails_info controller by explicitly loading it, and marking it as not reloadable. *Nicholas Seckar*
-
-* Fixed rails:freeze:gems for Windows #3274 *paul@paulbutcher.com*
-
-* Added 'port open?' check to the spawner when running in repeat mode so we don't needlessly boot the dispatcher if the port is already in use anyway #4089 *guy.naor@famundo.com*
-
-* Add verification to generated scaffolds, don't allow get for unsafe actions *Michael Koziarski*
-
-* Don't replace application.js in public/javascripts if it already exists *Cody Fauser*
-
-* Change test:uncommitted to delay execution of `svn status` by using internal Rake API's. *Nicholas Seckar*
-
-* Use require_library_or_gem to load rake in commands/server.rb. Closes #4205. *rob.rasmussen@gmail.com*
-
-* Use the Rake API instead of shelling out to create the tmp directory in commands/server.rb. *Chad Fowler*
-
-* Added a backtrace to the evil WSOD (White Screen of Death). Closes #4073. TODO: Clearer exceptions *Rick Olson*
-
-* Added tracking of database and framework versions in script/about #4088 *charles.gerungan@gmail.com/Rick Olson*
-
-* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults *David Heinemeier Hansson*
-
-* Added socket cleanup for lighttpd, both before and after *David Heinemeier Hansson*
-
-* Added automatic creation of tmp/ when running script/server *David Heinemeier Hansson*
-
-* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process *David Heinemeier Hansson*
-
-* Added reload! method to script/console to reload all models and others that include Reloadable without quitting the console #4056 *esad@esse.at*
-
-* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 *David Heinemeier Hansson*
-
-* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 *Thijs van der Vossen*
-
-* Added test:uncommitted to test changes since last checkin to Subversion #4035 *technomancy@gmail.com*
-
-* Help script/about print the correct svn revision when in a non-English locale. #4026 *babie7a0@ybb.ne.jp*
-
-* Add 'app' accessor to script/console as an instance of Integration::Session *Jamis Buck*
-
-* Generator::Base#usage takes an optional message argument which defaults to Generator::Base#usage_message. *Jeremy Kemper*
-
-* Remove the extraneous AR::Base.threaded_connections setting from the webrick server. *Jeremy Kemper*
-
-* Add integration test support to app generation and testing *Jamis Buck*
-
-* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though *David Heinemeier Hansson*
-
-* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! *David Heinemeier Hansson*
-
-* Added -r/--repeat option to script/process/spawner that offers the same loop protection as the spinner did. This deprecates the script/process/spinner, so it's no longer included in the default Rails skeleton, but still available for backwards compatibility #3461 *ror@andreas-s.net*
-
-* Added collision option to template generation in generators #3329 [anna@wota.jp]. Examples:
-
- m.template "stuff.config" , "config/stuff.config" , :collision => :skip
- m.template "auto-stamping", "config/generator.log", :collision => :force
-
-* Added more information to script/plugin's doings to ease debugging #3755 *Rick Olson*
-
-* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets *David Heinemeier Hansson*
-
-* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration *David Heinemeier Hansson*
-
-* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) *David Heinemeier Hansson*
-
-* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton *David Heinemeier Hansson*
-
-* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration *David Heinemeier Hansson*
-
-* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration *David Heinemeier Hansson*
-
-* Allow script/server -c /path/to/lighttpd.conf *Jeremy Kemper*
-
-* Remove hardcoded path to reaper script in script/server *Jeremy Kemper*
-
-* Update script.aculo.us to V1.5.3 *Thomas Fuchs*
-
-* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things *David Heinemeier Hansson*
-
-* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. *David Heinemeier Hansson*
-
-* Added Configuration#after_initialize for registering a block which gets called after the framework is fully initialized. Useful for things like per-environment configuration of plugins. *Michael Koziarski*
-
-* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. *David Heinemeier Hansson*
-
-* Fixed that static requests could unlock the mutex guarding dynamic requests in the WEBrick servlet #3433 *tom@craz8.com*
-
-* Fixed documentation tasks to work with Rake 0.7.0 #3563 *kazuhiko@fdiary.net*
-
-* Update to Prototype 1.5.0_pre0 *Sam Stephenson*
-
-* Sort the list of plugins so we load in a consistent order *Rick Olson*
-
-* Show usage when script/plugin is called without arguments *tom@craz8.com*
-
-* Corrected problems with plugin loader where plugins set 'name' incorrectly #3297 *anna@wota.jp*
-
-* Make migration generator only report on exact duplicate names, not partial dupliate names. #3442 *jeremy@planetargon.com Marcel Molina Jr.*
-
-* Fix typo in mailer generator USAGE. #3458 *chriztian.steinmeier@gmail.com*
-
-* Ignore version mismatch between pg_dump and the database server. #3457 *Simon Stapleton*
-
-* Reap FCGI processes after lighttpd exits. *Sam Stephenson*
-
-* Honor ActiveRecord::Base.pluralize_table_names when creating and destroying session store table. #3204. *rails@bencurtis.com, Marcel Molina Jr.*
-
-## 1.0.0 (December 13th, 2005) ##
-
-* Update instructions on how to find and install generators. #3172. *Chad Fowler*
-
-* Generator looks in vendor/generators also. *Chad Fowler*
-
-* Generator copies files in binary mode. #3156 *minimudboy@gmail.com*
-
-* Add builtin/ to the gemspec. Closes #3047. *Nicholas Seckar, Sam Stephenson*
-
-* Add install.rb file to plugin generation which is loaded, if it exists, when you install a plugin. *Marcel Molina Jr.*
-
-* Run initialize_logger in script/lighttpd to ensure the log file exists before tailing it. *Sam Stephenson*
-
-* Make load_fixtures include csv fixtures. #3053. *me@mdaines.com*
-
-* Fix freeze_gems so that the latest rails version is dumped by default. *Nicholas Seckar*
-
-* script/plugin: handle root paths and plugin names which contain spaces. #2995 *justin@aspect.net*
-
-* Model generator: correct relative path to test_helper in unit test. *Jeremy Kemper*
-
-* Make the db_schema_dump task honor the SCHEMA environment variable if present the way db_schema_import does. #2931. *Blair Zajac*
-
-* Have the lighttpd server script report the actual ip to which the server is bound. #2903. *Adam*
-
-* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. *James Adam*
-
-* Make help for the console command more explicit about how to specify the desired environment in which to run the console. #2911. *anonymous*
-
-* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 *Dreamer3*
-
-* Introducing the session_migration generator. Creates an add_session_table migration. Allows generator to specify migrations directory. #2958, #2960 *Rick Olson*
-
-* script/console uses RAILS_ENV environment variable if present. #2932 [Blair Zajac <blair@orcaware.com>
-
-* Windows: eliminate the socket option in database.yml. #2924 *Wayne Vucenic <waynev@gmail.com>*
-
-* Eliminate nil from newly generated logfiles. #2927 *Blair Zajac <blair@orcaware.com>*
-
-* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
-
-* Eliminate Subversion dependencies in scripts/plugin. Correct install options. Introduce --force option to reinstall a plugin. Remove useless --long option for list. Use --quiet to quiet the download output and --revision to update to a specific svn revision. #2842 *Chad Fowler, Rick Olson*
-
-* SQLite: the clone_structure_to_test and purge_test_database Rake tasks should always use the test environment. #2846 *Rick Olson*
-
-* Make sure that legacy db tasks also reference :database for SQLite #2830 *kazuhiko@fdiary.net*
-
-* Pass __FILE__ when evaluating plugins' init.rb. #2817 *James Adam*
-
-* Better svn status matching for generators. #2814 *François Beausoleil <francois.beausoleil@gmail.com>, Blair Zajac <blair@orcaware.com>*
-
-* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities *David Heinemeier Hansson*
-
-* Don't detach or fork for script/server tailing *Nicholas Seckar*
-
-* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path *David Heinemeier Hansson*
-
-* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [David Heinemeier Hansson] #2660
-
-* Correct versioning in :freeze_gems Rake task. #2778 *Jakob Skjerning, Jeremy Kemper*
-
-* Added an omnipresent RailsInfoController with a properties action that delivers an HTML rendering of Rails::Info (but only when local_request? is true). Added a new default index.html which fetches this with Ajax. *Sam Stephenson*
-
-
-## 0.14.3 (RC4) (November 7th, 2005) ##
-
-## Add 'add_new_scripts' rake task for adding new rails scripts to script/ Jamis Buck ##
-
-* Remove bogus hyphen from script/process/reaper calls to 'ps'. #2767 *anonymous*
-
-* Copy lighttpd.conf when it is first needed, instead of on app creation *Jamis Buck*
-
-* Use require_library_or_gem 'fcgi' in script/server *Sam Stephenson*
-
-* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' *David Heinemeier Hansson*
-
-* New configuration option config.plugin_paths which may be a single path like the default 'vendor/plugins' or an array of paths: ['vendor/plugins', 'lib/plugins']. *Jeremy Kemper*
-
-* Plugins are discovered in nested paths, so you can organize your plugins directory as you like. *Jeremy Kemper*
-
-* Refactor load_plugin from load_plugins. #2757 *alex.r.moon@gmail.com*
-
-* Make use of silence_stderr in script/lighttpd, script/plugin, and Rails::Info *Sam Stephenson*
-
-* Enable HTTP installation of plugins when svn isn't avaialable. Closes #2661. *Chad Fowler*
-
-* Added script/about to display formatted Rails::Info output *Sam Stephenson*
-
-* Added Rails::Info to catalog assorted information about a Rails application's environment *Sam Stephenson*
-
-* Tail the logfile when running script/server lighttpd in the foreground *Sam Stephenson*
-
-* Try to guess the port number from config/lighttpd.conf in script/server lighttpd *Sam Stephenson*
-
-* Don't reap spawn-fcgi. #2727 *matthew@walker.wattle.id.au*
-
-* Reaper knows how to find processes even if the dispatch path is very long. #2711 *matthew@walker.wattle.id.au*
-
-* Make fcgi handler respond to TERM signals with an explicit exit *Jamis Buck*
-
-* Added demonstration of fixture use to the test case generated by the model generator *David Heinemeier Hansson*
-
-* If specified, pass PostgreSQL client character encoding to createdb. #2703 *Kazuhiko <kazuhiko@fdiary.net>*
-
-* Catch CGI multipart parse errors. Wrap dispatcher internals in a failsafe response handler. *Jeremy Kemper*
-
-* The freeze_gems Rake task accepts the VERSION environment variable to decide which version of Rails to pull into vendor/rails. *Chad Fowler, Jeremy Kemper*
-
-* Removed script.aculo.us.js, builder.js and slider.js (preperation for move of scriptaculous extensions to plugins, core scriptaculous will remain in Railties) *Thomas Fuchs*
-
-* The freeze_edge Rake task does smarter svn detection and can export a specific revision by passing the REVISION environment variable. For example: rake freeze_edge REVISION=1234. #2663 *Rick Olson*
-
-* Comment database.yml and include PostgreSQL and SQLite examples. *Jeremy Kemper*
-
-* Improve script/plugin on Windows. #2646 *Chad Fowler*
-
-* The *_plugindoc Rake tasks look deeper into the plugins' lib directories. #2652 *bellis@deepthought.org*
-
-* The PostgreSQL :db_structure_dump Rake task limits its dump to the schema search path in database.yml. *Anatol Pomozov <anatol.pomozov@gmail.com>*
-
-* Add task to generate rdoc for all installed plugins. *Marcel Molina Jr.*
-
-* Update script.aculo.us to V1.5_rc4 *Thomas Fuchs*
-
-* Add default Mac + DarwinPorts MySQL socket locations to the app generator. *Jeremy Kemper*
-
-* Migrations may be destroyed: script/destroy migration foo. #2635 *Charles M. Gerungan <charles.gerungan@gmail.com>, Jamis Buck, Jeremy Kemper*
-
-* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator *David Heinemeier Hansson*
-
-* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service *David Heinemeier Hansson*
-
-* Added script/plugin to manage plugins (install, remove, list, etc) *Ryan Tomayko*
-
-* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) *David Heinemeier Hansson*
-
-* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) *David Heinemeier Hansson*
-
-* Fixed scaffold generator when started with only 1 parameter #2609 *self@mattmower.com*
-
-* rake should run functional tests even if the unit tests have failures *Jim Weirich*
-
-* Back off cleanpath to be symlink friendly. Closes #2533 *Nicholas Seckar*
-
-* Load rake task files in alphabetical order so you can build dependencies and count on them #2554 *Blair Zajac*
-
-
-## 0.14.2 (RC3) (October 26th, 2005) ##
-
-* Constants set in the development/test/production environment file are set in Object
-
-* Scaffold generator pays attention to the controller name. #2562 *self@mattmower.com*
-
-* Include tasks from vendor/plugins/*/tasks in the Rakefile #2545 *Rick Olson*
-
-
-## 0.14.1 (RC2) (October 19th, 2005) ##
-
-* Don't clean RAILS_ROOT on windows
-
-* Remove trailing '/' from RAILS_ROOT *Nicholas Seckar*
-
-* Upgraded to Active Record 1.12.1 and Action Pack 1.10.1
-
-
-## 0.14.0 (RC1) (October 16th, 2005) ##
-
-* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators *Tobias Lütke*
-
-* Fix rake dev and related commands *Nicholas Seckar*
-
-* The rails command tries to deduce your MySQL socket by running `mysql_config
- --socket`. If it fails, default to /path/to/your/mysql.sock
-
-* Made the rails command use the application name for database names in the tailored database.yml file. Example: "rails ~/projects/blog" will use "blog_development" instead of "rails_development". *Florian Weber*
-
-* Added Rails framework freezing tasks: freeze_gems (freeze to current gems), freeze_edge (freeze to Rails SVN trunk), unfreeze_rails (float with newest gems on system)
-
-* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. *Tobias Lütke*
-
-* Added cleaning of RAILS_ROOT to useless elements such as '../non-dot-dot/'. Provides cleaner backtraces and error messages. *Nicholas Seckar*
-
-* Made the instantiated/transactional fixtures settings be controlled through Rails::Initializer. Transactional and non-instantiated fixtures are default from now on. *Florian Weber*
-
-* Support using different database adapters for development and test with ActiveRecord::Base.schema_format = :ruby *Sam Stephenson*
-
-* Make webrick work with session(:off)
-
-* Add --version, -v option to the Rails command. Closes #1840. *stancell*
-
-* Update Prototype to V1.4.0_pre11, script.aculo.us to V1.5_rc3 [2504] and fix the rails generator to include the new .js files *Thomas Fuchs*
-
-* Make the generator skip a file if it already exists and is identical to the new file.
-
-* Add experimental plugin support #2335
-
-* Made Rakefile aware of new .js files in script.aculo.us *Thomas Fuchs*
-
-* Make table_name and controller_name in generators honor AR::Base.pluralize_table_names. #1216 #2213 *kazuhiko@fdiary.net*
-
-* Clearly label functional and unit tests in rake stats output. #2297 *lasse.koskela@gmail.com*
-
-* Make the migration generator only check files ending in *.rb when calculating the next file name #2317 *Chad Fowler*
-
-* Added prevention of duplicate migrations from the generator #2240 *François Beausoleil*
-
-* Add db_schema_dump and db_schema_import rake tasks to work with the new ActiveRecord::SchemaDumper (for dumping a schema to and reading a schema from a ruby file).
-
-* Reformed all the config/environments/* files to conform to the new Rails::Configuration approach. Fully backwards compatible.
-
-* Added create_sessions_table, drop_sessions_table, and purge_sessions_table as rake tasks for databases that supports migrations (MySQL, PostgreSQL, SQLite) to get a table for use with CGI::Session::ActiveRecordStore
-
-* Added dump of schema version to the db_structure_dump task for databases that support migrations #1835 *Rick Olson*
-
-* Fixed script/profiler for Ruby 1.8.2 #1863 *Rick Olson*
-
-* Fixed clone_structure_to_test task for SQLite #1864 *jon@burningbush.us*
-
-* Added -m/--mime-types option to the WEBrick server, so you can specify a Apache-style mime.types file to load #2059 *ask@develooper.com*
-
-* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 *Kevin Clark*
-
-* Added -c/--charset option to WEBrick server, so you can specify a default charset (which without changes is UTF-8) #2084 *wejn@box.cz*
-
-* Make the default stats task extendable by modifying the STATS_DIRECTORIES constant
-
-* Allow the selected environment to define RAILS_DEFAULT_LOGGER, and have Rails::Initializer use it if it exists.
-
-* Moved all the shared tasks from Rakefile into Rails, so that the Rakefile is empty and doesn't require updating.
-
-* Added Rails::Initializer and Rails::Configuration to abstract all of the common setup out of config/environment.rb (uses config/boot.rb to bootstrap the initializer and paths)
-
-* Fixed the scaffold generator to fail right away if the database isn't accessible instead of in mid-air #1169 *Chad Fowler*
-
-* Corrected project-local generator location in scripts.rb #2010 *Michael Schuerig*
-
-* Don't require the environment just to clear the logs #2093 *Scott Barron*
-
-* Make the default rakefile read *.rake files from config/tasks (for easy extension of the rakefile by e.g. generators)
-
-* Only load breakpoint in development mode and when BREAKPOINT_SERVER_PORT is defined.
-
-* Allow the --toggle-spin switch on process/reaper to be negated
-
-* Replace render_partial with render :partial in scaffold generator *Nicholas Seckar*
-
-* Added -w flag to ps in process/reaper #1934 *Scott Barron*
-
-* Allow ERb in the database.yml file (just like with fixtures), so you can pull out the database configuration in environment variables #1822 *Duane Johnson*
-
-* Added convenience controls for FCGI processes (especially when managed remotely): spinner, spawner, and reaper. They reside in script/process. More details can be had by calling them with -h/--help.
-
-* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 *Marcel Molina Jr.*
-
-* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 *Michael Schubert*
-
-* Dropped the 'immediate close-down' of FCGI processes since it didn't work consistently and produced bad responses when it didn't. So now a TERM ensures exit after the next request (just as if the process is handling a request when it receives the signal). This means that you'll have to 'nudge' all FCGI processes with a request in order to ensure that they have all reloaded. This can be done by something like ./script/process/repear --nudge 'http://www.myapp.com' --instances 10, which will load the myapp site 10 times (and thus hit all of the 10 FCGI processes once, enough to shut down).
-
-
-## 0.13.1 (11 July, 2005) ##
-
-* Look for app-specific generators in RAILS_ROOT/generators rather than the clunky old RAILS_ROOT/script/generators. Nobody really uses this feature except for the unit tests, so it's a negligible-impact change. If you want to work with third-party generators, drop them in ~/.rails/generators or simply install gems.
-
-* Fixed that each request with the WEBrick adapter would open a new database connection #1685 *Sam Stephenson*
-
-* Added support for SQL Server in the database rake tasks #1652 [Ken Barker] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
-
-* Added a VERSION parameter to the migrate task that allows you to do "rake migrate VERSION=34" to migrate to the 34th version traveling up or down depending on the current version
-
-* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 *court3nay*
-
-* Improved documentation for environment config files #1625 *court3nay*
-
-
-## 0.13.0 (6 July, 2005) ##
-
-* Changed the default logging level in config/environment.rb to INFO for production (so SQL statements won't be logged)
-
-* Added migration generator: ./script/generate migration add_system_settings
-
-* Added "migrate" as rake task to execute all the pending migrations from db/migrate
-
-* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 *Marcel Molina Jr.*
-
-* Added a DOCTYPE of HTML transitional to the HTML files generated by Rails #1124 *Michael Koziarski*
-
-* SIGTERM also gracefully exits dispatch.fcgi. Ignore SIGUSR1 on Windows.
-
-* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi *Stefan Kaes*
-
-* Allow dynamic application reloading for dispatch.fcgi processes by sending a SIGHUP. If the process is currently handling a request, the request will be allowed to complete first. This allows production fcgi's to be reloaded without having to restart them.
-
-* RailsFCGIHandler (dispatch.fcgi) no longer tries to explicitly flush $stdout (CgiProcess#out always calls flush)
-
-* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 *Michael Schubert*
-
-* ActionMailer::Base subclasses are reloaded with the other rails components #1262
-
-* Made the WEBrick adapter not use a mutex around action performance if ActionController::Base.allow_concurrency is true (default is false)
-
-* Fixed that mailer generator generated fixtures/plural while units expected fixtures/singular #1457 *Scott Barron*
-
-* Added a 'whiny nil' that's aim to ensure that when users pass nil to methods where that isn't appropriate, instead of NoMethodError? and the name of some method used by the framework users will see a message explaining what type of object was expected. Only active in test and development environments by default #1209 *Michael Koziarski*
-
-* Fixed the test_helper.rb to be safe for requiring controllers from multiple spots, like app/controllers/article_controller.rb and app/controllers/admin/article_controller.rb, without reloading the environment twice #1390 *Nicholas Seckar*
-
-* Fixed Webrick to escape + characters in URL's the same way that lighttpd and apache do #1397 *Nicholas Seckar*
-
-* Added -e/--environment option to script/runner #1408 *François Beausoleil*
-
-* Modernize the scaffold generator to use the simplified render and test methods and to change style from @params["id"] to params[:id]. #1367
-
-* Added graceful exit from pressing CTRL-C during the run of the rails command #1150 *Caleb Tennis*
-
-* Allow graceful exits for dispatch.fcgi processes by sending a SIGUSR1. If the process is currently handling a request, the request will be allowed to complete and then will terminate itself. If a request is not being handled, the process is terminated immediately (via #exit). This basically works like restart graceful on Apache. *Jamis Buck*
-
-* Made dispatch.fcgi more robust by catching fluke errors and retrying unless its a permanent condition. *Jamis Buck*
-
-* Added console --profile for profiling an IRB session #1154 *Jeremy Kemper*
-
-* Changed console_sandbox into console --sandbox #1154 *Jeremy Kemper*
-
-
-## 0.12.1 (20th April, 2005) ##
-
-* Upgraded to Active Record 1.10.1, Action Pack 1.8.1, Action Mailer 0.9.1, Action Web Service 0.7.1
-
-
-## 0.12.0 (19th April, 2005) ##
-
-* Fixed that purge_test_database would use database settings from the development environment when recreating the test database #1122 *rails@cogentdude.com*
-
-* Added script/benchmarker to easily benchmark one or more statement a number of times from within the environment. Examples:
-
- # runs the one statement 10 times
- script/benchmarker 10 'Person.expensive_method(10)'
-
- # pits the two statements against each other with 50 runs each
- script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
-
-* Added script/profiler to easily profile a single statement from within the environment. Examples:
-
- script/profiler 'Person.expensive_method(10)'
- script/profiler 'Person.expensive_method(10)' 10 # runs the statement 10 times
-
-* Added Rake target clear_logs that'll truncate all the *.log files in log/ to zero #1079 *Lucas Carlson*
-
-* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 *k@v2studio.com*
-
-* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 *pburleson*
-
-* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
-
-
-## 0.11.1 (27th March, 2005) ##
-
-* Fixed the dispatch.fcgi use of a logger
-
-* Upgraded to Active Record 1.9.1, Action Pack 1.7.0, Action Mailer 0.8.1, Action Web Service 0.6.2, Active Support 1.0.3
-
-
-## 0.11.0 (22th March, 2005) ##
-
-* Removed SCRIPT_NAME from the WEBrick environment to prevent conflicts with PATH_INFO #896 *Nicholas Seckar*
-
-* Removed ?$1 from the dispatch.f/cgi redirect line to get rid of 'complete/path/from/request.html' => nil being in the @params now that the ENV["REQUEST_URI"] is used to determine the path #895 *dblack/Nicholas Seckar*
-
-* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
-
-* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 *Tobias Lütke*
-
-* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 *Nicholas Seckar*
-
-* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 *Nicholas Seckar/Tobias Lütke*
-
-* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
-
- ./script/runner 'ReminderService.deliver'
- ./script/runner 'Mailer.receive(STDIN.read)'
-
- This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
-
-* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 *dave@cherryville.org*
-
-* Fixed the Rakefile's interaction with postgresql to:
-
- 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
- passwords when connecting to a remote db and local socket connections.
- 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
- 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
- 4. Use the port if available #875 [madrobby]
-
-* Upgraded to Active Record 1.9.0, Action Pack 1.6.0, Action Mailer 0.8.0, Action Web Service 0.6.1, Active Support 1.0.2
-
-
-## 0.10.1 (7th March, 2005) ##
-
-* Fixed rake stats to ignore editor backup files like model.rb~ #791 *Sebastian Kanthak*
-
-* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 *Tobias Lütke*
-
-* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
-
-* Fixed that scaffold generator new template should use local variable instead of instance variable #778 *Dan Peterson*
-
-* Allow unit tests to run on a remote server for PostgreSQL #781 *adamm@galacticasoftware.com*
-
-* Added web_service generator (run ./script/generate web_service for help) #776 *Leon Bredt*
-
-* Added app/apis and components to code statistics report #729 *Scott Barron*
-
-* Fixed WEBrick server to use ABSOLUTE_RAILS_ROOT instead of working_directory #687 *Nicholas Seckar*
-
-* Fixed rails_generator to be usable without RubyGems #686 *Cristi BALAN*
-
-* Fixed -h/--help for generate and destroy generators #331
-
-* Added begin/rescue around the FCGI dispatcher so no uncaught exceptions can bubble up to kill the process (logs to log/fastcgi.crash.log)
-
-* Fixed that association#count would produce invalid sql when called sequentialy #659 *kanis@comcard.de*
-
-* Fixed test/mocks/testing to the correct test/mocks/test #740
-
-* Added early failure if the Ruby version isn't 1.8.2 or above #735
-
-* Removed the obsolete -i/--index option from the WEBrick servlet #743
-
-* Upgraded to Active Record 1.8.0, Action Pack 1.5.1, Action Mailer 0.7.1, Action Web Service 0.6.0, Active Support 1.0.1
-
-
-## 0.10.0 (24th February, 2005) ##
-
-* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 *Marcel Molina Jr.*
-
-* Fixed that script/server -d was broken so daemon mode couldn't be used #687 *Nicholas Seckar*
-
-* Upgraded to breakpoint 92 which fixes:
-
- * overload IRB.parse_opts(), fixes #443
- => breakpoints in tests work even when running them via rake
- * untaint handlers, might fix an issue discussed on the Rails ML
- * added verbose mode to breakpoint_client
- * less noise caused by breakpoint_client by default
- * ignored TerminateLineInput exception in signal handler
- => quiet exit on Ctrl-C
-
-* Added support for independent components residing in /components. Example:
-
- Controller: components/list/items_controller.rb
- (holds a List::ItemsController class with uses_component_template_root called)
-
- Model : components/list/item.rb
- (namespace is still shared, so an Item model in app/models will take precedence)
-
- Views : components/list/items/show.rhtml
-
-
-* Added --sandbox option to script/console that'll roll back all changes made to the database when you quit #672 *Jeremy Kemper*
-
-* Added 'recent' as a rake target that'll run tests for files that changed in the last 10 minutes #612 *Jeremy Kemper*
-
-* Changed script/console to default to development environment and drop --no-inspect #650 *Jeremy Kemper*
-
-* Added that the 'fixture :posts' syntax can be used for has_and_belongs_to_many fixtures where a model doesn't exist #572 *Jeremy Kemper*
-
-* Added that running test_units and test_functional now performs the clone_structure_to_test as well #566 *rasputnik*
-
-* Added new generator framework that informs about its doings on generation and enables updating and destruction of generated artifacts. See the new script/destroy and script/update for more details #487 *Jeremy Kemper*
-
-* Added Action Web Service as a new add-on framework for Action Pack *Leon Bredt*
-
-* Added Active Support as an independent utility and standard library extension bundle
-
-* Upgraded to Active Record 1.7.0, Action Pack 1.5.0, Action Mailer 0.7.0
-
-
-## 0.9.5 (January 25th, 2005) ##
-
-* Fixed dependency reloading by switching to a remove_const approach where all Active Records, Active Record Observers, and Action Controllers are reloading by undefining their classes. This enables you to remove methods in all three types and see the change reflected immediately and it fixes #539. This also means that only those three types of classes will benefit from the const_missing and reloading approach. If you want other classes (like some in lib/) to reload, you must use require_dependency to do it.
-
-* Added Florian Gross' latest version of Breakpointer and friends that fixes a variaty of bugs #441 *Florian Gross*
-
-* Fixed skeleton Rakefile to work with sqlite3 out of the box #521 *rasputnik*
-
-* Fixed that script/breakpointer didn't get the Ruby path rewritten as the other scripts #523 *brandt@kurowski.net*
-
-* Fixed handling of syntax errors in models that had already been succesfully required once in the current interpreter
-
-* Fixed that models that weren't referenced in associations weren't being reloaded in the development mode by reinstating the reload
-
-* Fixed that generate scaffold would produce bad functional tests
-
-* Fixed that FCGI can also display SyntaxErrors
-
-* Upgraded to Active Record 1.6.0, Action Pack 1.4.0
-
-
-## 0.9.4.1 (January 18th, 2005) ##
-
-* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 *Marcel Molina Jr.*
-
-* Fixed binding of caller #496 *Alexey*
-
-* Upgraded to Active Record 1.5.1, Action Pack 1.3.1, Action Mailer 0.6.1
-
-
-## 0.9.4 (January 17th, 2005) ##
-
-* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller *Tobias Lütke*
-
-* Flipped code-to-test ratio around to be more readable #468 *Scott Baron*
-
-* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 *Lucas Carlson*
-
-* Fixed that auto reloading would some times not work or would reload the models twice #475 *Tobias Lütke*
-
-* Added rewrite rules to deal with caching to public/.htaccess
-
-* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
-
-* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
- RAILS_ENV instead of just forcing development #424 *Tobias Lütke*
-
-* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 *Chris McGrath*
-
-* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
-
-* Removed Fancy Indexing as a default option on the WEBrick servlet as it made it harder to use various caching schemes
-
-* Upgraded to Active Record 1.5, Action Pack 1.3, Action Mailer 0.6
-
-
-## 0.9.3 (January 4th, 2005) ##
-
-* Added support for SQLite in the auto-dumping/importing of schemas for development -> test #416
-
-* Added automated rewriting of the shebang lines on installs through the gem rails command #379 *Manfred Stienstra*
-
-* Added ActionMailer::Base.deliver_method = :test to the test environment so that mail objects are available in ActionMailer::Base.deliveries
- for functional testing.
-
-* Added protection for creating a model through the generators with a name of an existing class, like Thread or Date.
- It'll even offer you a synonym using wordnet.princeton.edu as a look-up. No, I'm not kidding :) *Florian Gross*
-
-* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
- the environment options needs to change from:
-
- Before in development.rb:
- ActionController::Base.reload_dependencies = true  
- ActiveRecord::Base.reload_associations     = true
-
- Now in development.rb:
- Dependencies.mechanism = :load
-
- Before in production.rb and test.rb:
- ActionController::Base.reload_dependencies = false
- ActiveRecord::Base.reload_associations     = false
-
- Now in production.rb and test.rb:
- Dependencies.mechanism = :require
-
-* Fixed problems with dependency caching and controller hierarchies on Ruby 1.8.2 in development mode #351
-
-* Fixed that generated action_mailers doesnt need to require the action_mailer since thats already done in the environment #382 *Lucas Carlson*
-
-* Upgraded to Action Pack 1.2.0 and Active Record 1.4.0
-
-
-## 0.9.2 ##
-
-* Fixed CTRL-C exists from the Breakpointer to be a clean affair without error dumping *Kent Sibilev*
-
-* Fixed "rake stats" to work with sub-directories in models and controllers and to report the code to test ration *Scott Baron*
-
-* Added that Active Record associations are now reloaded instead of cleared to work with the new const_missing hook in Active Record.
-
-* Added graceful handling of an inaccessible log file by redirecting output to STDERR with a warning #330 *rainmkr*
-
-* Added support for a -h/--help parameter in the generator #331 *Ulysses*
-
-* Fixed that File.expand_path in config/environment.rb would fail when dealing with symlinked public directories *mjobin*
-
-* Upgraded to Action Pack 1.1.0 and Active Record 1.3.0
-
-
-## 0.9.1 ##
-
-* Upgraded to Action Pack 1.0.1 for important bug fix
-
-* Updated gem dependencies
-
-
-## 0.9.0 ##
-
-* Renamed public/dispatch.servlet to script/server -- it wasn't really dispatching anyway as its delegating calls to public/dispatch.rb
-
-* Renamed AbstractApplicationController and abstract_application.rb to ApplicationController and application.rb, so that it will be possible
- for the framework to automatically pick up on app/views/layouts/application.rhtml and app/helpers/application.rb
-
-* Added script/console that makes it even easier to start an IRB session for interacting with the domain model. Run with no-args to
- see help.
-
-* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
- the code, investigate and change the model, AND then resume execution! Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find_all
- breakpoint "Breaking out from the list"
- end
- end
-
- So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
- Here you can do things like:
-
- Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
-
- >> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
- >> @posts.first.title = "hello from a breakpoint"
- => "hello from a breakpoint"
-
- ...and even better is that you can examine how your runtime objects actually work:
-
- >> f = @posts.first
- => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
- >> f.
- Display all 152 possibilities? (y or n)
-
- Finally, when you're ready to resume execution, you press CTRL-D
-
-* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
- can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
-
- SetEnv RAILS_ENV production
-
- ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
-
- ruby public/dispatcher.servlet -e production
-
-* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
-
-* Added a start_server in the root of the Rails application to make it even easier to get started
-
-* Fixed public/.htaccess to use RewriteBase and share the same rewrite rules for all the dispatch methods
-
-* Fixed webrick_server to handle requests in a serialized manner (the Rails reloading infrastructure is not thread-safe)
-
-* Added support for controllers in directories. So you can have:
-
- app/controllers/account_controller.rb # URL: /account/
- app/controllers/admin/account_controller.rb # URL: /admin/account/
-
- NOTE: You need to update your public/.htaccess with the new rules to pick it up
-
-* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
- those environments for development. This is turned on by default, but can be turned off with
- ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
-
-* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
-
- app/models/accounting
- app/models/project
- app/models/participants
- app/models/settings
-
- It's poor man's namespacing, but only for file-system organization. You still require files just like before.
- Nothing changes inside the files themselves.
-
-
-* Fixed a few references in the tests generated by new_mailer *Jeremy Kemper*
-
-* Added support for mocks in testing with test/mocks
-
-* Cleaned up the environments a bit and added global constant RAILS_ROOT
-
-
-## 0.8.5 (9) ##
-
-* Made dev-util available to all tests, so you can insert breakpoints in any test case to get an IRB prompt at that point [Jeremy Kemper]:
-
- def test_complex_stuff
- @david.projects << @new_project
- breakpoint "Let's have a closer look at @david"
- end
-
- You need to install dev-utils yourself for this to work ("gem install dev-util").
-
-* Added shared generator behavior so future upgrades should be possible without manually copying over files *Jeremy Kemper*
-
-* Added the new helper style to both controller and helper templates *Jeremy Kemper*
-
-* Added new_crud generator for creating a model and controller at the same time with explicit scaffolding *Jeremy Kemper*
-
-* Added configuration of Test::Unit::TestCase.fixture_path to test_helper to concide with the new AR fixtures style
-
-* Fixed that new_model was generating singular table/fixture names
-
-* Upgraded to Action Mailer 0.4.0
-
-* Upgraded to Action Pack 0.9.5
-
-* Upgraded to Active Record 1.1.0
-
-
-## 0.8.0 (15) ##
-
-* Removed custom_table_name option for new_model now that the Inflector is as powerful as it is
-
-* Changed the default rake action to just do testing and separate API generation and coding statistics into a "doc" task.
-
-* Fixed WEBrick dispatcher to handle missing slashes in the URLs gracefully *alexey*
-
-* Added user option for all postgresql tool calls in the rakefile *elvstone*
-
-* Fixed problem with running "ruby public/dispatch.servlet" instead of "cd public; ruby dispatch.servlet" *alexey*
-
-* Fixed WEBrick server so that it no longer hardcodes the ruby interpreter used to "ruby" but will get the one used based
- on the Ruby runtime configuration. *Marcel Molina Jr.*
-
-* Fixed Dispatcher so it'll route requests to magic_beans to MagicBeansController/magic_beans_controller.rb *Caio Chassot*
-
-* "new_controller MagicBeans" and "new_model SubscriptionPayments" will now both behave properly as they use the new Inflector.
-
-* Fixed problem with MySQL foreign key constraint checks in Rake :clone_production_structure_to_test target *Andreas Schwarz*
-
-* Changed WEBrick server to by default be auto-reloading, which is slower but makes source changes instant.
- Class compilation cache can be turned on with "-c" or "--cache-classes".
-
-* Added "-b/--binding" option to WEBrick dispatcher to bind the server to a specific IP address (default: 127.0.0.1) *Kevin Temp*
-
-* dispatch.fcgi now DOESN'T set FCGI_PURE_RUBY as it was slowing things down for now reason *Andreas Schwarz*
-
-* Added new_mailer generator to work with Action Mailer
-
-* Included new framework: Action Mailer 0.3
-
-* Upgraded to Action Pack 0.9.0
-
-* Upgraded to Active Record 1.0.0
-
-
-## 0.7.0 ##
-
-* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
- which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
- *Kevin Radloff*
-
-* script/new_model now turns AccountHolder into account_holder instead of accountholder *Kevin Radloff*
-
-* Fixed the faulty handleing of static files with WEBrick *Andreas Schwarz*
-
-* Unified function_test_helper and unit_test_helper into test_helper
-
-* Fixed bug with the automated production => test database dropping on PostgreSQL *dhawkins*
-
-* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
- and can generate more than one fixture at a time. Which makes it possible for assignments like:
-
- @people, @projects, @project_access, @companies, @accounts =
- create_fixtures "people", "projects", "project_access", "companies", "accounts"
-
-* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
-
-* Upgraded to Active Record 0.9.5 (better table_name guessing, cloning, find_all_in_collection)
-
-
-## 0.6.5 ##
-
-* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
-
-* The new_model generator will now use the same rules for plural wordings as Active Record
- (so Category will give categories, not categorys) *Kevin Radloff*
-
-* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded *danp*
-
-* Made the GEM work with Windows
-
-* Fixed bug where mod_ruby would "forget" the load paths added when switching between controllers
-
-* PostgreSQL are now supported for the automated production => test database dropping *Kevin Radloff*
-
-* Errors thrown by the dispatcher are now properly handled in FCGI.
-
-* Upgraded to Action Pack 0.8.0 (lots and lots and lots of fixes)
-
-* Upgraded to Active Record 0.9.4 (a bunch of fixes)
-
-
-## 0.6.0 ##
-
-* Added AbstractionApplicationController as a superclass for all controllers generated. This class can be used
- to carry filters and methods that are to be shared by all. It has an accompanying ApplicationHelper that all
- controllers will also automatically have available.
-
-* Added environments that can be included from any script to get the full Active Record and Action Controller
- context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
-
- require 'config/environments/production'
-
- for account in Account.find_all
- account.recalculate_interests
- end
-
- A short migration script for an account model that had it's interest calculation strategy changed.
-
-* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
-
-* Simplified the default Apache config so even remote requests are served off CGI as a default.
- You'll now have to do something specific to activate mod_ruby and FCGI (like using the force urls).
- This should make it easier for new comers that start on an external server.
-
-* Added more of the necessary Apache options to .htaccess to make it easier to setup
-
-* Upgraded to Action Pack 0.7.9 (lots of fixes)
-
-* Upgraded to Active Record 0.9.3 (lots of fixes)
-
-
-## 0.5.7 ##
-
-* Fixed bug in the WEBrick dispatcher that prevented it from getting parameters from the URL
- (through GET requests or otherwise)
-
-* Added lib in root as a place to store app specific libraries
-
-* Added lib and vendor to load_path, so anything store within can be loaded directly.
- Hence lib/redcloth.rb can be loaded with require "redcloth"
-
-* Upgraded to Action Pack 0.7.8 (lots of fixes)
-
-* Upgraded to Active Record 0.9.2 (minor upgrade)
-
-
-## 0.5.6 ##
-
-* Upgraded to Action Pack 0.7.7 (multipart form fix)
-
-* Updated the generated template stubs to valid XHTML files
-
-* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
- gives the same as "new_controller Todolists" and "new_controller todolists".
-
-
-## 0.5.5 ##
-
-* Works on Windows out of the box! (Dropped symlinks)
-
-* Added webrick dispatcher: Try "ruby public/dispatch.servlet --help" *Florian Gross*
-
-* Report errors about initialization to browser (instead of attempting to use uninitialized logger)
-
-* Upgraded to Action Pack 0.7.6
-
-* Upgraded to Active Record 0.9.1
-
-* Added distinct 500.html instead of reusing 404.html
-
-* Added MIT license
-
-
-## 0.5.0 ##
-
-* First public release
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/railties/CHANGELOG.md) for previous changes.
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index d5ec2cbfd9..80b8e4b9ba 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -16,7 +16,7 @@ module Rails
#
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
# the application object has several specific configurations, for example
- # "allow_concurrency", "cache_classes", "consider_all_requests_local", "filter_parameters",
+ # "cache_classes", "consider_all_requests_local", "filter_parameters",
# "logger" and so forth.
#
# Check Rails::Application::Configuration to see them all.
@@ -46,7 +46,7 @@ module Rails
# One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
# 9) Custom Railtie#initializers added by railties, engines and applications are executed
# 10) Build the middleware stack and run to_prepare callbacks
- # 11) Run config.before_eager_load and eager_load if cache classes is true
+ # 11) Run config.before_eager_load and eager_load! if eager_load is true
# 12) Run config.after_initialize callbacks
#
class Application < Engine
@@ -102,6 +102,17 @@ module Rails
# Stores some of the Rails initial environment parameters which
# will be used by middlewares and engines to configure themselves.
+ # Currently stores:
+ #
+ # * "action_dispatch.parameter_filter" => config.filter_parameters,
+ # * "action_dispatch.secret_token" => config.secret_token,
+ # * "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
+ # * "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
+ # * "action_dispatch.logger" => Rails.logger,
+ # * "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
+ #
+ # These parameters will be used by middlewares and engines to configure themselves
+ #
def env_config
@env_config ||= super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
@@ -177,7 +188,7 @@ module Rails
end
def queue #:nodoc:
- @queue ||= build_queue
+ @queue ||= Queueing::Container.new(build_queue)
end
def build_queue #:nodoc:
@@ -205,8 +216,9 @@ module Rails
railties.each { |r| r.run_tasks_blocks(app) }
super
require "rails/tasks"
+ config = self.config
task :environment do
- $rails_rake_task = true
+ config.eager_load = false
require_environment!
end
end
@@ -267,6 +279,7 @@ module Rails
def default_middleware_stack #:nodoc:
ActionDispatch::MiddlewareStack.new.tap do |middleware|
+ app = self
if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
require "action_dispatch/http/rack_cache"
middleware.use ::Rack::Cache, rack_cache
@@ -284,17 +297,16 @@ module Rails
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
end
- middleware.use ::Rack::Lock unless config.allow_concurrency
+ middleware.use ::Rack::Lock unless config.cache_classes
middleware.use ::Rack::Runtime
middleware.use ::Rack::MethodOverride
middleware.use ::ActionDispatch::RequestId
middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
- middleware.use ::ActionDispatch::DebugExceptions
+ middleware.use ::ActionDispatch::DebugExceptions, app
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
unless config.cache_classes
- app = self
middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
end
@@ -310,7 +322,7 @@ module Rails
end
middleware.use ::ActionDispatch::ParamsParser
- middleware.use ::ActionDispatch::Head
+ middleware.use ::Rack::Head
middleware.use ::Rack::ConditionalGet
middleware.use ::Rack::ETag, "no-cache"
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index e567df7162..a1bc95550b 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -13,11 +13,18 @@ module Rails
require "active_support/all" unless config.active_support.bare
end
- # Preload all frameworks specified by the Configuration#frameworks.
- # Used by Passenger to ensure everything's loaded before forking and
- # to avoid autoload race conditions in JRuby.
- initializer :preload_frameworks, :group => :all do
- ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
+ initializer :set_eager_load, :group => :all do
+ if config.eager_load.nil?
+ warn <<-INFO
+config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
+
+ * development - set it to false
+ * test - set it to false (unless you use a tool that preloads your test environment)
+ * production - set it to true
+
+INFO
+ config.eager_load = config.cache_classes
+ end
end
# Initialize the logger early in the stack in case we need to log some deprecation.
@@ -60,7 +67,6 @@ module Rails
end
# Sets the dependency loading mechanism.
- # TODO: Remove files from the $" and always use require.
initializer :initialize_dependency_mechanism, :group => :all do
ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
end
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index a2e5dece16..0202e86f32 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -5,13 +5,13 @@ require 'rails/engine/configuration'
module Rails
class Application
class Configuration < ::Rails::Engine::Configuration
- attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets, :autoflush_log,
+ attr_accessor :asset_host, :asset_path, :assets, :autoflush_log,
:cache_classes, :cache_store, :consider_all_requests_local, :console,
- :dependency_loading, :exceptions_app, :file_watcher, :filter_parameters,
+ :eager_load, :exceptions_app, :file_watcher, :filter_parameters,
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
- :preload_frameworks, :railties_order, :relative_url_root, :secret_token,
+ :railties_order, :relative_url_root, :secret_token,
:serve_static_assets, :ssl_options, :static_cache_control, :session_options,
- :time_zone, :reload_classes_only_on_change, :use_schema_cache_dump,
+ :time_zone, :reload_classes_only_on_change,
:queue, :queue_consumer
attr_writer :log_level
@@ -20,11 +20,9 @@ module Rails
def initialize(*)
super
self.encoding = "utf-8"
- @allow_concurrency = false
@consider_all_requests_local = false
@filter_parameters = []
@helpers_paths = []
- @dependency_loading = true
@serve_static_assets = true
@static_cache_control = nil
@force_ssl = false
@@ -43,14 +41,14 @@ module Rails
@exceptions_app = nil
@autoflush_log = true
@log_formatter = ActiveSupport::Logger::SimpleFormatter.new
- @use_schema_cache_dump = true
@queue = Rails::Queueing::Queue
@queue_consumer = Rails::Queueing::ThreadedConsumer
+ @eager_load = nil
@assets = ActiveSupport::OrderedOptions.new
@assets.enabled = false
@assets.paths = []
- @assets.precompile = [ Proc.new{ |path| !File.extname(path).in?(['.js', '.css']) },
+ @assets.precompile = [ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) },
/(?:\/|\\|\A)application\.(css|js)$/ ]
@assets.prefix = "/assets"
@assets.version = ''
@@ -92,15 +90,12 @@ module Rails
end
end
- # Enable threaded mode. Allows concurrent requests to controller actions and
- # multiple database connections. Also disables automatic dependency loading
- # after boot, and disables reloading code on every request, as these are
- # fundamentally incompatible with thread safety.
def threadsafe!
- @preload_frameworks = true
+ ActiveSupport::Deprecation.warn "config.threadsafe! is deprecated. Rails applications " \
+ "behave by default as thread safe in production as long as config.cache_classes and " \
+ "config.eager_load are set to true"
@cache_classes = true
- @dependency_loading = false
- @allow_concurrency = true
+ @eager_load = true
self
end
@@ -131,7 +126,12 @@ module Rails
when :disabled
nil
when :active_record_store
- ActiveRecord::SessionStore
+ begin
+ ActionDispatch::Session::ActiveRecordStore
+ rescue NameError
+ raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \
+ "Please add `activerecord-session_store` to your Gemfile to use it."
+ end
when Symbol
ActionDispatch::Session.const_get(@session_store.to_s.camelize)
else
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index 60aa40b92f..777f0d269e 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -50,9 +50,9 @@ module Rails
end
initializer :eager_load! do
- if config.cache_classes && !(defined?($rails_rake_task) && $rails_rake_task)
+ if config.eager_load
ActiveSupport.run_load_hooks(:before_eager_load, self)
- eager_load!
+ config.eager_load_namespaces.each(&:eager_load!)
end
end
@@ -91,7 +91,7 @@ module Rails
# Disable dependency loading during request cycle
initializer :disable_dependency_loading do
- if config.cache_classes && !config.dependency_loading
+ if config.eager_load && config.cache_classes
ActiveSupport::Dependencies.unhook!
end
end
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index 8816387d34..9c5dc8f188 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/object/inclusion'
-
ARGV << '--help' if ARGV.empty?
aliases = {
@@ -71,7 +69,7 @@ when 'application', 'runner'
require "rails/commands/#{command}"
when 'new'
- if ARGV.first.in?(['-h', '--help'])
+ if %w(-h --help).include?(ARGV.first)
require 'rails/commands/application'
else
puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
@@ -84,7 +82,7 @@ when '--version', '-v'
require 'rails/commands/application'
else
- puts "Error: Command not recognized" unless command.in?(['-h', '--help'])
+ puts "Error: Command not recognized" unless %w(-h --help).include?(command)
puts <<-EOT
Usage: rails COMMAND [ARGS]
diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb
index ae354eca97..9023c61bf2 100644
--- a/railties/lib/rails/commands/destroy.rb
+++ b/railties/lib/rails/commands/destroy.rb
@@ -1,7 +1,6 @@
require 'rails/generators'
-require 'active_support/core_ext/object/inclusion'
-if ARGV.first.in?([nil, "-h", "--help"])
+if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'destroy'
exit
end
diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb
index 1fb2d98834..9f13cb0513 100644
--- a/railties/lib/rails/commands/generate.rb
+++ b/railties/lib/rails/commands/generate.rb
@@ -1,7 +1,6 @@
require 'rails/generators'
-require 'active_support/core_ext/object/inclusion'
-if ARGV.first.in?([nil, "-h", "--help"])
+if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'generate'
exit
end
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index 9ef64da3ef..a684129353 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -87,6 +87,15 @@ module Rails
middlewares = []
middlewares << [Rails::Rack::Debugger] if options[:debugger]
middlewares << [::Rack::ContentLength]
+
+ # FIXME: add Rack::Lock in the case people are using webrick.
+ # This is to remain backwards compatible for those who are
+ # running webrick in production. We should consider removing this
+ # in development.
+ if server.name == 'Rack::Handler::WEBrick'
+ middlewares << [::Rack::Lock]
+ end
+
Hash.new(middlewares)
end
diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb
index ee8bb55f38..2a69c26deb 100644
--- a/railties/lib/rails/console/app.rb
+++ b/railties/lib/rails/console/app.rb
@@ -1,9 +1,6 @@
require 'active_support/all'
-require 'active_support/test_case'
require 'action_controller'
-# work around the at_exit hook in test/unit, which kills IRB
-
module Rails
module ConsoleMethods
# reference the global "app" instance, created on demand. To recreate the
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 383c159d3d..3a5caf9f62 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -176,8 +176,7 @@ module Rails
#
# * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
# it's used as default :as option
- # * some of the rake tasks are based on engine name, e.g. <tt>my_engine:install:migrations</tt>,
- # <tt>my_engine:install:assets</tt>
+ # * rake task for installing migrations <tt>my_engine:install:migrations</tt>
#
# Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
# <tt>my_engine_engine</tt>. You can change it manually using the <tt>engine_name</tt> method:
@@ -340,11 +339,16 @@ module Rails
class << self
attr_accessor :called_from, :isolated
+
alias :isolated? :isolated
alias :engine_name :railtie_name
+ delegate :eager_load!, to: :instance
+
def inherited(base)
unless base.abstract_railtie?
+ Rails::Railtie::Configuration.eager_load_namespaces << base
+
base.called_from = begin
# Remove the line number from backtraces making sure we don't leave anything behind
call_stack = caller.map { |p| p.sub(/:\d+.*/, '') }
@@ -495,7 +499,11 @@ module Rails
# Define the Rack API for this engine.
def call(env)
- app.call(env.merge!(env_config))
+ env.merge!(env_config)
+ if env['SCRIPT_NAME']
+ env.merge! "ROUTES_#{routes.object_id}_SCRIPT_NAME" => env['SCRIPT_NAME'].dup
+ end
+ app.call(env)
end
# Defines additional Rack env configuration that is added on each call.
diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb
index ffbc0b4bd6..072d16291b 100644
--- a/railties/lib/rails/engine/commands.rb
+++ b/railties/lib/rails/engine/commands.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/object/inclusion'
-
ARGV << '--help' if ARGV.empty?
aliases = {
@@ -25,7 +23,7 @@ when '--version', '-v'
require 'rails/commands/application'
else
- puts "Error: Command not recognized" unless command.in?(['-h', '--help'])
+ puts "Error: Command not recognized" unless %w(-h --help).include?(command)
puts <<-EOT
Usage: rails COMMAND [ARGS]
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 4fa990171d..a8c0626a41 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -173,7 +173,6 @@ module Rails
"#{orm}:migration",
"#{orm}:model",
"#{orm}:observer",
- "#{orm}:session_migration",
"#{test}:controller",
"#{test}:helper",
"#{test}:integration",
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 5838c9fc38..d69afcd2cb 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -140,14 +140,14 @@ module Rails
gem 'rails', path: '#{Rails::Generators::RAILS_DEV_PATH}'
gem 'journey', github: 'rails/journey'
gem 'arel', github: 'rails/arel'
- gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders'
+ gem 'activerecord-deprecated_finders', github: 'rails/activerecord-deprecated_finders'
GEMFILE
elsif options.edge?
<<-GEMFILE.strip_heredoc
gem 'rails', github: 'rails/rails'
gem 'journey', github: 'rails/journey'
gem 'arel', github: 'rails/arel'
- gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders'
+ gem 'activerecord-deprecated_finders', github: 'rails/activerecord-deprecated_finders'
GEMFILE
else
<<-GEMFILE.strip_heredoc
@@ -246,8 +246,15 @@ module Rails
# is easier to silence stdout in the existing test suite this way. The
# end-user gets the bundler commands called anyway, so no big deal.
#
+ # We unset temporary bundler variables to load proper bundler and Gemfile.
+ #
# Thanks to James Tucker for the Gem tricks involved in this call.
- print `"#{Gem.ruby}" "#{Gem.bin_path('bundler', 'bundle')}" #{command}`
+ _bundle_command = Gem.bin_path('bundler', 'bundle')
+
+ require 'bundler'
+ Bundler.with_clean_env do
+ print `"#{Gem.ruby}" "#{_bundle_command}" #{command}`
+ end
end
def run_bundle
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index a49a1724c5..a3f8ebf476 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -8,7 +8,6 @@ rescue LoadError
end
require 'rails/generators/actions'
-require 'active_support/core_ext/object/inclusion'
module Rails
module Generators
@@ -171,7 +170,7 @@ module Rails
names.each do |name|
defaults = if options[:type] == :boolean
{ }
- elsif default_value_for_option(name, options).in?([true, false])
+ elsif [true, false].include?(default_value_for_option(name, options))
{ :banner => "" }
else
{ :desc => "#{name.to_s.humanize} to be invoked", :banner => "NAME" }
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
index d78d97b2b4..f5182bcc50 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
@@ -19,7 +19,7 @@
<% end -%>
<td><%%= link_to 'Show', <%= singular_table_name %> %></td>
<td><%%= link_to 'Edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %></td>
- <td><%%= link_to 'Destroy', <%= singular_table_name %>, confirm: 'Are you sure?', method: :delete %></td>
+ <td><%%= link_to 'Destroy', <%= singular_table_name %>, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<%% end %>
</tbody>
</table>
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb
index d480fc12b5..d2c2abf40c 100644
--- a/railties/lib/rails/generators/generated_attribute.rb
+++ b/railties/lib/rails/generators/generated_attribute.rb
@@ -8,6 +8,7 @@ module Rails
attr_accessor :name, :type
attr_reader :attr_options
+ attr_writer :index_name
class << self
def parse(column_definition)
@@ -89,18 +90,26 @@ module Rails
end
end
+ def plural_name
+ name.sub(/_id$/, '').pluralize
+ end
+
def human_name
- name.to_s.humanize
+ name.humanize
end
def index_name
- if reference?
+ @index_name ||= if reference?
polymorphic? ? %w(id type).map { |t| "#{name}_#{t}" } : "#{name}_id"
else
name
end
end
+ def foreign_key?
+ !!(name =~ /_id$/)
+ end
+
def reference?
self.class.reference?(type)
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index 5915d20010..1ac0248bcf 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -27,9 +27,6 @@ module <%= app_const_base %>
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
- # Activate observers that should always be running.
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
@@ -54,11 +51,6 @@ module <%= app_const_base %>
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
<%= comment_if :skip_active_record %>config.active_record.whitelist_attributes = true
-
- # Specifies whether or not has_many or has_one association option :dependent => :restrict raises
- # an exception. If set to true, then an ActiveRecord::DeleteRestrictionError exception would be
- # raised. If set to false, then an error will be added on the model instead.
- <%= comment_if :skip_active_record %>config.active_record.dependent_restrict_raises = false
<% unless options.skip_sprockets? -%>
# Enable the asset pipeline.
@@ -68,7 +60,7 @@ module <%= app_const_base %>
config.assets.version = '1.0'
<% end -%>
- # Enable app-wide asynchronous ActionMailer
+ # Enable app-wide asynchronous ActionMailer.
# config.action_mailer.async = true
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environment.rb b/railties/lib/rails/generators/rails/app/templates/config/environment.rb
index 1684986a59..e080ebd74e 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environment.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/environment.rb
@@ -1,5 +1,5 @@
-# Load the rails application
+# Load the rails application.
require File.expand_path('../application', __FILE__)
-# Initialize the rails application
+# Initialize the rails application.
<%= app_const %>.initialize!
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 01f9396403..122e7e2b34 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -6,6 +6,9 @@
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
+ # Do not eager load code on boot.
+ config.eager_load = false
+
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
@@ -35,10 +38,10 @@
# Do not compress assets.
config.assets.compress = false
- # Expands the lines which load the assets.
+ # Debug mode disables concatenation and preprocessing of assets.
config.assets.debug = true
<%- end -%>
- # In development, use an in-memory queue for queueing
+ # In development, use an in-memory queue for queueing.
config.queue = Rails::Queueing::Queue
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index 072aa8355d..a627636089 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -4,6 +4,12 @@
# Code is not reloaded between requests.
config.cache_classes = true
+ # Eager load code on boot. This eager loads most of Rails and
+ # your application in memory, allowing both thread web servers
+ # and those relying on copy on write to perform better.
+ # Rake tasks automatically ignore this option for performance.
+ config.eager_load = true
+
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
@@ -20,9 +26,6 @@
# Generate digests for assets URLs.
config.assets.digest = true
-
- # Defaults to nil and saved in location specified by config.assets.prefix
- # config.assets.manifest = YOUR_PATH
<%- end -%>
# Specifies the header that your server uses for sending files.
@@ -74,10 +77,10 @@
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
- # Use default logging formatter so that PID and timestamp are not suppressed
+ # Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Default the production mode queue to an in-memory queue. You will probably
- # want to replace this with an out-of-process queueing solution
+ # want to replace this with an out-of-process queueing solution.
config.queue = Rails::Queueing::Queue
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index b27b88a3c6..8ab27eb6e1 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -7,6 +7,11 @@
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
+ # Do not eager load code on boot. This avoids loading your whole application
+ # just for the purpose of running a single test. If you are using a tool that
+ # preloads Rails for running tests, you may have to set it to true.
+ config.eager_load = false
+
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
@@ -34,6 +39,6 @@
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
- # Use the testing queue
+ # Use the testing queue.
config.queue = Rails::Queueing::TestQueue
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb
index 5d8d9be237..9262c3379f 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb
@@ -1,8 +1,9 @@
# Be sure to restart your server when you modify this file.
-# Add new inflection rules using the following format
-# (all these examples are active by default):
-# ActiveSupport::Inflector.inflections do |inflect|
+# Add new inflection rules using the following format. Inflections
+# are locale specific, and you may define rules for as many different
+# locales as you wish. All of these examples are active by default:
+# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
@@ -10,6 +11,6 @@
# end
#
# These inflection rules are supported but not enabled by default:
-# ActiveSupport::Inflector.inflections do |inflect|
+# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
index e02397aaf9..3c5611ca59 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
@@ -2,8 +2,11 @@
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
+
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
+# You can use `rake secret` to generate a secure secret key.
+
# Make sure your secret_token is kept private
# if you're sharing your code publicly.
<%= app_const %>.config.secret_token = '<%= app_secret %>'
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
index ade0c4f78c..4a099a4ce2 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
@@ -1,8 +1,3 @@
# Be sure to restart your server when you modify this file.
<%= app_const %>.config.session_store :cookie_store, key: <%= "'_#{app_name}_session'" %>
-
-# Use the database for sessions instead of the cookie-based default,
-# which shouldn't be used to store highly confidential information
-# (create the session table with "rails generate session_migration")
-# <%= app_const %>.config.session_store :active_record_store
diff --git a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
index 179c14ca52..0653957166 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
@@ -1,5 +1,23 @@
-# Sample localization file for English. Add more files in this directory for other locales.
-# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+# Files in the config/locales directory are used for internationalization
+# and are automatically loaded by Rails. If you want to use locales other
+# than English, add the necessary files in this directory.
+#
+# To use the locales, use `I18n.t`:
+#
+# I18n.t 'hello'
+#
+# In views, this is aliased to just `t`:
+#
+# <%= t('hello') %>
+#
+# To use a different locale, set it with `I18n.locale`:
+#
+# I18n.locale = :es
+#
+# This would use the information in config/locales/es.yml.
+#
+# To learn more, please read the Rails Internationalization guide
+# available at http://guides.rubyonrails.org/i18n.html.
en:
hello: "Hello world"
diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
index 85acac6725..f6b1ef1feb 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -8,11 +8,11 @@
# Sample of regular route:
# get 'products/:id' => 'catalog#view'
- # Keep in mind you can assign values other than :controller and :action
+ # Keep in mind you can assign values other than :controller and :action.
# Sample of named route:
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
- # This route can be invoked with purchase_url(id: product.id)
+ # This route can be invoked with purchase_url(id: product.id).
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
@@ -35,7 +35,7 @@
# resource :seller
# end
- # Sample resource route with more complex sub-resources
+ # Sample resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
@@ -51,5 +51,5 @@
# end
- # See how all your routes lay out with "rake routes"
+ # See how all your routes lay out with "rake routes".
end
diff --git a/railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt b/railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt
deleted file mode 100644
index f081e08b6c..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt
+++ /dev/null
@@ -1,7 +0,0 @@
-# See more about this file at: http://humanstxt.org/
-# For format suggestions, see: http://humanstxt.org/Standard.html
-/* TEAM */
-
-/* APP */
- Name: <%= app_const_base %>
- Software: Ruby on Rails
diff --git a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb
index 9342a57b20..d09ce5ad34 100644
--- a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb
+++ b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb
@@ -6,7 +6,7 @@ class BrowsingTest < ActionDispatch::PerformanceTest
# self.profile_options = { runs: 5, metrics: [:wall_time, :memory],
# output: 'tmp/performance', formats: [:flat] }
- def test_homepage
+ test "homepage" do
get '/'
end
end
diff --git a/railties/lib/rails/generators/rails/controller/USAGE b/railties/lib/rails/generators/rails/controller/USAGE
index 70618a3906..b658777b12 100644
--- a/railties/lib/rails/generators/rails/controller/USAGE
+++ b/railties/lib/rails/generators/rails/controller/USAGE
@@ -9,10 +9,10 @@ Description:
template engine and test framework generators.
Example:
- `rails generate controller CreditCard open debit credit close`
+ `rails generate controller CreditCards open debit credit close`
- Credit card controller with URLs like /credit_card/debit.
- Controller: app/controllers/credit_card_controller.rb
- Functional Test: test/functional/credit_card_controller_test.rb
- Views: app/views/credit_card/debit.html.erb [...]
- Helper: app/helpers/credit_card_helper.rb
+ CreditCards controller with URLs like /credit_cards/debit.
+ Controller: app/controllers/credit_cards_controller.rb
+ Functional Test: test/functional/credit_cards_controller_test.rb
+ Views: app/views/credit_cards/debit.html.erb [...]
+ Helper: app/helpers/credit_cards_helper.rb
diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
index ab0e440bc4..4f937ad65a 100644
--- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -155,7 +155,7 @@ task :default => :test
:desc => "Create dummy application at given path"
class_option :full, :type => :boolean, :default => false,
- :desc => "Generate rails engine with integration tests"
+ :desc => "Generate a rails engine with bundled Rails application for testing"
class_option :mountable, :type => :boolean, :default => false,
:desc => "Generate mountable isolated application"
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/USAGE b/railties/lib/rails/generators/rails/scaffold_controller/USAGE
index 673f69bc81..5cd51b62d4 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/USAGE
+++ b/railties/lib/rails/generators/rails/scaffold_controller/USAGE
@@ -1,8 +1,7 @@
Description:
- Stubs out a scaffolded controller and its views. Pass the model name,
- either CamelCased or under_scored, and a list of views as arguments.
- The controller name is retrieved as a pluralized version of the model
- name.
+ Stubs out a scaffolded controller, its seven RESTful actions and related
+ views. Pass the model name, either CamelCased or under_scored. The
+ controller name is retrieved as a pluralized version of the model name.
To create a controller within a module, specify the model name as a
path like 'parent_module/controller_name'.
diff --git a/railties/lib/rails/generators/rails/session_migration/USAGE b/railties/lib/rails/generators/rails/session_migration/USAGE
deleted file mode 100644
index 564d1ffd78..0000000000
--- a/railties/lib/rails/generators/rails/session_migration/USAGE
+++ /dev/null
@@ -1,8 +0,0 @@
-Description:
- Creates a migration to add the sessions table used by the ORM session store.
- Pass the migration name, either CamelCased or under_scored, as an argument.
-
- Before invoking this generator, be sure that your ORM supports session stores.
-
-Example:
- `rails generate session_migration CreateSessionTable`
diff --git a/railties/lib/rails/generators/rails/session_migration/session_migration_generator.rb b/railties/lib/rails/generators/rails/session_migration/session_migration_generator.rb
deleted file mode 100644
index 258cc5b4a0..0000000000
--- a/railties/lib/rails/generators/rails/session_migration/session_migration_generator.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-module Rails
- module Generators
- class SessionMigrationGenerator < NamedBase #metagenerator
- argument :name, :type => :string, :default => "add_sessions_table"
- hook_for :orm, :required => true
- end
- end
-end
diff --git a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb
index 370750a175..2f25dcf832 100644
--- a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb
+++ b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb
@@ -6,7 +6,7 @@ class <%= class_name %>Test < ActionDispatch::PerformanceTest
# self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory],
# :output => 'tmp/performance', :formats => [:flat] }
- def test_homepage
+ test "homepage" do
get '/'
end
end
diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb
index bacdcbf3aa..512803aeac 100644
--- a/railties/lib/rails/info_controller.rb
+++ b/railties/lib/rails/info_controller.rb
@@ -1,4 +1,4 @@
-require 'rails/application/routes_inspector'
+require 'action_dispatch/routing/inspector'
class Rails::InfoController < ActionController::Base
self.view_paths = File.join(File.dirname(__FILE__), 'templates')
@@ -15,7 +15,7 @@ class Rails::InfoController < ActionController::Base
end
def routes
- inspector = Rails::Application::RoutesInspector.new
+ inspector = ActionDispatch::Routing::RoutesInspector.new
@info = inspector.format(_routes.routes).join("\n")
end
diff --git a/railties/lib/rails/queueing.rb b/railties/lib/rails/queueing.rb
index 8a76914548..baf6811d3e 100644
--- a/railties/lib/rails/queueing.rb
+++ b/railties/lib/rails/queueing.rb
@@ -1,7 +1,34 @@
require "thread"
+require 'delegate'
module Rails
module Queueing
+ # A container for multiple queues. This class delegates to a default Queue
+ # so that <tt>Rails.queue.push</tt> and friends will Just Work. To use this class
+ # with multiple queues:
+ #
+ # # In your configuration:
+ # Rails.queue[:image_queue] = SomeQueue.new
+ # Rails.queue[:mail_queue] = SomeQueue.new
+ #
+ # # In your app code:
+ # Rails.queue[:mail_queue].push SomeJob.new
+ #
+ class Container < DelegateClass(::Queue)
+ def initialize(default_queue)
+ @queues = { :default => default_queue }
+ super(default_queue)
+ end
+
+ def [](queue_name)
+ @queues[queue_name]
+ end
+
+ def []=(queue_name, queue)
+ @queues[queue_name] = queue
+ end
+ end
+
# A Queue that simply inherits from STDLIB's Queue. Everytime this
# queue is used, Rails automatically sets up a ThreadedConsumer
# to consume it.
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index 1cb99463cc..fba685c769 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -178,9 +178,6 @@ module Rails
@config ||= Railtie::Configuration.new
end
- def eager_load!
- end
-
def railtie_namespace
@railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
end
diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb
index 1c6b3769a5..9dc8843887 100644
--- a/railties/lib/rails/railtie/configuration.rb
+++ b/railties/lib/rails/railtie/configuration.rb
@@ -7,6 +7,16 @@ module Rails
@@options ||= {}
end
+ # Expose the eager_load_namespaces at "module" level for convenience.
+ def self.eager_load_namespaces #:nodoc:
+ @@eager_load_namespaces ||= []
+ end
+
+ # All namespaces that are eager loaded
+ def eager_load_namespaces
+ @@eager_load_namespaces ||= []
+ end
+
# Add files that should be watched for change.
def watchable_files
@@watchable_files ||= []
diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake
index 0dcca36d8b..0a9b9ff4ff 100644
--- a/railties/lib/rails/tasks/misc.rake
+++ b/railties/lib/rails/tasks/misc.rake
@@ -1,10 +1,3 @@
-task :rails_env do
- # TODO Do we really need this?
- unless defined? RAILS_ENV
- RAILS_ENV = ENV['RAILS_ENV'] ||= 'development'
- end
-end
-
desc 'Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions).'
task :secret do
require 'securerandom'
diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake
index 4ade825616..95f47566ef 100644
--- a/railties/lib/rails/tasks/routes.rake
+++ b/railties/lib/rails/tasks/routes.rake
@@ -1,7 +1,7 @@
desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.'
task :routes => :environment do
all_routes = Rails.application.routes.routes
- require 'rails/application/routes_inspector'
- inspector = Rails::Application::RoutesInspector.new
+ require 'action_dispatch/routing/inspector'
+ inspector = ActionDispatch::Routing::RoutesInspector.new
puts inspector.format(all_routes, ENV['CONTROLLER']).join "\n"
end
diff --git a/railties/lib/rails/tasks/tmp.rake b/railties/lib/rails/tasks/tmp.rake
index 0d6c10328f..0968765b4f 100644
--- a/railties/lib/rails/tasks/tmp.rake
+++ b/railties/lib/rails/tasks/tmp.rake
@@ -2,10 +2,16 @@ namespace :tmp do
desc "Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)"
task :clear => [ "tmp:sessions:clear", "tmp:cache:clear", "tmp:sockets:clear"]
+ tmp_dirs = [ 'tmp/sessions',
+ 'tmp/cache',
+ 'tmp/sockets',
+ 'tmp/pids',
+ 'tmp/cache/assets' ]
+
+ tmp_dirs.each { |d| directory d }
+
desc "Creates tmp directories for sessions, cache, sockets, and pids"
- task :create do
- FileUtils.mkdir_p(%w( tmp/sessions tmp/cache tmp/sockets tmp/pids tmp/cache/assets ))
- end
+ task :create => tmp_dirs
namespace :sessions do
# desc "Clears all files in tmp/sessions"
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 4243a79b58..c29fa4d95f 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -106,20 +106,28 @@ module ApplicationTests
precompile!
images_should_compile.each do |filename|
- assert File.exists?("#{app_path}/public/assets/#{filename}")
+ assert_file_exists "#{app_path}/public/assets/#{filename}"
end
- assert File.exists?("#{app_path}/public/assets/application.js")
- assert File.exists?("#{app_path}/public/assets/application.css")
+ assert_file_exists("#{app_path}/public/assets/application.js")
+ assert_file_exists("#{app_path}/public/assets/application.css")
+
+ assert_no_file_exists("#{app_path}/public/assets/someapplication.js")
+ assert_no_file_exists("#{app_path}/public/assets/someapplication.css")
- assert !File.exists?("#{app_path}/public/assets/someapplication.js")
- assert !File.exists?("#{app_path}/public/assets/someapplication.css")
+ assert_no_file_exists("#{app_path}/public/assets/something.min.js")
+ assert_no_file_exists("#{app_path}/public/assets/something.min.css")
- assert !File.exists?("#{app_path}/public/assets/something.min.js")
- assert !File.exists?("#{app_path}/public/assets/something.min.css")
+ assert_no_file_exists("#{app_path}/public/assets/something.else.js")
+ assert_no_file_exists("#{app_path}/public/assets/something.else.css")
+ end
+
+ def assert_file_exists(filename)
+ assert File.exists?(filename), "missing #{filename}"
+ end
- assert !File.exists?("#{app_path}/public/assets/something.else.js")
- assert !File.exists?("#{app_path}/public/assets/something.else.css")
+ def assert_no_file_exists(filename)
+ assert !File.exists?(filename), "#{filename} does exist"
end
test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do
@@ -233,7 +241,7 @@ module ApplicationTests
get '/posts'
assert_match(/AssetNotPrecompiledError/, last_response.body)
- assert_match(/app.js isn't precompiled/, last_response.body)
+ assert_match(/app.js isn&#x27;t precompiled/, last_response.body)
end
test "assets raise AssetNotPrecompiledError when manifest file is present and requested file isn't precompiled if digest is disabled" do
@@ -257,7 +265,7 @@ module ApplicationTests
get '/posts'
assert_match(/AssetNotPrecompiledError/, last_response.body)
- assert_match(/app.js isn't precompiled/, last_response.body)
+ assert_match(/app.js isn&#x27;t precompiled/, last_response.body)
end
test "precompile properly refers files referenced with asset_path and and run in the provided RAILS_ENV" do
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index c813defe93..039b08c723 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -139,22 +139,19 @@ module ApplicationTests
assert_instance_of Pathname, Rails.root
end
- test "marking the application as threadsafe sets the correct config variables" do
+ test "initialize an eager loaded, cache classes app" do
add_to_config <<-RUBY
- config.threadsafe!
+ config.eager_load = true
+ config.cache_classes = true
RUBY
require "#{app_path}/config/application"
- assert AppTemplate::Application.config.allow_concurrency
+ assert AppTemplate::Application.initialize!
end
- test "initialize a threadsafe app" do
- add_to_config <<-RUBY
- config.threadsafe!
- RUBY
-
+ test "application is always added to eager_load namespaces" do
require "#{app_path}/config/application"
- assert AppTemplate::Application.initialize!
+ assert AppTemplate::Application, AppTemplate::Application.config.eager_load_namespaces
end
test "asset_path defaults to nil for application" do
@@ -162,10 +159,11 @@ module ApplicationTests
assert_equal nil, AppTemplate::Application.config.asset_path
end
- test "the application can be marked as threadsafe when there are no frameworks" do
+ test "the application can be eager loaded even when there are no frameworks" do
FileUtils.rm_rf("#{app_path}/config/environments")
add_to_config <<-RUBY
- config.threadsafe!
+ config.eager_load = true
+ config.cache_classes = true
RUBY
use_frameworks []
@@ -175,22 +173,6 @@ module ApplicationTests
end
end
- test "frameworks are not preloaded by default" do
- require "#{app_path}/config/environment"
-
- assert ActionController.autoload?(:Caching)
- end
-
- test "frameworks are preloaded with config.preload_frameworks is set" do
- add_to_config <<-RUBY
- config.preload_frameworks = true
- RUBY
-
- require "#{app_path}/config/environment"
-
- assert !ActionView.autoload?(:AssetPaths)
- end
-
test "filter_parameters should be able to set via config.filter_parameters" do
add_to_config <<-RUBY
config.filter_parameters += [ :foo, 'bar', lambda { |key, value|
@@ -648,5 +630,24 @@ module ApplicationTests
ActiveRecord::Base
assert defined?(FooObserver)
end
+
+ test "config.session_store with :active_record_store with activerecord-session_store gem" do
+ begin
+ make_basic_app do |app|
+ ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore)
+ app.config.session_store :active_record_store
+ end
+ ensure
+ ActionDispatch::Session.send :remove_const, :ActiveRecordStore
+ end
+ end
+
+ test "config.session_store with :active_record_store without activerecord-session_store gem" do
+ assert_raise RuntimeError, /activerecord-session_store/ do
+ make_basic_app do |app|
+ app.config.session_store :active_record_store
+ end
+ end
+ end
end
end
diff --git a/railties/test/application/initializers/boot_test.rb b/railties/test/application/initializers/boot_test.rb
index 04c46058cb..7eda15894e 100644
--- a/railties/test/application/initializers/boot_test.rb
+++ b/railties/test/application/initializers/boot_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class GemBooting < ActiveSupport::TestCase
+ class BootTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index c2d4a0f2c8..d3bbac811c 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -163,26 +163,6 @@ module ApplicationTests
end
# AR
- test "database middleware doesn't initialize when session store is not active_record" do
- add_to_config <<-RUBY
- config.root = "#{app_path}"
- config.session_store :cookie_store, { :key => "blahblahblah" }
- RUBY
- require "#{app_path}/config/environment"
-
- assert !Rails.application.config.middleware.include?(ActiveRecord::SessionStore)
- end
-
- test "database middleware initializes when session store is active record" do
- add_to_config "config.session_store :active_record_store"
-
- require "#{app_path}/config/environment"
-
- expects = [ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActiveRecord::SessionStore]
- middleware = Rails.application.config.middleware.map { |m| m.klass }
- assert_equal expects, middleware & expects
- end
-
test "active_record extensions are applied to ActiveRecord" do
add_to_config "config.active_record.table_name_prefix = 'tbl_'"
require "#{app_path}/config/environment"
diff --git a/railties/test/application/initializers/hooks_test.rb b/railties/test/application/initializers/hooks_test.rb
index 7b3e6844fd..b2cea0a8e1 100644
--- a/railties/test/application/initializers/hooks_test.rb
+++ b/railties/test/application/initializers/hooks_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class InitializersTest < ActiveSupport::TestCase
+ class HooksTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -20,11 +20,11 @@ module ApplicationTests
assert $foo
end
- test "hooks block works correctly without cache classes (before_eager_load is not called)" do
+ test "hooks block works correctly without eager_load (before_eager_load is not called)" do
add_to_config <<-RUBY
$initialization_callbacks = []
config.root = "#{app_path}"
- config.cache_classes = false
+ config.eager_load = false
config.before_configuration { $initialization_callbacks << 1 }
config.before_initialize { $initialization_callbacks << 2 }
config.before_eager_load { Boom }
@@ -35,11 +35,11 @@ module ApplicationTests
assert_equal [1,2,3], $initialization_callbacks
end
- test "hooks block works correctly with cache classes" do
+ test "hooks block works correctly with eager_load" do
add_to_config <<-RUBY
$initialization_callbacks = []
config.root = "#{app_path}"
- config.cache_classes = true
+ config.eager_load = true
config.before_configuration { $initialization_callbacks << 1 }
config.before_initialize { $initialization_callbacks << 2 }
config.before_eager_load { $initialization_callbacks << 3 }
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
index 54b18542c2..19d3f3a397 100644
--- a/railties/test/application/middleware/cache_test.rb
+++ b/railties/test/application/middleware/cache_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class RoutingTest < ActiveSupport::TestCase
+ class CacheTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb
index d1a614e181..42096cfec4 100644
--- a/railties/test/application/middleware/exceptions_test.rb
+++ b/railties/test/application/middleware/exceptions_test.rb
@@ -88,9 +88,6 @@ module ApplicationTests
end
test "displays diagnostics message when exception raised in template that contains UTF-8" do
- app.config.action_dispatch.show_exceptions = true
- app.config.consider_all_requests_local = true
-
controller :foo, <<-RUBY
class FooController < ActionController::Base
def index
@@ -98,18 +95,15 @@ module ApplicationTests
end
RUBY
+ app.config.action_dispatch.show_exceptions = true
+ app.config.consider_all_requests_local = true
+
app_file 'app/views/foo/index.html.erb', <<-ERB
<% raise 'boooom' %>
✓測試テスト시험
ERB
- app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do
- post ':controller(/:action)'
- end
- RUBY
-
- post '/foo', :utf8 => '✓'
+ get '/foo', :utf8 => '✓'
assert_match(/boooom/, last_response.body)
assert_match(/測試テスト시험/, last_response.body)
end
diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb
index 066f0c1c84..9d97bae9ae 100644
--- a/railties/test/application/middleware/remote_ip_test.rb
+++ b/railties/test/application/middleware/remote_ip_test.rb
@@ -4,20 +4,6 @@ module ApplicationTests
class RemoteIpTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
- def setup
- build_app
- boot_rails
- FileUtils.rm_rf "#{app_path}/config/environments"
- end
-
- def teardown
- teardown_app
- end
-
- def app
- @app ||= Rails.application
- end
-
def remote_ip(env = {})
remote_ip = nil
env = Rack::MockRequest.env_for("/").merge(env).merge!(
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index ba747bc633..3e096e99f2 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -1,6 +1,4 @@
require 'isolation/abstract_unit'
-require 'stringio'
-require 'rack/test'
module ApplicationTests
class MiddlewareTest < ActiveSupport::TestCase
@@ -45,7 +43,7 @@ module ApplicationTests
"ActionDispatch::Session::CookieStore",
"ActionDispatch::Flash",
"ActionDispatch::ParamsParser",
- "ActionDispatch::Head",
+ "Rack::Head",
"Rack::ConditionalGet",
"Rack::ETag",
"ActionDispatch::BestStandardsSupport"
@@ -87,8 +85,8 @@ module ApplicationTests
assert !middleware.include?("ActiveRecord::QueryCache")
end
- test "removes lock if allow concurrency is set" do
- add_to_config "config.allow_concurrency = true"
+ test "removes lock if cache classes is set" do
+ add_to_config "config.cache_classes = true"
boot!
assert !middleware.include?("Rack::Lock")
end
diff --git a/railties/test/application/queue_test.rb b/railties/test/application/queue_test.rb
index 22d6c20404..c856089540 100644
--- a/railties/test/application/queue_test.rb
+++ b/railties/test/application/queue_test.rb
@@ -1,8 +1,7 @@
require 'isolation/abstract_unit'
-require 'rack/test'
module ApplicationTests
- class GeneratorsTest < ActiveSupport::TestCase
+ class QueueTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -20,14 +19,14 @@ module ApplicationTests
test "the queue is a TestQueue in test mode" do
app("test")
- assert_kind_of Rails::Queueing::TestQueue, Rails.application.queue
- assert_kind_of Rails::Queueing::TestQueue, Rails.queue
+ assert_kind_of Rails::Queueing::TestQueue, Rails.application.queue[:default]
+ assert_kind_of Rails::Queueing::TestQueue, Rails.queue[:default]
end
test "the queue is a Queue in development mode" do
app("development")
- assert_kind_of Rails::Queueing::Queue, Rails.application.queue
- assert_kind_of Rails::Queueing::Queue, Rails.queue
+ assert_kind_of Rails::Queueing::Queue, Rails.application.queue[:default]
+ assert_kind_of Rails::Queueing::Queue, Rails.queue[:default]
end
class ThreadTrackingJob
@@ -144,7 +143,7 @@ module ApplicationTests
test "a custom queue implementation can be provided" do
setup_custom_queue
- assert_kind_of MyQueue, Rails.queue
+ assert_kind_of MyQueue, Rails.queue[:default]
job = Struct.new(:id, :ran) do
def run
diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb
index 46fd09cb26..2f5bd3a764 100644
--- a/railties/test/application/rack/logger_test.rb
+++ b/railties/test/application/rack/logger_test.rb
@@ -26,12 +26,18 @@ module ApplicationTests
@logs ||= @logger.logged(:info)
end
- test "logger logs proper HTTP verb and path" do
+ test "logger logs proper HTTP GET verb and path" do
get "/blah"
wait
assert_match(/^Started GET "\/blah"/, logs[0])
end
+ test "logger logs proper HTTP HEAD verb and path" do
+ head "/blah"
+ wait
+ assert_match(/^Started HEAD "\/blah"/, logs[0])
+ end
+
test "logger logs HTTP verb override" do
post "/", {:_method => 'put'}
wait
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index a450f90dbf..b05fe3aed5 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -55,6 +55,29 @@ module ApplicationTests
assert_match "Doing something...", output
end
+ def test_does_not_explode_when_accessing_a_model_with_eager_load
+ add_to_config <<-RUBY
+ config.eager_load = true
+
+ rake_tasks do
+ task :do_nothing => :environment do
+ Hello.new.world
+ end
+ end
+ RUBY
+
+ app_file "app/models/hello.rb", <<-RUBY
+ class Hello
+ def world
+ puts "Hello world"
+ end
+ end
+ RUBY
+
+ output = Dir.chdir(app_path){ `rake do_nothing` }
+ assert_match "Hello world", output
+ end
+
def test_code_statistics_sanity
assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0",
Dir.chdir(app_path){ `rake stats` }
diff --git a/railties/test/application/routes_inspect_test.rb b/railties/test/application/routes_inspect_test.rb
deleted file mode 100644
index 68a8afc93e..0000000000
--- a/railties/test/application/routes_inspect_test.rb
+++ /dev/null
@@ -1,168 +0,0 @@
-require 'minitest/autorun'
-require 'rails/application/routes_inspector'
-require 'action_controller'
-require 'rails/engine'
-
-module ApplicationTests
- class RoutesInspectTest < ActiveSupport::TestCase
- def setup
- @set = ActionDispatch::Routing::RouteSet.new
- @inspector = Rails::Application::RoutesInspector.new
- app = ActiveSupport::OrderedOptions.new
- app.config = ActiveSupport::OrderedOptions.new
- app.config.assets = ActiveSupport::OrderedOptions.new
- app.config.assets.prefix = '/sprockets'
- Rails.stubs(:application).returns(app)
- Rails.stubs(:env).returns("development")
- end
-
- def draw(&block)
- @set.draw(&block)
- @inspector.format(@set.routes)
- end
-
- def test_displaying_routes_for_engines
- engine = Class.new(Rails::Engine) do
- def self.to_s
- "Blog::Engine"
- end
- end
- engine.routes.draw do
- get '/cart', :to => 'cart#show'
- end
-
- output = draw do
- get '/custom/assets', :to => 'custom_assets#show'
- mount engine => "/blog", :as => "blog"
- end
-
- expected = [
- "custom_assets GET /custom/assets(.:format) custom_assets#show",
- " blog /blog Blog::Engine",
- "\nRoutes for Blog::Engine:",
- "cart GET /cart(.:format) cart#show"
- ]
- assert_equal expected, output
- end
-
- def test_cart_inspect
- output = draw do
- get '/cart', :to => 'cart#show'
- end
- assert_equal ["cart GET /cart(.:format) cart#show"], output
- end
-
- def test_inspect_shows_custom_assets
- output = draw do
- get '/custom/assets', :to => 'custom_assets#show'
- end
- assert_equal ["custom_assets GET /custom/assets(.:format) custom_assets#show"], output
- end
-
- def test_inspect_routes_shows_resources_route
- output = draw do
- resources :articles
- end
- expected = [
- " articles GET /articles(.:format) articles#index",
- " POST /articles(.:format) articles#create",
- " new_article GET /articles/new(.:format) articles#new",
- "edit_article GET /articles/:id/edit(.:format) articles#edit",
- " article GET /articles/:id(.:format) articles#show",
- " PATCH /articles/:id(.:format) articles#update",
- " PUT /articles/:id(.:format) articles#update",
- " DELETE /articles/:id(.:format) articles#destroy" ]
- assert_equal expected, output
- end
-
- def test_inspect_routes_shows_root_route
- output = draw do
- root :to => 'pages#main'
- end
- assert_equal ["root GET / pages#main"], output
- end
-
- def test_inspect_routes_shows_dynamic_action_route
- output = draw do
- get 'api/:action' => 'api'
- end
- assert_equal [" GET /api/:action(.:format) api#:action"], output
- end
-
- def test_inspect_routes_shows_controller_and_action_only_route
- output = draw do
- get ':controller/:action'
- end
- assert_equal [" GET /:controller/:action(.:format) :controller#:action"], output
- end
-
- def test_inspect_routes_shows_controller_and_action_route_with_constraints
- output = draw do
- get ':controller(/:action(/:id))', :id => /\d+/
- end
- assert_equal [" GET /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"], output
- end
-
- def test_rake_routes_shows_route_with_defaults
- output = draw do
- get 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
- end
- assert_equal [%Q[ GET /photos/:id(.:format) photos#show {:format=>"jpg"}]], output
- end
-
- def test_rake_routes_shows_route_with_constraints
- output = draw do
- get 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
- end
- assert_equal [" GET /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"], output
- end
-
- class RackApp
- def self.call(env)
- end
- end
-
- def test_rake_routes_shows_route_with_rack_app
- output = draw do
- get 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
- end
- assert_equal [" GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output
- end
-
- def test_rake_routes_shows_route_with_rack_app_nested_with_dynamic_constraints
- constraint = Class.new do
- def to_s
- "( my custom constraint )"
- end
- end
-
- output = draw do
- scope :constraint => constraint.new do
- mount RackApp => '/foo'
- end
- end
-
- assert_equal [" /foo #{RackApp.name} {:constraint=>( my custom constraint )}"], output
- end
-
- def test_rake_routes_dont_show_app_mounted_in_assets_prefix
- output = draw do
- get '/sprockets' => RackApp
- end
- assert_no_match(/RackApp/, output.first)
- assert_no_match(/\/sprockets/, output.first)
- end
-
- def test_redirect
- output = draw do
- get "/foo" => redirect("/foo/bar"), :constraints => { :subdomain => "admin" }
- get "/bar" => redirect(path: "/foo/bar", status: 307)
- get "/foobar" => redirect{ "/foo/bar" }
- end
-
- assert_equal " foo GET /foo(.:format) redirect(301, /foo/bar) {:subdomain=>\"admin\"}", output[0]
- assert_equal " bar GET /bar(.:format) redirect(307, path: /foo/bar)", output[1]
- assert_equal "foobar GET /foobar(.:format) redirect(301)", output[2]
- end
- end
-end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 5534476a6d..c294bfb238 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -213,7 +213,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_no_file "config/database.yml"
assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
assert_file "config/application.rb", /#\s+config\.active_record\.whitelist_attributes = true/
- assert_file "config/application.rb", /#\s+config\.active_record\.dependent_restrict_raises = false/
assert_file "test/test_helper.rb" do |helper_content|
assert_no_match(/fixtures :all/, helper_content)
end
@@ -367,21 +366,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "config/application.rb", /config\.active_record\.whitelist_attributes = true/
end
- def test_active_record_dependent_restrict_raises_is_present_application_config
- run_generator
- assert_file "config/application.rb", /config\.active_record\.dependent_restrict_raises = false/
- end
-
def test_pretend_option
output = run_generator [File.join(destination_root, "myapp"), "--pretend"]
assert_no_match(/run bundle install/, output)
end
- def test_humans_txt_file
- run_generator [File.join(destination_root, 'things-43')]
- assert_file "things-43/public/humans.txt", /Name: Things43/, /Software: Ruby on Rails/
- end
-
protected
def action(*args, &block)
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index b320e40654..774038c0e1 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -76,6 +76,23 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_remove_migration_with_references_options
+ migration = "remove_references_from_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :up, content do |up|
+ assert_match(/remove_reference :books, :author/, up)
+ assert_match(/remove_reference :books, :distributor, polymorphic: true/, up)
+ end
+
+ assert_method :down, content do |down|
+ assert_match(/add_reference :books, :author, index: true/, down)
+ assert_match(/add_reference :books, :distributor, polymorphic: true, index: true/, down)
+ end
+ end
+ end
+
def test_add_migration_with_attributes_and_indices
migration = "add_title_with_index_and_body_to_posts"
run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"]
@@ -138,6 +155,31 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_migration_with_references_options
+ migration = "add_references_to_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/add_reference :books, :author, index: true/, up)
+ assert_match(/add_reference :books, :distributor, polymorphic: true, index: true/, up)
+ end
+ end
+ end
+
+ def test_create_join_table_migration
+ migration = "add_media_join_table"
+ run_generator [migration, "artist_id", "musics:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/create_join_table :artists, :musics/, up)
+ assert_match(/# t.index \[:artist_id, :music_id\]/, up)
+ assert_match(/ t.index \[:music_id, :artist_id\], unique: true/, up)
+ end
+ end
+ end
+
def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove
migration = "create_books"
run_generator [migration, "title:string", "content:text"]
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index 6c3e0178f2..bfb20dad2d 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -115,7 +115,13 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
end
def test_generation_runs_bundle_install_with_full_and_mountable
- result = run_generator [destination_root, "--mountable", "--full"]
+ result = run_generator [destination_root, "--mountable", "--full", "--dev"]
+ assert_file "#{destination_root}/Gemfile.lock" do |contents|
+ assert_match(/bukkits/, contents)
+ end
+ assert_match(/run bundle install/, result)
+ assert_match(/Using bukkits \(0\.0\.1\)/, result)
+ assert_match(/Your bundle is complete/, result)
assert_equal 1, result.scan("Your bundle is complete").size
end
@@ -394,4 +400,3 @@ protected
silence(:stdout){ generator.send(*args, &block) }
end
end
-
diff --git a/railties/test/generators/session_migration_generator_test.rb b/railties/test/generators/session_migration_generator_test.rb
deleted file mode 100644
index b590047ff0..0000000000
--- a/railties/test/generators/session_migration_generator_test.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-require 'generators/generators_test_helper'
-require 'rails/generators/rails/session_migration/session_migration_generator'
-
-class SessionMigrationGeneratorTest < Rails::Generators::TestCase
- include GeneratorsTestHelper
-
- def test_session_migration_with_default_name
- run_generator
- assert_migration "db/migrate/add_sessions_table.rb", /class AddSessionsTable < ActiveRecord::Migration/
- end
-
- def test_session_migration_with_given_name
- run_generator ["create_session_table"]
- assert_migration "db/migrate/create_session_table.rb", /class CreateSessionTable < ActiveRecord::Migration/
- end
-
- def test_session_migration_with_custom_table_name
- ActiveRecord::SessionStore::Session.table_name = "custom_table_name"
- run_generator
- assert_migration "db/migrate/add_sessions_table.rb" do |migration|
- assert_match(/class AddSessionsTable < ActiveRecord::Migration/, migration)
- assert_match(/create_table :custom_table_name/, migration)
- end
- ensure
- ActiveRecord::SessionStore::Session.table_name = "sessions"
- end
-end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index ad2f85a5ff..027d8eb9b7 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -167,7 +167,7 @@ class GeneratorsTest < Rails::Generators::TestCase
def test_developer_options_are_overwriten_by_user_options
Rails::Generators.options[:with_options] = { :generate => false }
- self.class.class_eval <<-end_eval
+ self.class.class_eval(<<-end_eval, __FILE__, __LINE__ + 1)
class WithOptionsGenerator < Rails::Generators::Base
class_option :generate, :default => true
end
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 6071cd3f39..07a7faa3af 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -8,11 +8,10 @@
# Rails booted up.
require 'fileutils'
-require 'bundler/setup'
+require 'bundler/setup' unless defined?(Bundler)
require 'minitest/autorun'
require 'active_support/test_case'
-# TODO: Remove setting this magic constant
RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..")
# These files do not require any others and are needed
@@ -106,8 +105,9 @@ module TestHelpers
end
end
- unless options[:gemfile]
- File.delete"#{app_path}/Gemfile"
+ gemfile_path = "#{app_path}/Gemfile"
+ if options[:gemfile].blank? && File.exist?(gemfile_path)
+ File.delete gemfile_path
end
routes = File.read("#{app_path}/config/routes.rb")
@@ -118,6 +118,7 @@ module TestHelpers
end
add_to_config <<-RUBY
+ config.eager_load = false
config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
config.session_store :cookie_store, :key => "_myapp_session"
config.active_support.deprecation = :log
@@ -136,6 +137,7 @@ module TestHelpers
require "action_controller/railtie"
app = Class.new(Rails::Application)
+ app.config.eager_load = false
app.config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
app.config.session_store :cookie_store, :key => "_myapp_session"
app.config.active_support.deprecation = :log
@@ -253,7 +255,6 @@ module TestHelpers
:activerecord] - arr
if to_remove.include? :activerecord
remove_from_config "config.active_record.whitelist_attributes = true"
- remove_from_config "config.active_record.dependent_restrict_raises = false"
end
$:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
end
@@ -281,8 +282,7 @@ Module.new do
environment = File.expand_path('../../../../load_paths', __FILE__)
require_environment = "-r #{environment}"
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{app_template_path}`
-
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{app_template_path} --skip-gemfile`
File.open("#{app_template_path}/config/boot.rb", 'w') do |f|
f.puts "require '#{environment}'"
f.puts "require 'rails/all'"
diff --git a/railties/test/queueing/container_test.rb b/railties/test/queueing/container_test.rb
new file mode 100644
index 0000000000..69e59a3871
--- /dev/null
+++ b/railties/test/queueing/container_test.rb
@@ -0,0 +1,30 @@
+require 'abstract_unit'
+require 'rails/queueing'
+
+module Rails
+ module Queueing
+ class ContainerTest < ActiveSupport::TestCase
+ def test_delegates_to_default
+ q = Queue.new
+ container = Container.new q
+ job = Object.new
+
+ container.push job
+ assert_equal job, q.pop
+ end
+
+ def test_access_default
+ q = Queue.new
+ container = Container.new q
+ assert_equal q, container[:default]
+ end
+
+ def test_assign_queue
+ container = Container.new Object.new
+ q = Object.new
+ container[:foo] = q
+ assert_equal q, container[:foo]
+ end
+ end
+ end
+end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 63814f7a04..e52b3efdab 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -1193,6 +1193,54 @@ YAML
last_response.body.split("\n").map(&:strip)
end
+ test "paths are properly generated when application is mounted at sub-path" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ app_file "app/controllers/bar_controller.rb", <<-RUBY
+ class BarController < ApplicationController
+ def index
+ render :text => bukkits.bukkit_path
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/bar' => 'bar#index', :as => 'bar'
+ mount Bukkits::Engine => "/bukkits", :as => "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ get '/bukkit' => 'bukkit#index'
+ end
+ RUBY
+
+
+ @plugin.write "app/controllers/bukkits/bukkit_controller.rb", <<-RUBY
+ class Bukkits::BukkitController < ActionController::Base
+ def index
+ render :text => main_app.bar_path
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ get("/bukkits/bukkit", {}, {'SCRIPT_NAME' => '/foo'})
+ assert_equal '/foo/bar', last_response.body
+
+ get("/bar", {}, {'SCRIPT_NAME' => '/foo'})
+ assert_equal '/foo/bukkits/bukkit', last_response.body
+ end
+
private
def app
Rails.application
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
index 4c0fdee556..bd13c3aba3 100644
--- a/railties/test/railties/mounted_engine_test.rb
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -163,24 +163,14 @@ module ApplicationTests
end
end
- def reset_script_name!
- Rails.application.routes.default_url_options = {}
- end
-
- def script_name(script_name)
- Rails.application.routes.default_url_options = {:script_name => script_name}
- end
-
test "routes generation in engine and application" do
# test generating engine's route from engine
get "/john/blog/posts"
assert_equal "/john/blog/posts/1", last_response.body
# test generating engine's route from engine with default_url_options
- script_name "/foo"
get "/john/blog/posts", {}, 'SCRIPT_NAME' => "/foo"
assert_equal "/foo/john/blog/posts/1", last_response.body
- reset_script_name!
# test generating engine's route from application
get "/engine_route"
@@ -193,14 +183,11 @@ module ApplicationTests
assert_equal "/john/blog/posts", last_response.body
# test generating engine's route from application with default_url_options
- script_name "/foo"
get "/engine_route", {}, 'SCRIPT_NAME' => "/foo"
assert_equal "/foo/anonymous/blog/posts", last_response.body
- script_name "/foo"
get "/url_for_engine_route", {}, 'SCRIPT_NAME' => "/foo"
assert_equal "/foo/john/blog/posts", last_response.body
- reset_script_name!
# test generating application's route from engine
get "/someone/blog/generate_application_route"
@@ -210,10 +197,8 @@ module ApplicationTests
assert_equal "/", last_response.body
# test generating application's route from engine with default_url_options
- script_name "/foo"
get "/someone/blog/generate_application_route", {}, 'SCRIPT_NAME' => '/foo'
assert_equal "/foo/", last_response.body
- reset_script_name!
# test polymorphic routes
get "/polymorphic_route"